diff --git a/src/FIPA/AgentIDHelper.java b/src/FIPA/AgentIDHelper.java index 7a8c338..5985e1f 100644 --- a/src/FIPA/AgentIDHelper.java +++ b/src/FIPA/AgentIDHelper.java @@ -8,6 +8,8 @@ package FIPA; public class AgentIDHelper { + private static org.omg.CORBA.TypeCode _tc; + // It is useless to have instances of this class private AgentIDHelper() { } @@ -72,8 +74,6 @@ public static void insert(org.omg.CORBA.Any a, AgentID that) { a.read_value(out.create_input_stream(), type()); } - private static org.omg.CORBA.TypeCode _tc; - synchronized public static org.omg.CORBA.TypeCode type() { int _memberCount = 4; org.omg.CORBA.StructMember[] _members = null; diff --git a/src/FIPA/AgentIDsHelper.java b/src/FIPA/AgentIDsHelper.java index 8c27cde..72c790d 100644 --- a/src/FIPA/AgentIDsHelper.java +++ b/src/FIPA/AgentIDsHelper.java @@ -8,6 +8,8 @@ package FIPA; public class AgentIDsHelper { + private static org.omg.CORBA.TypeCode _tc; + // It is useless to have instances of this class private AgentIDsHelper() { } @@ -45,8 +47,6 @@ public static void insert(org.omg.CORBA.Any a, AgentID[] that) { a.read_value(out.create_input_stream(), type()); } - private static org.omg.CORBA.TypeCode _tc; - synchronized public static org.omg.CORBA.TypeCode type() { if (_tc == null) _tc = org.omg.CORBA.ORB.init().create_alias_tc(id(), "AgentIDs", org.omg.CORBA.ORB.init().create_sequence_tc(0, AgentIDHelper.type())); diff --git a/src/FIPA/DateTimeHelper.java b/src/FIPA/DateTimeHelper.java index ebc4b5f..58b39d5 100644 --- a/src/FIPA/DateTimeHelper.java +++ b/src/FIPA/DateTimeHelper.java @@ -8,6 +8,8 @@ package FIPA; public class DateTimeHelper { + private static org.omg.CORBA.TypeCode _tc; + // It is useless to have instances of this class private DateTimeHelper() { } @@ -47,8 +49,6 @@ public static void insert(org.omg.CORBA.Any a, DateTime that) { a.read_value(out.create_input_stream(), type()); } - private static org.omg.CORBA.TypeCode _tc; - synchronized public static org.omg.CORBA.TypeCode type() { int _memberCount = 8; org.omg.CORBA.StructMember[] _members = null; diff --git a/src/FIPA/EnvelopeHelper.java b/src/FIPA/EnvelopeHelper.java index 989e6b6..6508184 100644 --- a/src/FIPA/EnvelopeHelper.java +++ b/src/FIPA/EnvelopeHelper.java @@ -8,6 +8,8 @@ package FIPA; public class EnvelopeHelper { + private static org.omg.CORBA.TypeCode _tc; + // It is useless to have instances of this class private EnvelopeHelper() { } @@ -174,8 +176,6 @@ public static void insert(org.omg.CORBA.Any a, Envelope that) { a.read_value(out.create_input_stream(), type()); } - private static org.omg.CORBA.TypeCode _tc; - synchronized public static org.omg.CORBA.TypeCode type() { int _memberCount = 12; org.omg.CORBA.StructMember[] _members = null; diff --git a/src/FIPA/EnvelopesHelper.java b/src/FIPA/EnvelopesHelper.java index a8bb5df..095fd53 100644 --- a/src/FIPA/EnvelopesHelper.java +++ b/src/FIPA/EnvelopesHelper.java @@ -8,6 +8,8 @@ package FIPA; public class EnvelopesHelper { + private static org.omg.CORBA.TypeCode _tc; + // It is useless to have instances of this class private EnvelopesHelper() { } @@ -45,8 +47,6 @@ public static void insert(org.omg.CORBA.Any a, Envelope[] that) { a.read_value(out.create_input_stream(), type()); } - private static org.omg.CORBA.TypeCode _tc; - synchronized public static org.omg.CORBA.TypeCode type() { if (_tc == null) _tc = org.omg.CORBA.ORB.init().create_alias_tc(id(), "Envelopes", org.omg.CORBA.ORB.init().create_sequence_tc(0, EnvelopeHelper.type())); diff --git a/src/FIPA/FipaMessageHelper.java b/src/FIPA/FipaMessageHelper.java index 0e61522..261e38c 100644 --- a/src/FIPA/FipaMessageHelper.java +++ b/src/FIPA/FipaMessageHelper.java @@ -8,6 +8,8 @@ package FIPA; public class FipaMessageHelper { + private static org.omg.CORBA.TypeCode _tc; + // It is useless to have instances of this class private FipaMessageHelper() { } @@ -53,8 +55,6 @@ public static void insert(org.omg.CORBA.Any a, FipaMessage that) { a.read_value(out.create_input_stream(), type()); } - private static org.omg.CORBA.TypeCode _tc; - synchronized public static org.omg.CORBA.TypeCode type() { int _memberCount = 2; org.omg.CORBA.StructMember[] _members = null; diff --git a/src/FIPA/MTSHelper.java b/src/FIPA/MTSHelper.java index c566fda..028ee6b 100644 --- a/src/FIPA/MTSHelper.java +++ b/src/FIPA/MTSHelper.java @@ -8,6 +8,8 @@ package FIPA; public class MTSHelper { + private static org.omg.CORBA.TypeCode _tc; + // It is useless to have instances of this class private MTSHelper() { } @@ -31,8 +33,6 @@ public static void insert(org.omg.CORBA.Any a, MTS that) { a.read_value(out.create_input_stream(), type()); } - private static org.omg.CORBA.TypeCode _tc; - synchronized public static org.omg.CORBA.TypeCode type() { if (_tc == null) _tc = org.omg.CORBA.ORB.init().create_interface_tc(id(), "MTS"); diff --git a/src/FIPA/OptAgentIDHelper.java b/src/FIPA/OptAgentIDHelper.java index 0414fac..d8229e7 100644 --- a/src/FIPA/OptAgentIDHelper.java +++ b/src/FIPA/OptAgentIDHelper.java @@ -8,6 +8,8 @@ package FIPA; public class OptAgentIDHelper { + private static org.omg.CORBA.TypeCode _tc; + // It is useless to have instances of this class private OptAgentIDHelper() { } @@ -51,8 +53,6 @@ public static void insert(org.omg.CORBA.Any a, AgentID[] that) { a.read_value(out.create_input_stream(), type()); } - private static org.omg.CORBA.TypeCode _tc; - synchronized public static org.omg.CORBA.TypeCode type() { if (_tc == null) _tc = org.omg.CORBA.ORB.init().create_alias_tc(id(), "OptAgentID", org.omg.CORBA.ORB.init().create_sequence_tc((int) (1L), AgentIDHelper.type())); diff --git a/src/FIPA/OptDateTimeHelper.java b/src/FIPA/OptDateTimeHelper.java index f66fdfc..c957dcc 100644 --- a/src/FIPA/OptDateTimeHelper.java +++ b/src/FIPA/OptDateTimeHelper.java @@ -8,6 +8,8 @@ package FIPA; public class OptDateTimeHelper { + private static org.omg.CORBA.TypeCode _tc; + // It is useless to have instances of this class private OptDateTimeHelper() { } @@ -51,8 +53,6 @@ public static void insert(org.omg.CORBA.Any a, DateTime[] that) { a.read_value(out.create_input_stream(), type()); } - private static org.omg.CORBA.TypeCode _tc; - synchronized public static org.omg.CORBA.TypeCode type() { if (_tc == null) _tc = org.omg.CORBA.ORB.init().create_alias_tc(id(), "OptDateTime", org.omg.CORBA.ORB.init().create_sequence_tc((int) (1L), DateTimeHelper.type())); diff --git a/src/FIPA/OptReceivedObjectHelper.java b/src/FIPA/OptReceivedObjectHelper.java index 65f96cd..6e7eb28 100644 --- a/src/FIPA/OptReceivedObjectHelper.java +++ b/src/FIPA/OptReceivedObjectHelper.java @@ -8,6 +8,8 @@ package FIPA; public class OptReceivedObjectHelper { + private static org.omg.CORBA.TypeCode _tc; + // It is useless to have instances of this class private OptReceivedObjectHelper() { } @@ -51,8 +53,6 @@ public static void insert(org.omg.CORBA.Any a, ReceivedObject[] that) { a.read_value(out.create_input_stream(), type()); } - private static org.omg.CORBA.TypeCode _tc; - synchronized public static org.omg.CORBA.TypeCode type() { if (_tc == null) _tc = org.omg.CORBA.ORB.init().create_alias_tc(id(), "OptReceivedObject", org.omg.CORBA.ORB.init().create_sequence_tc((int) (1L), ReceivedObjectHelper.type())); diff --git a/src/FIPA/OptTransportBehaviourTypeHelper.java b/src/FIPA/OptTransportBehaviourTypeHelper.java index 74cf9da..98ab5a8 100644 --- a/src/FIPA/OptTransportBehaviourTypeHelper.java +++ b/src/FIPA/OptTransportBehaviourTypeHelper.java @@ -8,6 +8,8 @@ package FIPA; public class OptTransportBehaviourTypeHelper { + private static org.omg.CORBA.TypeCode _tc; + // It is useless to have instances of this class private OptTransportBehaviourTypeHelper() { } @@ -58,8 +60,6 @@ public static void insert(org.omg.CORBA.Any a, Property[][] that) { a.read_value(out.create_input_stream(), type()); } - private static org.omg.CORBA.TypeCode _tc; - synchronized public static org.omg.CORBA.TypeCode type() { if (_tc == null) _tc = org.omg.CORBA.ORB.init().create_alias_tc(id(), "OptTransportBehaviourType", org.omg.CORBA.ORB.init().create_sequence_tc((int) (1L), org.omg.CORBA.ORB.init().create_sequence_tc(0, PropertyHelper.type()))); diff --git a/src/FIPA/PayloadHelper.java b/src/FIPA/PayloadHelper.java index da256a1..27c2082 100644 --- a/src/FIPA/PayloadHelper.java +++ b/src/FIPA/PayloadHelper.java @@ -8,6 +8,8 @@ package FIPA; public class PayloadHelper { + private static org.omg.CORBA.TypeCode _tc; + // It is useless to have instances of this class private PayloadHelper() { } @@ -41,8 +43,6 @@ public static void insert(org.omg.CORBA.Any a, byte[] that) { a.read_value(out.create_input_stream(), type()); } - private static org.omg.CORBA.TypeCode _tc; - synchronized public static org.omg.CORBA.TypeCode type() { if (_tc == null) _tc = org.omg.CORBA.ORB.init().create_alias_tc(id(), "Payload", org.omg.CORBA.ORB.init().create_sequence_tc(0, org.omg.CORBA.ORB.init().get_primitive_tc(org.omg.CORBA.TCKind.tk_octet))); diff --git a/src/FIPA/PropertyHelper.java b/src/FIPA/PropertyHelper.java index 8c7538c..66d0bcc 100644 --- a/src/FIPA/PropertyHelper.java +++ b/src/FIPA/PropertyHelper.java @@ -8,6 +8,8 @@ package FIPA; public class PropertyHelper { + private static org.omg.CORBA.TypeCode _tc; + // It is useless to have instances of this class private PropertyHelper() { } @@ -35,8 +37,6 @@ public static void insert(org.omg.CORBA.Any a, Property that) { a.read_value(out.create_input_stream(), type()); } - private static org.omg.CORBA.TypeCode _tc; - synchronized public static org.omg.CORBA.TypeCode type() { int _memberCount = 2; org.omg.CORBA.StructMember[] _members = null; diff --git a/src/FIPA/ReceivedObjectHelper.java b/src/FIPA/ReceivedObjectHelper.java index dcea84f..6717fa8 100644 --- a/src/FIPA/ReceivedObjectHelper.java +++ b/src/FIPA/ReceivedObjectHelper.java @@ -8,6 +8,8 @@ package FIPA; public class ReceivedObjectHelper { + private static org.omg.CORBA.TypeCode _tc; + // It is useless to have instances of this class private ReceivedObjectHelper() { } @@ -41,8 +43,6 @@ public static void insert(org.omg.CORBA.Any a, ReceivedObject that) { a.read_value(out.create_input_stream(), type()); } - private static org.omg.CORBA.TypeCode _tc; - synchronized public static org.omg.CORBA.TypeCode type() { int _memberCount = 5; org.omg.CORBA.StructMember[] _members = null; diff --git a/src/FIPA/TransportBehaviourTypeHelper.java b/src/FIPA/TransportBehaviourTypeHelper.java index 2a7f1f0..1509aac 100644 --- a/src/FIPA/TransportBehaviourTypeHelper.java +++ b/src/FIPA/TransportBehaviourTypeHelper.java @@ -8,6 +8,8 @@ package FIPA; public class TransportBehaviourTypeHelper { + private static org.omg.CORBA.TypeCode _tc; + // It is useless to have instances of this class private TransportBehaviourTypeHelper() { } @@ -45,8 +47,6 @@ public static void insert(org.omg.CORBA.Any a, Property[] that) { a.read_value(out.create_input_stream(), type()); } - private static org.omg.CORBA.TypeCode _tc; - synchronized public static org.omg.CORBA.TypeCode type() { if (_tc == null) _tc = org.omg.CORBA.ORB.init().create_alias_tc(id(), "TransportBehaviourType", org.omg.CORBA.ORB.init().create_sequence_tc(0, PropertyHelper.type())); diff --git a/src/FIPA/URLHelper.java b/src/FIPA/URLHelper.java index 140f035..0ff01be 100644 --- a/src/FIPA/URLHelper.java +++ b/src/FIPA/URLHelper.java @@ -8,6 +8,8 @@ package FIPA; public class URLHelper { + private static org.omg.CORBA.TypeCode _tc; + // It is useless to have instances of this class private URLHelper() { } @@ -34,8 +36,6 @@ public static void insert(org.omg.CORBA.Any a, String that) { a.read_value(out.create_input_stream(), type()); } - private static org.omg.CORBA.TypeCode _tc; - synchronized public static org.omg.CORBA.TypeCode type() { if (_tc == null) _tc = org.omg.CORBA.ORB.init().create_alias_tc(id(), "URL", org.omg.CORBA.ORB.init().get_primitive_tc(org.omg.CORBA.TCKind.tk_string)); diff --git a/src/FIPA/_MTSImplBase.java b/src/FIPA/_MTSImplBase.java index f3914b9..27d06f7 100644 --- a/src/FIPA/_MTSImplBase.java +++ b/src/FIPA/_MTSImplBase.java @@ -12,27 +12,26 @@ import java.util.Hashtable; public abstract class _MTSImplBase extends org.omg.CORBA.DynamicImplementation implements MTS { - // Constructor - public _MTSImplBase() { - super(); - } - // Type strings for this class and its superclases private static final String[] _type_ids = { "IDL:FIPA/MTS:1.0" }; - - @Deprecated - public String[] _ids() { - return _type_ids.clone(); - } - private static final java.util.Dictionary _methods = new Hashtable<>(); static { _methods.put("message", 0); } + // Constructor + public _MTSImplBase() { + super(); + } + + @Deprecated + public String[] _ids() { + return _type_ids.clone(); + } + // DSI Dispatch call @Deprecated public void invoke(org.omg.CORBA.ServerRequest r) { diff --git a/src/FIPA/_MTSStub.java b/src/FIPA/_MTSStub.java index 7f6b0c8..fc1121c 100644 --- a/src/FIPA/_MTSStub.java +++ b/src/FIPA/_MTSStub.java @@ -11,15 +11,15 @@ public class _MTSStub extends org.omg.CORBA.portable.ObjectImpl implements MTS { + private static final String[] _type_ids = { + "IDL:FIPA/MTS:1.0" + }; + public _MTSStub(org.omg.CORBA.portable.Delegate d) { super(); _set_delegate(d); } - private static final String[] _type_ids = { - "IDL:FIPA/MTS:1.0" - }; - public String[] _ids() { return _type_ids.clone(); } diff --git a/src/FIPA/stringsHelper.java b/src/FIPA/stringsHelper.java index f35d95c..1103d16 100644 --- a/src/FIPA/stringsHelper.java +++ b/src/FIPA/stringsHelper.java @@ -8,6 +8,8 @@ package FIPA; public class stringsHelper { + private static org.omg.CORBA.TypeCode _tc; + // It is useless to have instances of this class private stringsHelper() { } @@ -45,8 +47,6 @@ public static void insert(org.omg.CORBA.Any a, String[] that) { a.read_value(out.create_input_stream(), type()); } - private static org.omg.CORBA.TypeCode _tc; - synchronized public static org.omg.CORBA.TypeCode type() { if (_tc == null) _tc = org.omg.CORBA.ORB.init().create_alias_tc(id(), "strings", org.omg.CORBA.ORB.init().create_sequence_tc(0, org.omg.CORBA.ORB.init().get_primitive_tc(org.omg.CORBA.TCKind.tk_string))); diff --git a/src/jade/Boot.java b/src/jade/Boot.java index e70018e..3d35bb9 100644 --- a/src/jade/Boot.java +++ b/src/jade/Boot.java @@ -47,6 +47,12 @@ public class Boot { public static final String DEFAULT_FILENAME = "leap.properties"; private static final Logger logger = Logger.getMyLogger("jade.Boot"); + /** + * Default constructor. + */ + public Boot() { + } + /** * Fires up the JADE system. * This method initializes the Profile Manager and then starts the @@ -105,13 +111,6 @@ public static void main(String[] args) { } } - /** - * Default constructor. - */ - public Boot() { - } - - public static Properties parseCmdLineArgs(String[] args) throws IllegalArgumentException { Properties props = new ExtendedProperties(); diff --git a/src/jade/Boot3.java b/src/jade/Boot3.java index e3018e7..945155b 100644 --- a/src/jade/Boot3.java +++ b/src/jade/Boot3.java @@ -26,6 +26,13 @@ * java jade.Boot -host fbellif.cselt.it -port 1200 * java jade.Boot -help * java jade.Boot -gui + * Tests: + * java jade.Boot (with/without rmiregistry started): run a main-container + * java jade.Boot -host pippo.cselt.it + * java jade.Boot -host fbellif.cselt.it + * java jade.Boot -host fbellif.cselt.it -port 1200 + * java jade.Boot -help + * java jade.Boot -gui **/ /** Tests: @@ -65,15 +72,6 @@ public class Boot3 { private final ExtendedProperties properties; private BootProfileImpl profile = null; - /** - * Main entry point for invocation. - * @param args The command line arguments. These use the form key:value - * or -key (shorthand for key:true). - */ - public static void main(String[] args) { - new Boot3(args); - } - /** * Constructor. Starts Jade with provided arguments. * @param args The command line arguments. These use the form key:value @@ -150,6 +148,15 @@ public Boot3(String[] args) { } } + /** + * Main entry point for invocation. + * @param args The command line arguments. These use the form key:value + * or -key (shorthand for key:true). + */ + public static void main(String[] args) { + new Boot3(args); + } + /** * Transform original style boot arguments to new form. *
diff --git a/src/jade/BootGUI.java b/src/jade/BootGUI.java
index a394ef5..302f6d6 100644
--- a/src/jade/BootGUI.java
+++ b/src/jade/BootGUI.java
@@ -37,6 +37,7 @@
 
 /**
  * This class create the gui for the jade configuration
+ *
  * @author Tiziana Trucco - CSELT S.p.A.
  * @author Dick Cowan - HP Labs
  * @author Dominic Greenwood - Whitestein Technologies AG
@@ -59,6 +60,7 @@ public class BootGUI extends JDialog {
 
     /**
      * Constructor - launches the GUI configurator.
+     *
      * @param theBooter The Boot class.
      */
     public BootGUI(Boot3 theBooter) {
diff --git a/src/jade/BootProfileImpl.java b/src/jade/BootProfileImpl.java
index a51afe9..ab44901 100644
--- a/src/jade/BootProfileImpl.java
+++ b/src/jade/BootProfileImpl.java
@@ -40,6 +40,7 @@
  * from the argument properties. The class Profile defines
  * a similar collection of keys which are used to access profile
  * properties.
+ *
  * @author Dick Cowan - HP Labs
  * @version $Date: 2011-03-21 14:10:30 +0100(lun, 21 mar 2011) $ $Revision: 6395 $
  */
@@ -59,8 +60,7 @@ public class BootProfileImpl extends ProfileImpl {
     public static final String SMPORT_KEY = "smport";
     public static final String VERSION_KEY = "version";
     public static final String NOMOBILITY_KEY = "nomobility";
-
-
+    private static final String ARGUMENT_SEPARATOR = ";";
     ExtendedProperties argProp;
     BootHelper helper = new BootHelper();
 
@@ -75,6 +75,7 @@ public BootProfileImpl() {
 
     /**
      * Construct profile with specified arguments
+     *
      * @param args Boot arguments
      */
     public BootProfileImpl(String[] args) throws PropertiesException {
@@ -88,6 +89,7 @@ public BootProfileImpl(String[] args) throws PropertiesException {
      * Return the properties collection which resulted from the arguments.
      * This collection is used to create/modify the underlying profile's
      * properties.
+     *
      * @return ExtendedProperties The argument property collection.
      */
     public ExtendedProperties getArgProperties() {
@@ -99,9 +101,10 @@ public ExtendedProperties getArgProperties() {
      * argument properties and then into the profile properties.
      * When moving between the argument properties and profile
      * properties different keys are required.
+     *
      * @param source A collection of argument properties. The
-     * keys to this collection are from the XXX_KEY strings
-     * defined in this class.
+     *               keys to this collection are from the XXX_KEY strings
+     *               defined in this class.
      */
     public void setArgProperties(ExtendedProperties source) {
         argProp.copyProperties(source);
@@ -124,7 +127,7 @@ public void setArgProperties(ExtendedProperties source) {
         } else {
             profileProp.setProperty(Profile.MAIN, "false");
             // Since the value is false, we cancel the default done in ProfileImpl's constructor
-            setSpecifiers(Profile.MTPS, new ArrayList(0)); // remove default MTP
+            setSpecifiers(Profile.MTPS, new ArrayList<>(0)); // remove default MTP
         }
 
         String sm = argProp.getProperty(LOCAL_SERVICE_MANAGER);
@@ -337,6 +340,7 @@ public void setArgProperties(ExtendedProperties source) {
 
     /**
      * Fetch and verify a boolean attribute.
+     *
      * @param aKey The property key to check.
      * @return True or false depending on the attributes setting. False if attribute doesn't exist.
      * @throws PropertiesException if there is a value but its not either "true" or "false".
@@ -355,8 +359,6 @@ protected boolean fetchAndVerifyBoolean(String aKey) throws PropertiesException
         return false;
     }
 
-    private static final String ARGUMENT_SEPARATOR = ";";
-
     /**
      * Parse a String reading for a set of
      * parameter(arg)
diff --git a/src/jade/PropertyType.java b/src/jade/PropertyType.java
index cc4b51b..1b052c7 100644
--- a/src/jade/PropertyType.java
+++ b/src/jade/PropertyType.java
@@ -118,6 +118,13 @@ public String getName() {
         return this.name;
     }
 
+    /*
+    To set the name of the property to a specified value.
+    */
+    public void setName(String value) {
+        this.name = value;
+    }
+
     /**
      * Returns the default value of the property.
      */
@@ -125,6 +132,13 @@ public String getDefaultValue() {
         return this.defaultValue;
     }
 
+    /*
+    To set the default value of the property.
+    */
+    public void setDefaultValue(String value) {
+        this.defaultValue = value;
+    }
+
     /**
      * Returns the combo values for the property.
      */
@@ -146,21 +160,6 @@ public boolean isMandatory() {
         return this.mandatory;
     }
 
-    /*
-    To set the name of the property to a specified value.
-    */
-    public void setName(String value) {
-        this.name = value;
-    }
-
-
-    /*
-    To set the default value of the property.
-    */
-    public void setDefaultValue(String value) {
-        this.defaultValue = value;
-    }
-
 
 }
  
diff --git a/src/jade/content/AgentAction.java b/src/jade/content/AgentAction.java
index 1d2514c..28b98c8 100644
--- a/src/jade/content/AgentAction.java
+++ b/src/jade/content/AgentAction.java
@@ -26,8 +26,9 @@
 
 /**
  * Generic interface to be implemented by classes associated to agent actions
- * in an ontology. Agent actions are expressions describing actions that can 
- * be performed by agents. 
+ * in an ontology. Agent actions are expressions describing actions that can
+ * be performed by agents.
+ *
  * @author Federico Bergenti - Universita` di Parma
  */
 public interface AgentAction extends ContentElement, Concept {
diff --git a/src/jade/content/ContentElement.java b/src/jade/content/ContentElement.java
index ad49c35..137adc7 100644
--- a/src/jade/content/ContentElement.java
+++ b/src/jade/content/ContentElement.java
@@ -28,9 +28,10 @@
 import java.io.Serializable;
 
 /**
- * Interface representing a generic content element, i.e. an 
- * expression that can be meaningfully used as the content of 
+ * Interface representing a generic content element, i.e. an
+ * expression that can be meaningfully used as the content of
  * an ACL message.
+ *
  * @author Federico Bergenti - Universita` di Parma
  */
 public interface ContentElement extends Serializable {
diff --git a/src/jade/content/ContentManager.java b/src/jade/content/ContentManager.java
index d0464fb..ee49e8b 100644
--- a/src/jade/content/ContentManager.java
+++ b/src/jade/content/ContentManager.java
@@ -42,9 +42,9 @@
 import java.util.Map;
 
 /**
- * This class provides all methods to manage the content languages 
- * and ontologies "known" by a given agent and to fill and extract the 
- * content of an ACL message according to a given content language and 
+ * This class provides all methods to manage the content languages
+ * and ontologies "known" by a given agent and to fill and extract the
+ * content of an ACL message according to a given content language and
  * ontology.
  * Each agent has a ContentManager object accessible through
  * the getContentManager() method of the Agent
@@ -74,6 +74,7 @@ private void readObject(java.io.ObjectInputStream oin) throws java.io.IOExceptio
      * Since this operation is performed the agent that owns this
      * ContentManager is able to "speak" the language
      * corresponding to the registered Codec.
+     *
      * @param c the Codec to be registered.
      */
     public void registerLanguage(Codec c) {
@@ -86,7 +87,8 @@ public void registerLanguage(Codec c) {
     /**
      * Registers a Codec for a given content language
      * with a given name.
-     * @param c the Codec to be registered.
+     *
+     * @param c    the Codec to be registered.
      * @param name the name associated to the registered codec.
      */
     public void registerLanguage(Codec c, String name) {
@@ -102,6 +104,7 @@ public void registerLanguage(Codec c, String name) {
      * Since this operation is performed the agent that owns this
      * ContentManager "knows" the registered
      * Ontology.
+     *
      * @param o the Ontology to be registered.
      */
     public void registerOntology(Ontology o) {
@@ -113,7 +116,8 @@ public void registerOntology(Ontology o) {
 
     /**
      * Registers an Ontology with a given name.
-     * @param o the Ontology to be registered.
+     *
+     * @param o    the Ontology to be registered.
      * @param name the name associated to the registered Ontology.
      */
     public void registerOntology(Ontology o, String name) {
@@ -126,8 +130,9 @@ public void registerOntology(Ontology o, String name) {
     /**
      * Retrieves a previously registered Codec
      * giving its name.
+     *
      * @param name the name associated to the Codec
-     * to be retrieved.
+     *             to be retrieved.
      * @return the Codec associated to
      * name or null if no Codec was registered
      * with the given name.
@@ -139,8 +144,9 @@ public Codec lookupLanguage(String name) {
     /**
      * Retrieves a previously registered Ontology
      * giving its name.
+     *
      * @param name the name associated to the Ontology
-     * to be retrieved.
+     *             to be retrieved.
      * @return the Ontology associated to
      * name or null if no Ontology was registered
      * with the given name.
@@ -154,13 +160,14 @@ public Ontology lookupOntology(String name) {
      * ACLMessage msg using the content language
      * and ontology indicated in the :language and
      * :ontology fields of msg.
-     * @param msg the message whose content has to be filled.
+     *
+     * @param msg     the message whose content has to be filled.
      * @param content the content of the message represented as an
-     * AbsContentElement.
-     * @throws CodecException if content is not compliant
-     * to the content language used for this operation.
+     *                AbsContentElement.
+     * @throws CodecException    if content is not compliant
+     *                           to the content language used for this operation.
      * @throws OntologyException if content is not compliant
-     * to the ontology used for this operation.
+     *                           to the ontology used for this operation.
      */
     public void fillContent(ACLMessage msg, AbsContentElement content) throws CodecException, OntologyException {
         Codec codec = lookupLanguage(msg.getLanguage());
@@ -187,13 +194,14 @@ public void fillContent(ACLMessage msg, AbsContentElement content) throws CodecE
      * ACLMessage msg using the content language
      * and ontology indicated in the :language and
      * :ontology fields of msg.
-     * @param msg the message whose content has to be filled.
+     *
+     * @param msg     the message whose content has to be filled.
      * @param content the content of the message represented as a
-     * ContentElement.
-     * @throws CodecException if content is not compliant
-     * to the content language used for this operation.
+     *                ContentElement.
+     * @throws CodecException    if content is not compliant
+     *                           to the content language used for this operation.
      * @throws OntologyException if content is not compliant
-     * to the ontology used for this operation.
+     *                           to the ontology used for this operation.
      */
     public void fillContent(ACLMessage msg, ContentElement content) throws CodecException, OntologyException {
         Codec codec = lookupLanguage(msg.getLanguage());
@@ -222,13 +230,14 @@ public void fillContent(ACLMessage msg, ContentElement content) throws CodecExce
      * ACLMessage msg into an AbsContentElement
      * using the content language and ontology indicated in the
      * :language and :ontology fields of msg.
+     *
      * @param msg the message whose content has to be extracted.
      * @return the content of the message represented as an
      * AbsContentElement.
-     * @throws CodecException if the content of the message is not compliant
-     * to the content language used for this operation.
+     * @throws CodecException    if the content of the message is not compliant
+     *                           to the content language used for this operation.
      * @throws OntologyException if the content of the message is not compliant
-     * to the ontology used for this operation.
+     *                           to the ontology used for this operation.
      */
     public AbsContentElement extractAbsContent(ACLMessage msg) throws CodecException, OntologyException {
         Codec codec = lookupLanguage(msg.getLanguage());
@@ -257,13 +266,14 @@ public AbsContentElement extractAbsContent(ACLMessage msg) throws CodecException
      * ACLMessage msg into a ContentElement
      * using the content language and ontology indicated in the
      * :language and :ontology fields of msg.
+     *
      * @param msg the message whose content has to be extracted.
      * @return the content of the message represented as a
      * ContentElement.
-     * @throws CodecException if the content of the message is not compliant
-     * to the content language used for this operation.
+     * @throws CodecException    if the content of the message is not compliant
+     *                           to the content language used for this operation.
      * @throws OntologyException if the content of the message is not compliant
-     * to the ontology used for this operation.
+     *                           to the ontology used for this operation.
      */
     public ContentElement extractContent(ACLMessage msg) throws CodecException, OntologyException {
         Codec codec = lookupLanguage(msg.getLanguage());
@@ -288,30 +298,33 @@ public ContentElement extractContent(ACLMessage msg) throws CodecException, Onto
     }
 
     /**
-     Set the validation mode i.e. whether contents that are managed
-     by this content manager should be validated during
-     message content filling/extraction.
-     Default value is true
-     @param mode the new validation mode
+     * Return the currently set validation mode i.e. whether
+     * contents that are managed by this content manager should
+     * be validated during message content filling/extraction.
+     * Default value is true
+     *
+     * @return the currently set validation mode
      */
-    public void setValidationMode(boolean mode) {
-        validationMode = mode;
+    public boolean getValidationMode() {
+        return validationMode;
     }
 
     /**
-     Return the currently set validation mode i.e. whether
-     contents that are managed by this content manager should
-     be validated during message content filling/extraction.
-     Default value is true
-     @return the currently set validation mode
+     * Set the validation mode i.e. whether contents that are managed
+     * by this content manager should be validated during
+     * message content filling/extraction.
+     * Default value is true
+     *
+     * @param mode the new validation mode
      */
-    public boolean getValidationMode() {
-        return validationMode;
+    public void setValidationMode(boolean mode) {
+        validationMode = mode;
     }
 
     //#APIDOC_EXCLUDE_BEGIN
 
     /**
+     *
      */
     public Ontology getOntology(ACLMessage msg) {
         return getMergedOntology(lookupLanguage(msg.getLanguage()), lookupOntology(msg.getOntology()));
@@ -365,12 +378,11 @@ else if (codec instanceof StringCodec)
     }
 
     public String toString() {
-        StringBuilder sb = new StringBuilder("(ContentManager:\n  - registered-ontologies = ");
-        sb.append(ontologies);
-        sb.append("\n  - registered-languages = ");
-        sb.append(languages);
-        sb.append(")");
-        return sb.toString();
+        String sb = "(ContentManager:\n  - registered-ontologies = " + ontologies +
+                "\n  - registered-languages = " +
+                languages +
+                ")";
+        return sb;
     }
 
     public String[] getLanguageNames() {
diff --git a/src/jade/content/OntoACLMessage.java b/src/jade/content/OntoACLMessage.java
index 46d979a..bfbd9a2 100644
--- a/src/jade/content/OntoACLMessage.java
+++ b/src/jade/content/OntoACLMessage.java
@@ -32,6 +32,7 @@
 /**
  * Utility class that allow using an ACLMessage object
  * as an ontological agent action.
+ *
  * @author Giovanni Caire - TILAB
  */
 public class OntoACLMessage extends ACLMessage implements AgentAction {
@@ -47,6 +48,7 @@ public OntoACLMessage() {
     /**
      * Construct an ontological ACL message with a given
      * performative
+     *
      * @param performative the performative of this ACL message.
      * @see ACLMessage#ACLMessage(int)
      */
@@ -57,11 +59,12 @@ public OntoACLMessage(int performative) {
     /**
      * Create an ontological ACL message that wraps an existing
      * ACLMessage.
+     *
      * @param msg the ACLMessageto be wrapped. If
-     * msg
-     * is already an ontological ACL message no new object is
-     * created and msg is returned with the sender
-     * and receivers properly wrapped if necessary.
+     *            msg
+     *            is already an ontological ACL message no new object is
+     *            created and msg is returned with the sender
+     *            and receivers properly wrapped if necessary.
      */
     public static OntoACLMessage wrap(ACLMessage msg) {
         OntoACLMessage wrapper = null;
diff --git a/src/jade/content/OntoAID.java b/src/jade/content/OntoAID.java
index f84b9e0..8048d78 100644
--- a/src/jade/content/OntoAID.java
+++ b/src/jade/content/OntoAID.java
@@ -31,6 +31,7 @@
 /**
  * Utility class that allow using an AID object
  * as an ontological concept.
+ *
  * @author Giovanni Caire - TILAB
  */
 public class OntoAID extends AID implements Concept {
@@ -38,6 +39,7 @@ public class OntoAID extends AID implements Concept {
     /**
      * Constructs an ontological Agent-Identifier whose slot name is
      * set to an empty string
+     *
      * @see AID#AID()
      */
     public OntoAID() {
@@ -46,13 +48,14 @@ public OntoAID() {
 
     /**
      * Constructor for an ontological Agent-identifier
-     * @param name is the value for the slot name for the agent.
+     *
+     * @param name   is the value for the slot name for the agent.
      * @param isGUID indicates if the passed name
-     * is already a globally unique identifier or not. Two
-     * constants ISGUID, ISLOCALNAME
-     * have also been defined for setting a value for this parameter.
-     * If the name is a local name, then the HAP (Home Agent Platform)
-     * is concatenated to the name, separated by  "@".
+     *               is already a globally unique identifier or not. Two
+     *               constants ISGUID, ISLOCALNAME
+     *               have also been defined for setting a value for this parameter.
+     *               If the name is a local name, then the HAP (Home Agent Platform)
+     *               is concatenated to the name, separated by  "@".
      * @see AID#AID(String, boolean)
      */
     public OntoAID(String name, boolean isGUID) {
@@ -62,10 +65,11 @@ public OntoAID(String name, boolean isGUID) {
     /**
      * Create an ontological Agent identifier that wraps an existing
      * AID.
+     *
      * @param id the AIDto be wrapped. If id
-     * is already an ontological agent identifier no new object is
-     * created and id is returned with the resolvers
-     * (if any) properly wrapped.
+     *           is already an ontological agent identifier no new object is
+     *           created and id is returned with the resolvers
+     *           (if any) properly wrapped.
      */
     public static OntoAID wrap(AID id) {
         OntoAID wrapper = null;
diff --git a/src/jade/content/Predicate.java b/src/jade/content/Predicate.java
index 5ede48c..0d22c78 100644
--- a/src/jade/content/Predicate.java
+++ b/src/jade/content/Predicate.java
@@ -26,8 +26,9 @@
 
 /**
  * Generic interface to be implemented by classes associated to predicates
- * in an ontology. Predicates are expressions that say something about 
+ * in an ontology. Predicates are expressions that say something about
  * the status of the world and can be true or false.
+ *
  * @author Federico Bergenti - Universita` di Parma
  */
 public interface Predicate extends ContentElement {
diff --git a/src/jade/content/Term.java b/src/jade/content/Term.java
index 9533070..fa49798 100644
--- a/src/jade/content/Term.java
+++ b/src/jade/content/Term.java
@@ -29,9 +29,10 @@
 import java.io.Serializable;
 
 /**
- * Interface representing a generic term, i.e. an expression 
- * identifying a generic entity (abstract or concrete) that "exist" 
+ * Interface representing a generic term, i.e. an expression
+ * identifying a generic entity (abstract or concrete) that "exist"
  * in the world and that agents can talk and reason about.
+ *
  * @author Federico Bergenti - Universita` di Parma
  */
 public interface Term extends Serializable {
diff --git a/src/jade/content/abs/AbsAgentAction.java b/src/jade/content/abs/AbsAgentAction.java
index 8834caa..e3f5540 100644
--- a/src/jade/content/abs/AbsAgentAction.java
+++ b/src/jade/content/abs/AbsAgentAction.java
@@ -34,6 +34,9 @@
  */
 public class AbsAgentAction extends AbsConcept implements AbsContentElement, AgentAction {
 
+    // Easy way to access the Java class representing AbsAgentAction.
+    // Useful in MIDP where XXX.class is not available
+    private static Class absAgentActionClass = null;
     private boolean isAContentExpression = false;
 
     /**
@@ -47,21 +50,6 @@ public AbsAgentAction(String typeName) {
         super(typeName);
     }
 
-    /**
-     * Set an attribute of the agent action held by this
-     * abstract descriptor.
-     *
-     * @param name  The name of the attribute to be set.
-     * @param value The new value of the attribute.
-     */
-    public void set(String name, AbsPredicate value) {
-        super.set(name, value);
-    }
-
-    // Easy way to access the Java class representing AbsAgentAction.
-    // Useful in MIDP where XXX.class is not available
-    private static Class absAgentActionClass = null;
-
     public static Class getJavaClass() {
         if (absAgentActionClass == null) {
             try {
@@ -74,6 +62,17 @@ public static Class getJavaClass() {
         return absAgentActionClass;
     }
 
+    /**
+     * Set an attribute of the agent action held by this
+     * abstract descriptor.
+     *
+     * @param name  The name of the attribute to be set.
+     * @param value The new value of the attribute.
+     */
+    public void set(String name, AbsPredicate value) {
+        super.set(name, value);
+    }
+
     /**
      * see AbsContent.isAContentExpression
      */
diff --git a/src/jade/content/abs/AbsConcept.java b/src/jade/content/abs/AbsConcept.java
index 50dfcc7..1de30e2 100644
--- a/src/jade/content/abs/AbsConcept.java
+++ b/src/jade/content/abs/AbsConcept.java
@@ -29,24 +29,43 @@
 /**
  * An abstract descriptor that can hold a concept
  * expression.
+ *
  * @author Federico Bergenti - Universita` di Parma
  */
 public class AbsConcept extends AbsPrimitiveSlotsHolder implements AbsTerm, Concept {
 
+    // Easy way to access the Java class representing AbsConcept.
+    // Useful in MIDP where XXX.class is not available
+    private static Class absConceptClass = null;
+
     /**
      * Construct an Abstract descriptor to hold a concept of
      * the proper type (e.g. PERSON, ADDRESS...).
+     *
      * @param typeName The name of the type of the concept held by
-     * this abstract descriptor.
+     *                 this abstract descriptor.
      */
     public AbsConcept(String typeName) {
         super(typeName);
     }
 
+    public static Class getJavaClass() {
+        if (absConceptClass == null) {
+            try {
+                absConceptClass = (Class) Class.forName("jade.content.abs.AbsConcept");
+            } catch (Exception e) {
+                // Should never happen
+                e.printStackTrace();
+            }
+        }
+        return absConceptClass;
+    }
+
     /**
      * Sets an attribute of the concept held by this
      * abstract descriptor.
-     * @param name The name of the attribute to be set.
+     *
+     * @param name  The name of the attribute to be set.
      * @param value The new value of the attribute.
      */
     public void set(String name, AbsTerm value) {
@@ -56,6 +75,7 @@ public void set(String name, AbsTerm value) {
     /**
      * Gets the value of an attribute of the concept
      * held by this abstract descriptor.
+     *
      * @param name The name of the attribute.
      * @return value The value of the attribute.
      */
@@ -63,22 +83,6 @@ public AbsTerm getAbsTerm(String name) {
         return (AbsTerm) getAbsObject(name);
     }
 
-    // Easy way to access the Java class representing AbsConcept.
-    // Useful in MIDP where XXX.class is not available
-    private static Class absConceptClass = null;
-
-    public static Class getJavaClass() {
-        if (absConceptClass == null) {
-            try {
-                absConceptClass = (Class) Class.forName("jade.content.abs.AbsConcept");
-            } catch (Exception e) {
-                // Should never happen
-                e.printStackTrace();
-            }
-        }
-        return absConceptClass;
-    }
-
     public int getAbsType() {
         return ABS_CONCEPT;
     }
diff --git a/src/jade/content/abs/AbsContentElement.java b/src/jade/content/abs/AbsContentElement.java
index 1500261..7b4a7aa 100644
--- a/src/jade/content/abs/AbsContentElement.java
+++ b/src/jade/content/abs/AbsContentElement.java
@@ -29,12 +29,14 @@
 /**
  * An abstract descriptor that can hold a generic content element
  * expression.
+ *
  * @author Federico Bergenti - Universita` di Parma
  */
 public interface AbsContentElement extends AbsObject, ContentElement {
     /**
      * Return true if this Abstract Content Element represents a ContentExpression
      * of the SL Grammar (see also FIPA-SL specifications).
+     *
      * @return true if this Abstract Content Element represents a ContentExpression
      * of the SL Grammar (see also FIPA-SL specifications), false otherwise
      */
@@ -43,8 +45,9 @@ public interface AbsContentElement extends AbsObject, ContentElement {
     /**
      * Set the isAContentExpression flag to the passed value.
      * By default, if this method was not called, this value is intialized to false.
+     *
      * @param flag true if this Abstract Content Element represents a ContentExpression
-     * of the SL Grammar (see also FIPA-SL specifications), false otherwise
+     *             of the SL Grammar (see also FIPA-SL specifications), false otherwise
      */
     void setIsAContentExpression(boolean flag);
 }
diff --git a/src/jade/content/abs/AbsExtendedPrimitive.java b/src/jade/content/abs/AbsExtendedPrimitive.java
index 8055e01..9c85fd3 100644
--- a/src/jade/content/abs/AbsExtendedPrimitive.java
+++ b/src/jade/content/abs/AbsExtendedPrimitive.java
@@ -25,15 +25,14 @@
 package jade.content.abs;
 
 /**
- * An extended abstract descriptor that can hold a generic primitive types 
+ * An extended abstract descriptor that can hold a generic primitive types
  * (eg. java.math.BigDecimal) not supported by AbsPrimitive.
  */
 public class AbsExtendedPrimitive implements AbsTerm {
 
     public static final int ABS_EXTENDED_PRIMITIVE = 10;
-
-    private Object value;
     private final String typeName;
+    private Object value;
 
     /**
      * Construct an extended abstract descriptor to hold a primitive of
@@ -49,7 +48,7 @@ private AbsExtendedPrimitive(String typeName, Object value) {
      * the proper type (e.g. java.math.BigInteger...).
      *
      * @param typeName The name of the type of the extended-primitive held by
-     * this descriptor.
+     *                 this descriptor.
      */
     public AbsExtendedPrimitive(String typeName) {
         this(typeName, null);
@@ -72,7 +71,7 @@ public static AbsExtendedPrimitive wrap(Object value) {
      *
      * @param value The new value
      * @throws IllegalArgumentException If the type of this AbsExtendedPrimitive
-     * is not correct.
+     *                                  is not correct.
      */
     public void set(Object value) {
         if (!getTypeName().equals(value.getClass().getName()))
@@ -96,16 +95,16 @@ public String getTypeName() {
     }
 
     /**
-     Makes no sense in the case of an AbsExtendedPrimitive that has no attribute
-     --> Just return null
+     * Makes no sense in the case of an AbsExtendedPrimitive that has no attribute
+     * --> Just return null
      */
     public AbsObject getAbsObject(String name) {
         return null;
     }
 
     /**
-     Makes no sense in the case of an AbsExtendedPrimitive that has no attribute
-     --> Just return null
+     * Makes no sense in the case of an AbsExtendedPrimitive that has no attribute
+     * --> Just return null
      */
     public String[] getNames() {
         return null;
@@ -119,8 +118,8 @@ public boolean isGrounded() {
     }
 
     /**
-     Makes no sense in the case of an AbsExtendedPrimitive that has no attribute
-     --> Just return 0
+     * Makes no sense in the case of an AbsExtendedPrimitive that has no attribute
+     * --> Just return 0
      */
     public int getCount() {
         return 0;
diff --git a/src/jade/content/abs/AbsIRE.java b/src/jade/content/abs/AbsIRE.java
index ed72018..f291793 100644
--- a/src/jade/content/abs/AbsIRE.java
+++ b/src/jade/content/abs/AbsIRE.java
@@ -32,40 +32,87 @@
  * Note that an IRE is both a content element (as in the case of
  * a QUERY-REF communicative act) and a Term (as in the case of
  * (== (X) (iota ?x P(?x))
+ *
  * @author Paola Turci, Federico Bergenti - Universita` di Parma
  */
 public class AbsIRE extends AbsObjectImpl implements AbsContentElement, AbsTerm {
 
+    // Easy way to access the Java class representing AbsIRE.
+    // Useful in MIDP where XXX.class is not available
+    private static Class absIREClass = null;
     private boolean isAContentExpression = false;
 
     /**
      * Construct an Abstract descriptor to hold a IRE of
      * the proper type (e.g. ANY, IOTA, ALL...).
+     *
      * @param typeName The name of the type of the IRE held by
-     * this abstract descriptor.
+     *                 this abstract descriptor.
      */
     public AbsIRE(String typeName) {
         super(typeName);
     }
 
+    public static Class getJavaClass() {
+        if (absIREClass == null) {
+            try {
+                absIREClass = (Class) Class.forName("jade.content.abs.AbsIRE");
+            } catch (Exception e) {
+                // Should never happen
+                e.printStackTrace();
+            }
+        }
+        return absIREClass;
+    }
+
+    /**
+     * Gets the variable of this IRE.
+     *
+     * @return the abstract descriptor holding the variable of this IRE.
+     */
+    public AbsVariable getVariable() {
+        return (AbsVariable) getAbsObject(IRESchema.VARIABLE);
+    }
+
     /**
      * Sets the variable of this IRE.
+     *
      * @param variable The abstract descriptor holding the variable.
      */
     public void setVariable(AbsVariable variable) {
         set(IRESchema.VARIABLE, variable);
     }
 
+    /**
+     * Gets the sequence of variables of this IRE.
+     *
+     * @return the abstract descriptor holding the sequence of variables of this IRE.
+     */
+    public AbsAggregate getVariables() {
+        return (AbsAggregate) getAbsObject(IRESchema.VARIABLE);
+    }
+
     /**
      * Sets the sequence of variables of this IRE.
+     *
      * @param variables The abstract descriptor holding the sequence of variables.
      */
     public void setVariables(AbsAggregate variables) {
         set(IRESchema.VARIABLE, variables);
     }
 
+    /**
+     * Gets the variable term of this IRE.
+     *
+     * @return the abstract descriptor holding the variable term of this IRE.
+     */
+    public AbsTerm getTerm() {
+        return (AbsTerm) getAbsObject(IRESchema.VARIABLE);
+    }
+
     /**
      * Sets the variable term of this IRE.
+     *
      * @param t The abstract descriptor holding the variable or sequence of variables.
      */
     public void setTerm(AbsTerm t) {
@@ -78,46 +125,24 @@ public void setTerm(AbsTerm t) {
         }
     }
 
-    /**
-     * Sets the proposition of this IRE.
-     * @param proposition The abstract descriptor holding the proposition.
-     */
-    public void setProposition(AbsPredicate proposition) {
-        set(IRESchema.PROPOSITION, proposition);
-    }
-
-    /**
-     * Gets the variable of this IRE.
-     * @return the abstract descriptor holding the variable of this IRE.
-     */
-    public AbsVariable getVariable() {
-        return (AbsVariable) getAbsObject(IRESchema.VARIABLE);
-    }
-
-    /**
-     * Gets the sequence of variables of this IRE.
-     * @return the abstract descriptor holding the sequence of variables of this IRE.
-     */
-    public AbsAggregate getVariables() {
-        return (AbsAggregate) getAbsObject(IRESchema.VARIABLE);
-    }
-
-    /**
-     * Gets the variable term of this IRE.
-     * @return the abstract descriptor holding the variable term of this IRE.
-     */
-    public AbsTerm getTerm() {
-        return (AbsTerm) getAbsObject(IRESchema.VARIABLE);
-    }
-
     /**
      * Gets the proposition of this IRE.
+     *
      * @return the abstract descriptor holding the proposition of this IRE.
      */
     public AbsPredicate getProposition() {
         return (AbsPredicate) getAbsObject(IRESchema.PROPOSITION);
     }
 
+    /**
+     * Sets the proposition of this IRE.
+     *
+     * @param proposition The abstract descriptor holding the proposition.
+     */
+    public void setProposition(AbsPredicate proposition) {
+        set(IRESchema.PROPOSITION, proposition);
+    }
+
     /**
      * Redefine the isGrounded() method in order to
      * always return false. Infact an IRE always
@@ -127,23 +152,6 @@ public boolean isGrounded() {
         return false;
     }
 
-    // Easy way to access the Java class representing AbsIRE.
-    // Useful in MIDP where XXX.class is not available
-    private static Class absIREClass = null;
-
-    public static Class getJavaClass() {
-        if (absIREClass == null) {
-            try {
-                absIREClass = (Class) Class.forName("jade.content.abs.AbsIRE");
-            } catch (Exception e) {
-                // Should never happen
-                e.printStackTrace();
-            }
-        }
-        return absIREClass;
-    }
-
-
     /**
      * see AbsContent.isAContentExpression
      */
diff --git a/src/jade/content/abs/AbsObject.java b/src/jade/content/abs/AbsObject.java
index d1bec92..2d27eb7 100644
--- a/src/jade/content/abs/AbsObject.java
+++ b/src/jade/content/abs/AbsObject.java
@@ -29,6 +29,7 @@
 
 /**
  * The common ancestor of all abstract descriptors
+ *
  * @author Federico Bergenti - Universita` di Parma
  * @author Giovanni Caire - TILAB
  */
@@ -53,6 +54,7 @@ public interface AbsObject extends Serializable {
     /**
      * Gets the value of an attribute of the object held by this
      * abstract descriptor.
+     *
      * @param name The name of the attribute.
      * @return value The value of the attribute.
      */
@@ -64,14 +66,16 @@ public interface AbsObject extends Serializable {
     String[] getNames();
 
     /**
-     * Tests if the object is grounded, i.e., if no one of its attributes 
+     * Tests if the object is grounded, i.e., if no one of its attributes
      * is associated with a variable
+     *
      * @return true if the object is grounded.
      */
     boolean isGrounded();
 
     /**
      * Gets the number of attributes.
+     *
      * @return the number of attributes.
      */
     int getCount();
diff --git a/src/jade/content/abs/AbsPredicate.java b/src/jade/content/abs/AbsPredicate.java
index a782e1e..9de2a66 100644
--- a/src/jade/content/abs/AbsPredicate.java
+++ b/src/jade/content/abs/AbsPredicate.java
@@ -28,27 +28,45 @@
 
 /**
  * An abstract descriptor that can hold a predicate expression.
+ *
  * @author Paola Turci, Federico Bergenti - Universita` di Parma
  */
 public class AbsPredicate extends AbsPrimitiveSlotsHolder implements AbsContentElement, Predicate {
 
+    // Easy way to access the Java class representing AbsPredicate.
+    // Useful in MIDP where XXX.class is not available
+    private static Class absPredicateClass = null;
     private boolean isAContentExpression = false;
     private boolean isMeta = false;
 
     /**
      * Construct an Abstract descriptor to hold a predicate of
      * the proper type (e.g. FATHER_OF, WORKS_FOR...).
+     *
      * @param typeName The name of the type of the predicate held by
-     * this abstract descriptor.
+     *                 this abstract descriptor.
      */
     public AbsPredicate(String typeName) {
         super(typeName);
     }
 
+    public static Class getJavaClass() {
+        if (absPredicateClass == null) {
+            try {
+                absPredicateClass = (Class) Class.forName("jade.content.abs.AbsPredicate");
+            } catch (Exception e) {
+                // Should never happen
+                e.printStackTrace();
+            }
+        }
+        return absPredicateClass;
+    }
+
     /**
      * Sets an attribute of the predicate held by this
      * abstract descriptor.
-     * @param name The name of the attribute to be set.
+     *
+     * @param name  The name of the attribute to be set.
      * @param value The new value of the attribute.
      */
     public void set(String name, AbsObject value) {
@@ -59,6 +77,7 @@ public void set(String name, AbsObject value) {
      * Gets the value (casted as an AbsTerm) of an attribute of
      * the predicate held by this abstract descriptor.
      * This method is here mainly for backward compatibility.
+     *
      * @param name The name of the attribute.
      * @return value The value of the attribute.
      */
@@ -66,22 +85,6 @@ public AbsTerm getAbsTerm(String name) {
         return (AbsTerm) getAbsObject(name);
     }
 
-    // Easy way to access the Java class representing AbsPredicate.
-    // Useful in MIDP where XXX.class is not available
-    private static Class absPredicateClass = null;
-
-    public static Class getJavaClass() {
-        if (absPredicateClass == null) {
-            try {
-                absPredicateClass = (Class) Class.forName("jade.content.abs.AbsPredicate");
-            } catch (Exception e) {
-                // Should never happen
-                e.printStackTrace();
-            }
-        }
-        return absPredicateClass;
-    }
-
     /**
      * see AbsContentElement.isAContentExpression
      */
@@ -97,8 +100,10 @@ public void setIsAContentExpression(boolean flag) {
     }
 
 
-    /** Return true if this object represents a meta formula (symbol ??x) rather than a concrete formula.
+    /**
+     * Return true if this object represents a meta formula (symbol ??x) rather than a concrete formula.
      * This method is currently used only by the semantics framework.
+     *
      * @return true if this object represents a meta formula
      * @since JADE3.4
      **/
@@ -106,8 +111,10 @@ public final boolean isMetaFormula() {
         return isMeta;
     }
 
-    /** Sets the value of isMetaFormula, where the default is false.
+    /**
+     * Sets the value of isMetaFormula, where the default is false.
      * This method is currently used only by the semantics framework.
+     *
      * @since JADE3.4
      **/
     public final void setIsMetaFormula(boolean isMeta) {
diff --git a/src/jade/content/abs/AbsPrimitive.java b/src/jade/content/abs/AbsPrimitive.java
index 4f73aef..5e87780 100644
--- a/src/jade/content/abs/AbsPrimitive.java
+++ b/src/jade/content/abs/AbsPrimitive.java
@@ -30,12 +30,13 @@
 
 /**
  * An abstract descriptor that can hold a primitive expression.
+ *
  * @author Paola Turci, Federico Bergenti - Universita` di Parma
  * @author Giovanni Caire - TILAB
  */
 public class AbsPrimitive implements AbsTerm {
-    private Object value;
     private final String typeName;
+    private Object value;
 
     /**
      * Construct an Abstract descriptor to hold a primitive of
@@ -49,8 +50,9 @@ private AbsPrimitive(String typeName, Object value) {
     /**
      * Construct an Abstract descriptor to hold a primitive of
      * the proper type (e.g. String, int, boolean...).
+     *
      * @param typeName The name of the type of the primitive held by
-     * this abstract descriptor.
+     *                 this abstract descriptor.
      */
     public AbsPrimitive(String typeName) {
         this(typeName, null);
@@ -138,9 +140,10 @@ public static AbsPrimitive wrap(byte[] value) {
 
     /**
      * Set the value of this AbsPrimitive to the given String.
+     *
      * @param value The new value
      * @throws IllegalArgumentException If the type of this AbsPrimitive
-     * is not BasicOntology.STRING
+     *                                  is not BasicOntology.STRING
      */
     public void set(String value) {
         if (!getTypeName().equals(BasicOntology.STRING))
@@ -150,9 +153,10 @@ public void set(String value) {
 
     /**
      * Set the value of this AbsPrimitive to the given boolean value.
+     *
      * @param value The new value
      * @throws IllegalArgumentException If the type of this AbsPrimitive
-     * is not BasicOntology.BOOLEAN
+     *                                  is not BasicOntology.BOOLEAN
      */
     public void set(boolean value) {
         if (!getTypeName().equals(BasicOntology.BOOLEAN))
@@ -162,9 +166,10 @@ public void set(boolean value) {
 
     /**
      * Set the value of this AbsPrimitive to the given int value.
+     *
      * @param value The new value
      * @throws IllegalArgumentException If the type of this AbsPrimitive
-     * is not BasicOntology.INTEGER
+     *                                  is not BasicOntology.INTEGER
      */
     public void set(int value) {
         if (!getTypeName().equals(BasicOntology.INTEGER))
@@ -174,9 +179,10 @@ public void set(int value) {
 
     /**
      * Set the value of this AbsPrimitive to the given long value.
+     *
      * @param value The new value
      * @throws IllegalArgumentException If the type of this AbsPrimitive
-     * is not BasicOntology.INTEGER
+     *                                  is not BasicOntology.INTEGER
      */
     public void set(long value) {
         if (!getTypeName().equals(BasicOntology.INTEGER))
@@ -188,9 +194,10 @@ public void set(long value) {
 
     /**
      * Set the value of this AbsPrimitive to the given float value.
+     *
      * @param value The new value
      * @throws IllegalArgumentException If the type of this AbsPrimitive
-     * is not BasicOntology.FLOAT
+     *                                  is not BasicOntology.FLOAT
      */
     public void set(float value) {
         if (!getTypeName().equals(BasicOntology.FLOAT))
@@ -200,9 +207,10 @@ public void set(float value) {
 
     /**
      * Set the value of this AbsPrimitive to the given double value.
+     *
      * @param value The new value
      * @throws IllegalArgumentException If the type of this AbsPrimitive
-     * is not BasicOntology.FLOAT
+     *                                  is not BasicOntology.FLOAT
      */
     public void set(double value) {
         if (!getTypeName().equals(BasicOntology.FLOAT))
@@ -213,9 +221,10 @@ public void set(double value) {
 
     /**
      * Set the value of this AbsPrimitive to the given Date value.
+     *
      * @param value The new value
      * @throws IllegalArgumentException If the type of this AbsPrimitive
-     * is not BasicOntology.DATE
+     *                                  is not BasicOntology.DATE
      */
     public void set(Date value) {
         if (!getTypeName().equals(BasicOntology.DATE))
@@ -225,9 +234,10 @@ public void set(Date value) {
 
     /**
      * Set the value of this AbsPrimitive to the given byte[] value.
+     *
      * @param value The new value
      * @throws IllegalArgumentException If the type of this AbsPrimitive
-     * is not BasicOntology.BYTE_SEQUENCE
+     *                                  is not BasicOntology.BYTE_SEQUENCE
      */
     public void set(byte[] value) {
         if (!getTypeName().equals(BasicOntology.BYTE_SEQUENCE))
@@ -238,7 +248,7 @@ public void set(byte[] value) {
     /**
      * @return the value of this AbsPrimitive as a String.
      * @throws ClassCastException If the type of this AbsPrimitive
-     * is not BasicOntology.STRING
+     *                            is not BasicOntology.STRING
      */
     public String getString() {
         return (String) value;
@@ -247,7 +257,7 @@ public String getString() {
     /**
      * @return the value of this AbsPrimitive as a boolean.
      * @throws ClassCastException If the type of this AbsPrimitive
-     * is not BasicOntology.BOOLEAN
+     *                            is not BasicOntology.BOOLEAN
      */
     public boolean getBoolean() {
         return (Boolean) value;
@@ -256,7 +266,7 @@ public boolean getBoolean() {
     /**
      * @return the value of this AbsPrimitive as an int.
      * @throws ClassCastException If the type of this AbsPrimitive
-     * is not BasicOntology.INTEGER
+     *                            is not BasicOntology.INTEGER
      */
     public int getInteger() {
         try {
@@ -270,7 +280,7 @@ public int getInteger() {
     /**
      * @return the value of this AbsPrimitive as a long.
      * @throws ClassCastException If the type of this AbsPrimitive
-     * is not BasicOntology.INTEGER
+     *                            is not BasicOntology.INTEGER
      */
     public long getLong() {
         try {
@@ -286,7 +296,7 @@ public long getLong() {
     /**
      * @return the value of this AbsPrimitive as a float.
      * @throws ClassCastException If the type of this AbsPrimitive
-     * is not BasicOntology.FLOAT
+     *                            is not BasicOntology.FLOAT
      */
     public float getFloat() {
         try {
@@ -300,7 +310,7 @@ public float getFloat() {
     /**
      * @return the value of this AbsPrimitive as a double.
      * @throws ClassCastException If the type of this AbsPrimitive
-     * is not BasicOntology.FLOAT
+     *                            is not BasicOntology.FLOAT
      */
     public double getDouble() {
         try {
@@ -315,7 +325,7 @@ public double getDouble() {
     /**
      * @return the value of this AbsPrimitive as a Date.
      * @throws ClassCastException If the type of this AbsPrimitive
-     * is not BasicOntology.DATE
+     *                            is not BasicOntology.DATE
      */
     public Date getDate() {
         return (Date) value;
@@ -324,7 +334,7 @@ public Date getDate() {
     /**
      * @return the value of this AbsPrimitive as a byte[].
      * @throws ClassCastException If the type of this AbsPrimitive
-     * is not BasicOntology.BYTE_SEQUENCE
+     *                            is not BasicOntology.BYTE_SEQUENCE
      */
     public byte[] getByteSequence() {
         return (byte[]) value;
@@ -351,16 +361,16 @@ public String getTypeName() {
     }
 
     /**
-     Makes no sense in the case of an AbsPrimitive that has no attribute
-     --> Just return null
+     * Makes no sense in the case of an AbsPrimitive that has no attribute
+     * --> Just return null
      */
     public AbsObject getAbsObject(String name) {
         return null;
     }
 
     /**
-     Makes no sense in the case of an AbsPrimitive that has no attribute
-     --> Just return null
+     * Makes no sense in the case of an AbsPrimitive that has no attribute
+     * --> Just return null
      */
     public String[] getNames() {
         return null;
@@ -374,8 +384,8 @@ public boolean isGrounded() {
     }
 
     /**
-     Makes no sense in the case of an AbsPrimitive that has no attribute
-     --> Just return 0
+     * Makes no sense in the case of an AbsPrimitive that has no attribute
+     * --> Just return 0
      */
     public int getCount() {
         return 0;
diff --git a/src/jade/content/abs/AbsPrimitiveSlotsHolder.java b/src/jade/content/abs/AbsPrimitiveSlotsHolder.java
index 24bcd40..ab97f77 100644
--- a/src/jade/content/abs/AbsPrimitiveSlotsHolder.java
+++ b/src/jade/content/abs/AbsPrimitiveSlotsHolder.java
@@ -28,6 +28,7 @@
 
 /**
  * This class is not intended to be used by programmers.
+ *
  * @author Giovanni Caire - TILAB
  */
 public class AbsPrimitiveSlotsHolder extends AbsObjectImpl {
@@ -35,8 +36,9 @@ public class AbsPrimitiveSlotsHolder extends AbsObjectImpl {
     /**
      * Construct an Abstract descriptor to hold an object of
      * the proper type.
-     * @param typeName The name of the type of the object held by 
-     * this abstract descriptor.
+     *
+     * @param typeName The name of the type of the object held by
+     *                 this abstract descriptor.
      */
     protected AbsPrimitiveSlotsHolder(String typeName) {
         super(typeName);
@@ -46,7 +48,8 @@ protected AbsPrimitiveSlotsHolder(String typeName) {
      * Utility method that allows setting attributes of type
      * String without the need of wrapping the new value
      * into an AbsPrimitive.
-     * @param name The name of the attribute to be set.
+     *
+     * @param name  The name of the attribute to be set.
      * @param value The new value of the attribute.
      */
     public void set(String name, String value) {
@@ -61,7 +64,8 @@ public void set(String name, AbsObject value) {
      * Utility method that allows setting attributes of type
      * boolean without the need of wrapping the new value
      * into an AbsPrimitive.
-     * @param name The name of the attribute to be set.
+     *
+     * @param name  The name of the attribute to be set.
      * @param value The new value of the attribute.
      */
     public void set(String name, boolean value) {
@@ -72,7 +76,8 @@ public void set(String name, boolean value) {
      * Utility method that allows setting attributes of type
      * int without the need of wrapping the new value
      * into an AbsPrimitive.
-     * @param name The name of the attribute to be set.
+     *
+     * @param name  The name of the attribute to be set.
      * @param value The new value of the attribute.
      */
     public void set(String name, int value) {
@@ -83,7 +88,8 @@ public void set(String name, int value) {
      * Utility method that allows setting attributes of type
      * long without the need of wrapping the new value
      * into an AbsPrimitive.
-     * @param name The name of the attribute to be set.
+     *
+     * @param name  The name of the attribute to be set.
      * @param value The new value of the attribute.
      */
     public void set(String name, long value) {
@@ -96,7 +102,8 @@ public void set(String name, long value) {
      * Utility method that allows setting attributes of type
      * float without the need of wrapping the new value
      * into an AbsPrimitive.
-     * @param name The name of the attribute to be set.
+     *
+     * @param name  The name of the attribute to be set.
      * @param value The new value of the attribute.
      */
     public void set(String name, float value) {
@@ -107,7 +114,8 @@ public void set(String name, float value) {
      * Utility method that allows setting attributes of type
      * double without the need of wrapping the new value
      * into an AbsPrimitive.
-     * @param name The name of the attribute to be set.
+     *
+     * @param name  The name of the attribute to be set.
      * @param value The new value of the attribute.
      */
     public void set(String name, double value) {
@@ -119,7 +127,8 @@ public void set(String name, double value) {
      * Utility method that allows setting attributes of type
      * Date without the need of wrapping the new value
      * into an AbsPrimitive.
-     * @param name The name of the attribute to be set.
+     *
+     * @param name  The name of the attribute to be set.
      * @param value The new value of the attribute.
      */
     public void set(String name, Date value) {
@@ -130,7 +139,8 @@ public void set(String name, Date value) {
      * Utility method that allows setting attributes of type
      * byte[] without the need of wrapping the new value
      * into an AbsPrimitive.
-     * @param name The name of the attribute to be set.
+     *
+     * @param name  The name of the attribute to be set.
      * @param value The new value of the attribute.
      */
     public void set(String name, byte[] value) {
@@ -138,9 +148,10 @@ public void set(String name, byte[] value) {
     }
 
     /**
-     * Utility method that allows getting the value of attributes 
+     * Utility method that allows getting the value of attributes
      * of type String directly as a String
      * i.e. not wrapped into an AbsPrimitive/code>.
+     *
      * @param name The name of the attribute to be retrieved.
      */
     public String getString(String name) {
@@ -153,9 +164,10 @@ public String getString(String name) {
     }
 
     /**
-     * Utility method that allows getting the value of attributes 
+     * Utility method that allows getting the value of attributes
      * of type boolean directly as a boolean
      * i.e. not wrapped into an AbsPrimitive/code>.
+     *
      * @param name The name of the attribute to be retrieved.
      */
     public boolean getBoolean(String name) {
@@ -163,9 +175,10 @@ public boolean getBoolean(String name) {
     }
 
     /**
-     * Utility method that allows getting the value of attributes 
+     * Utility method that allows getting the value of attributes
      * of type int directly as an int
      * i.e. not wrapped into an AbsPrimitive/code>.
+     *
      * @param name The name of the attribute to be retrieved.
      */
     public int getInteger(String name) {
@@ -173,9 +186,10 @@ public int getInteger(String name) {
     }
 
     /**
-     * Utility method that allows getting the value of attributes 
+     * Utility method that allows getting the value of attributes
      * of type long directly as a long
      * i.e. not wrapped into an AbsPrimitive/code>.
+     *
      * @param name The name of the attribute to be retrieved.
      */
     public long getLong(String name) {
@@ -185,9 +199,10 @@ public long getLong(String name) {
     //#MIDP_EXCLUDE_BEGIN
 
     /**
-     * Utility method that allows getting the value of attributes 
+     * Utility method that allows getting the value of attributes
      * of type float directly as a float
      * i.e. not wrapped into an AbsPrimitive/code>.
+     *
      * @param name The name of the attribute to be retrieved.
      */
     public float getFloat(String name) {
@@ -195,9 +210,10 @@ public float getFloat(String name) {
     }
 
     /**
-     * Utility method that allows getting the value of attributes 
+     * Utility method that allows getting the value of attributes
      * of type double directly as a double
      * i.e. not wrapped into an AbsPrimitive/code>.
+     *
      * @param name The name of the attribute to be retrieved.
      */
     public double getDouble(String name) {
@@ -206,9 +222,10 @@ public double getDouble(String name) {
     //#MIDP_EXCLUDE_END
 
     /**
-     * Utility method that allows getting the value of attributes 
+     * Utility method that allows getting the value of attributes
      * of type Date directly as a Date
      * i.e. not wrapped into an AbsPrimitive/code>.
+     *
      * @param name The name of the attribute to be retrieved.
      */
     public Date getDate(String name) {
@@ -221,9 +238,10 @@ public Date getDate(String name) {
     }
 
     /**
-     * Utility method that allows getting the value of attributes 
+     * Utility method that allows getting the value of attributes
      * of type byte[] directly as a byte[]
      * i.e. not wrapped into an AbsPrimitive/code>.
+     *
      * @param name The name of the attribute to be retrieved.
      */
     public byte[] getByteSequence(String name) {
diff --git a/src/jade/content/abs/AbsTerm.java b/src/jade/content/abs/AbsTerm.java
index d3c0e67..199e3ea 100644
--- a/src/jade/content/abs/AbsTerm.java
+++ b/src/jade/content/abs/AbsTerm.java
@@ -28,6 +28,7 @@
 
 /**
  * An abstract descriptor that can hold a term expression.
+ *
  * @author Federico Bergenti - Universita` di Parma
  */
 public interface AbsTerm extends AbsObject, Term {
diff --git a/src/jade/content/abs/AbsVariable.java b/src/jade/content/abs/AbsVariable.java
index 4b6be91..b52dd56 100644
--- a/src/jade/content/abs/AbsVariable.java
+++ b/src/jade/content/abs/AbsVariable.java
@@ -29,9 +29,13 @@
 /**
  * An abstract descriptor that can hold a variable expression, i.e. an
  * entity that is not known yet.
+ *
  * @author Federico Bergenti - Universita` di Parma
  */
 public class AbsVariable extends AbsObjectImpl implements AbsTerm {
+    // Easy way to access the Java class representing AbsVariable.
+    // Useful in MIDP where XXX.class is not available
+    private static Class absVariableClass = null;
     private boolean isMeta = false;
 
     /**
@@ -43,10 +47,10 @@ public AbsVariable() {
 
     /**
      * Construct an AbsVariable with the given name and value type
-     * @param name The name of the variable.
-     * @param valueType The type of values that can be assigned to
-     * this variable.
      *
+     * @param name      The name of the variable.
+     * @param valueType The type of values that can be assigned to
+     *                  this variable.
      */
     public AbsVariable(String name, String valueType) {
         super(VariableSchema.BASE_NAME);
@@ -55,25 +59,21 @@ public AbsVariable(String name, String valueType) {
         setType(valueType);
     }
 
-    /**
-     * Sets the name of this variable.
-     * @param name The new name of this variable.
-     */
-    public void setName(String name) {
-        set(VariableSchema.NAME, AbsPrimitive.wrap(name));
-    }
-
-    /**
-     * Sets the value type of this variable.
-     * @param valueType The type of values that can be assigned to
-     * this variable.
-     */
-    public void setType(String valueType) {
-        set(VariableSchema.VALUE_TYPE, AbsPrimitive.wrap(valueType));
+    public static Class getJavaClass() {
+        if (absVariableClass == null) {
+            try {
+                absVariableClass = (Class) Class.forName("jade.content.abs.AbsVariable");
+            } catch (Exception e) {
+                // Should never happen
+                e.printStackTrace();
+            }
+        }
+        return absVariableClass;
     }
 
     /**
      * Gets the name of this variable.
+     *
      * @return The name of this variable.
      */
     public String getName() {
@@ -85,8 +85,18 @@ public String getName() {
         }
     }
 
+    /**
+     * Sets the name of this variable.
+     *
+     * @param name The new name of this variable.
+     */
+    public void setName(String name) {
+        set(VariableSchema.NAME, AbsPrimitive.wrap(name));
+    }
+
     /**
      * Gets the value type of this variable.
+     *
      * @return The type of values that can be assigned to
      * this variable.
      */
@@ -99,6 +109,16 @@ public String getType() {
         }
     }
 
+    /**
+     * Sets the value type of this variable.
+     *
+     * @param valueType The type of values that can be assigned to
+     *                  this variable.
+     */
+    public void setType(String valueType) {
+        set(VariableSchema.VALUE_TYPE, AbsPrimitive.wrap(valueType));
+    }
+
     /**
      * Redefine the isGrounded() method in order to
      * always return false.
@@ -107,24 +127,10 @@ public boolean isGrounded() {
         return false;
     }
 
-    // Easy way to access the Java class representing AbsVariable.
-    // Useful in MIDP where XXX.class is not available
-    private static Class absVariableClass = null;
-
-    public static Class getJavaClass() {
-        if (absVariableClass == null) {
-            try {
-                absVariableClass = (Class) Class.forName("jade.content.abs.AbsVariable");
-            } catch (Exception e) {
-                // Should never happen
-                e.printStackTrace();
-            }
-        }
-        return absVariableClass;
-    }
-
-    /** Return true if this object represents a meta term (i.e. symbol ??x) rather than a concrete variable.
+    /**
+     * Return true if this object represents a meta term (i.e. symbol ??x) rather than a concrete variable.
      * This method is currently used only by the semantics framework.
+     *
      * @return true if this object represents a meta term
      * @since JADE3.4
      **/
@@ -132,8 +138,10 @@ public final boolean isMetaTerm() {
         return isMeta;
     }
 
-    /** Sets the value of isMetaTerm, where the default is false.
+    /**
+     * Sets the value of isMetaTerm, where the default is false.
      * This method is currently used only by the semantics framework.
+     *
      * @since JADE3.4
      **/
     public final void setIsMetaTerm(boolean isMeta) {
diff --git a/src/jade/content/frame/Frame.java b/src/jade/content/frame/Frame.java
index 8d70328..9772c8f 100644
--- a/src/jade/content/frame/Frame.java
+++ b/src/jade/content/frame/Frame.java
@@ -25,19 +25,20 @@
 package jade.content.frame;
 
 /**
- Generic interface representing all non-primitive elements
- that can appear in a content expression.
- Each frame has a type-name accessible by means of the
- getTypeName() method and a number of composing
- elements that can be primitive elements or frames themselves.
- The way composing elements are stored within and retrieved
- from a Frame depends on the specific type of Frame.
- @see OrderedFrame, QualifiedFrame
- @author Giovanni Caire - TILAB
+ * Generic interface representing all non-primitive elements
+ * that can appear in a content expression.
+ * Each frame has a type-name accessible by means of the
+ * getTypeName() method and a number of composing
+ * elements that can be primitive elements or frames themselves.
+ * The way composing elements are stored within and retrieved
+ * from a Frame depends on the specific type of Frame.
+ *
+ * @author Giovanni Caire - TILAB
+ * @see OrderedFrame, QualifiedFrame
  */
 public interface Frame {
     /**
-     @return the type-name of this Frame
+     * @return the type-name of this Frame
      */
     String getTypeName();
 }
diff --git a/src/jade/content/frame/FrameException.java b/src/jade/content/frame/FrameException.java
index 1c962e6..2e37053 100644
--- a/src/jade/content/frame/FrameException.java
+++ b/src/jade/content/frame/FrameException.java
@@ -34,8 +34,9 @@
 public class FrameException extends WrapperException {
 
     /**
-     Construct a FrameException with a given message.
-     @param message the message
+     * Construct a FrameException with a given message.
+     *
+     * @param message the message
      */
     public FrameException(String message) {
         super(message);
@@ -43,10 +44,11 @@ public FrameException(String message) {
 
 
     /**
-     Construct a FrameException with a given message
-     and a given nested Throwable.
-     @param message The message
-     @param t The nested Throwable
+     * Construct a FrameException with a given message
+     * and a given nested Throwable.
+     *
+     * @param message The message
+     * @param t       The nested Throwable
      */
     public FrameException(String message, Throwable t) {
         super(message, t);
diff --git a/src/jade/content/frame/LEAPFrameCodec.java b/src/jade/content/frame/LEAPFrameCodec.java
index 1d0daca..72c1f8c 100644
--- a/src/jade/content/frame/LEAPFrameCodec.java
+++ b/src/jade/content/frame/LEAPFrameCodec.java
@@ -34,51 +34,47 @@
 import java.util.Vector;
 
 /**
- @author Giovanni Caire - TILAB
+ * @author Giovanni Caire - TILAB
  */
 public class LEAPFrameCodec implements Serializable {
     public static final String NAME = "LEAP";
-
-    private transient ByteArrayOutputStream outBuffer = new ByteArrayOutputStream();
-    private transient DataOutputStream outStream = new DataOutputStream(outBuffer);
-    private transient Vector stringReferences = new Vector<>();
-
-    //#MIDP_EXCLUDE_BEGIN
-    @Serial
-    private void readObject(ObjectInputStream oin) throws IOException, ClassNotFoundException {
-        oin.defaultReadObject();
-        outBuffer = new ByteArrayOutputStream();
-        outStream = new DataOutputStream(outBuffer);
-        stringReferences = new Vector<>();
-    }
-    //#MIDP_EXCLUDE_END
-
     // Primitive types
     private static final byte STRING = 6;
     private static final byte BOOLEAN = 7;
     private static final byte INTEGER = 8;
     private static final byte FLOAT = 9;
+    //#MIDP_EXCLUDE_END
     private static final byte DATE = 10;
     private static final byte BYTE_SEQUENCE = 11;
-
     // Structured types
     private static final byte AGGREGATE = 1;
     private static final byte CONTENT_ELEMENT_LIST = 2;
     private static final byte OBJECT = 3;
-
     // Markers for structured types
     private static final byte ELEMENT = 4;
     private static final byte END = 5;
-
     // Modifiers for string encoding
     private static final byte MODIFIER = (byte) 0x10; // Only bit five set to 1
     private static final byte UNMODIFIER = (byte) 0xEF; // Only bit five cleared to 1
+    private transient ByteArrayOutputStream outBuffer = new ByteArrayOutputStream();
+    private transient DataOutputStream outStream = new DataOutputStream(outBuffer);
+    private transient Vector stringReferences = new Vector<>();
+
+    //#MIDP_EXCLUDE_BEGIN
+    @Serial
+    private void readObject(ObjectInputStream oin) throws IOException, ClassNotFoundException {
+        oin.defaultReadObject();
+        outBuffer = new ByteArrayOutputStream();
+        outStream = new DataOutputStream(outBuffer);
+        stringReferences = new Vector<>();
+    }
 
     /**
-     Transform a Frame into a sequence of bytes encoded according to the
-     LEAP language
-     @param content The Frame to be transformed
-     @throws FrameException
+     * Transform a Frame into a sequence of bytes encoded according to the
+     * LEAP language
+     *
+     * @param content The Frame to be transformed
+     * @throws FrameException
      */
     public synchronized byte[] encode(Frame content) throws FrameException {
         if (content == null) {
@@ -98,10 +94,11 @@ public synchronized byte[] encode(Frame content) throws FrameException {
     }
 
     /**
-     Transform a sequence of bytes encoded according to the LEAP 
-     language into a Frame 
-     @param content The sequence of bytes to be transformed.
-     @throws FrameException
+     * Transform a sequence of bytes encoded according to the LEAP
+     * language into a Frame
+     *
+     * @param content The sequence of bytes to be transformed.
+     * @throws FrameException
      */
     public synchronized Frame decode(byte[] content) throws FrameException {
         if (content == null || content.length == 0) {
@@ -132,6 +129,7 @@ public synchronized Frame decode(byte[] content) throws FrameException {
     }
 
     /**
+     *
      */
     private void write(DataOutputStream stream, Object obj) throws Throwable {
         // PRIMITIVES
@@ -200,6 +198,7 @@ else if (obj instanceof AID) {
     }
 
     /**
+     *
      */
     private Object read(DataInputStream stream) throws Throwable {
         Object obj;
diff --git a/src/jade/content/frame/OrderedFrame.java b/src/jade/content/frame/OrderedFrame.java
index 48aadd4..e5c969d 100644
--- a/src/jade/content/frame/OrderedFrame.java
+++ b/src/jade/content/frame/OrderedFrame.java
@@ -27,17 +27,19 @@
 import java.util.Vector;
 
 /**
- Generic class representing all frames (such as aggregates
- and content-element-lists) whose composing elements can be
- retrieved by an index.
- @author Giovanni Caire - TILAB
+ * Generic class representing all frames (such as aggregates
+ * and content-element-lists) whose composing elements can be
+ * retrieved by an index.
+ *
+ * @author Giovanni Caire - TILAB
  */
 public class OrderedFrame extends Vector implements Frame {
     private final String typeName;
 
     /**
-     Create an OrderedFrame with a given type-name.
-     @param typeName The type-name of the OrderedFrame to be created.
+     * Create an OrderedFrame with a given type-name.
+     *
+     * @param typeName The type-name of the OrderedFrame to be created.
      */
     public OrderedFrame(String typeName) {
         super();
@@ -45,8 +47,9 @@ public OrderedFrame(String typeName) {
     }
 
     /**
-     Retrieve the type-name of this OrderedFrame.
-     @return the type-name of this OrderedFrame
+     * Retrieve the type-name of this OrderedFrame.
+     *
+     * @return the type-name of this OrderedFrame
      */
     public String getTypeName() {
         return typeName;
diff --git a/src/jade/content/frame/QualifiedFrame.java b/src/jade/content/frame/QualifiedFrame.java
index 9112045..2cfd310 100644
--- a/src/jade/content/frame/QualifiedFrame.java
+++ b/src/jade/content/frame/QualifiedFrame.java
@@ -27,17 +27,19 @@
 import java.util.Hashtable;
 
 /**
- Generic class representing all frames (such as concepts and
- predicates) whose composing elements can be retrieved by a
- unique name.
- @author Giovanni Caire - TILAB
+ * Generic class representing all frames (such as concepts and
+ * predicates) whose composing elements can be retrieved by a
+ * unique name.
+ *
+ * @author Giovanni Caire - TILAB
  */
 public class QualifiedFrame extends Hashtable implements Frame {
     private final String typeName;
 
     /**
-     Create a QualifiedFrame with a given type-name.
-     @param typeName The type-name of the QualifiedFrame to be created.
+     * Create a QualifiedFrame with a given type-name.
+     *
+     * @param typeName The type-name of the QualifiedFrame to be created.
      */
     public QualifiedFrame(String typeName) {
         super();
@@ -45,18 +47,20 @@ public QualifiedFrame(String typeName) {
     }
 
     /**
-     Retrieve the type-name of this QualifiedFrame.
-     @return the type-name of this QualifiedFrame
+     * Retrieve the type-name of this QualifiedFrame.
+     *
+     * @return the type-name of this QualifiedFrame
      */
     public String getTypeName() {
         return typeName;
     }
 
     /**
-     Redefine the put() method so that keys must be String and
-     setting a null value for a given key is interpreted as
-     removing the entry.
-     @exception ClassCastException if key is not a String
+     * Redefine the put() method so that keys must be String and
+     * setting a null value for a given key is interpreted as
+     * removing the entry.
+     *
+     * @throws ClassCastException if key is not a String
      */
     public Object put(Object key, Object val) {
         if (val != null) {
@@ -67,32 +71,32 @@ public Object put(Object key, Object val) {
     }
 
     /**
-     Utility method to put a value of type int in this
-     Frame.
+     * Utility method to put a value of type int in this
+     * Frame.
      */
     public Object putInteger(Object key, int val) {
         return put(key, (long) val);
     }
 
     /**
-     Utility method to retrieve a value of type int from this
-     Frame.
+     * Utility method to retrieve a value of type int from this
+     * Frame.
      */
     public int getInteger(Object key) {
         return (int) (((Long) get(key)).longValue());
     }
 
     /**
-     Utility method to put a value of type boolean in this
-     Frame.
+     * Utility method to put a value of type boolean in this
+     * Frame.
      */
     public Object putBoolean(Object key, boolean val) {
         return put(key, val);
     }
 
     /**
-     Utility method to retrieve a value of type boolean from this
-     Frame.
+     * Utility method to retrieve a value of type boolean from this
+     * Frame.
      */
     public boolean getBoolean(Object key) {
         return (Boolean) get(key);
diff --git a/src/jade/content/frame/package.html b/src/jade/content/frame/package.html
index 497c89b..e89b94e 100644
--- a/src/jade/content/frame/package.html
+++ b/src/jade/content/frame/package.html
@@ -1,12 +1,12 @@
-
+
 
 
-    
-    
-    
-    
-    
+    
+    
+    
+    
+    
     Though compatible with MIDP1
     
 
+
     
     
 
diff --git a/src/jade/content/lang/ByteArrayCodec.java b/src/jade/content/lang/ByteArrayCodec.java
index fe0180b..c4e9c7e 100644
--- a/src/jade/content/lang/ByteArrayCodec.java
+++ b/src/jade/content/lang/ByteArrayCodec.java
@@ -28,8 +28,9 @@
 import jade.content.onto.Ontology;
 
 /**
- * Base class for content language codecs that transform 
+ * Base class for content language codecs that transform
  * AbsContentElements to/from sequences of bytes
+ *
  * @author Giovanni Caire - TILAB
  */
 public abstract class ByteArrayCodec extends Codec {
@@ -43,6 +44,7 @@ public ByteArrayCodec(String name) {
 
     /**
      * Encodes a content into a byte array.
+     *
      * @param content the content as an abstract descriptor.
      * @return the content as a byte array.
      * @throws CodecException
@@ -52,8 +54,9 @@ public abstract byte[] encode(AbsContentElement content)
 
     /**
      * Encodes a content into a byte array.
-     * @param ontology the ontology 
-     * @param content the content as an abstract descriptor.
+     *
+     * @param ontology the ontology
+     * @param content  the content as an abstract descriptor.
      * @return the content as a byte array.
      * @throws CodecException
      */
@@ -62,6 +65,7 @@ public abstract byte[] encode(Ontology ontology, AbsContentElement content)
 
     /**
      * Decodes the content to an abstract description.
+     *
      * @param content the content as a byte array.
      * @return the content as an abstract description.
      * @throws CodecException
@@ -71,8 +75,9 @@ public abstract AbsContentElement decode(byte[] content)
 
     /**
      * Decodes the content to an abstract description.
+     *
      * @param ontology the ontology.
-     * @param content the content as a byte array.
+     * @param content  the content as a byte array.
      * @return the content as an abstract description.
      * @throws CodecException
      */
diff --git a/src/jade/content/lang/Codec.java b/src/jade/content/lang/Codec.java
index c2597fe..3a53c50 100644
--- a/src/jade/content/lang/Codec.java
+++ b/src/jade/content/lang/Codec.java
@@ -31,41 +31,15 @@
 
 /**
  * Generic base class for al content language codecs
+ *
  * @author Federico Bergenti - Universita` di Parma
  */
 public abstract class Codec implements Serializable {
 
     /**
-     * Class CodecException.
-     *
-     * @author Federico Bergenti
-     */
-    public static class CodecException extends ContentException {
-
-        /**
-         * Constructor
-         *
-         * @param message the message.
-         *
-         */
-        public CodecException(String message) {
-            super(message);
-        }
-
-        /**
-         Construct a new CodecException
-         @param msg The message for this exception.
-         @param t The exception wrapped by this object.
-         */
-        public CodecException(String msg, Throwable t) {
-            super(msg, t);
-        }
-
-    }
-
-    /** This string is the prefix of all the unnamed slots of a Frame **/
+     * This string is the prefix of all the unnamed slots of a Frame
+     **/
     public static String UNNAMEDPREFIX = "_JADE.UNNAMED";
-
     private String name = null;
 
     /**
@@ -77,6 +51,7 @@ protected Codec(String name) {
 
     /**
      * Gets the name of this codec.
+     *
      * @return the name of this codec.
      */
     public String getName() {
@@ -90,5 +65,33 @@ public String getName() {
     public Ontology getInnerOntology() {
         return null;
     }
+
+    /**
+     * Class CodecException.
+     *
+     * @author Federico Bergenti
+     */
+    public static class CodecException extends ContentException {
+
+        /**
+         * Constructor
+         *
+         * @param message the message.
+         */
+        public CodecException(String message) {
+            super(message);
+        }
+
+        /**
+         * Construct a new CodecException
+         *
+         * @param msg The message for this exception.
+         * @param t   The exception wrapped by this object.
+         */
+        public CodecException(String msg, Throwable t) {
+            super(msg, t);
+        }
+
+    }
 }
 
diff --git a/src/jade/content/lang/StringCodec.java b/src/jade/content/lang/StringCodec.java
index e976d36..5acc304 100644
--- a/src/jade/content/lang/StringCodec.java
+++ b/src/jade/content/lang/StringCodec.java
@@ -28,8 +28,9 @@
 import jade.content.onto.Ontology;
 
 /**
- * Base class for content language codecs that transform 
+ * Base class for content language codecs that transform
  * AbsContentElements to/from sequences of strings
+ *
  * @author Giovanni Caire - TILAB
  */
 public abstract class StringCodec extends Codec {
@@ -43,6 +44,7 @@ public StringCodec(String name) {
 
     /**
      * Encodes a content into a string.
+     *
      * @param content the content as an abstract descriptor.
      * @return the content as a string.
      * @throws CodecException
@@ -52,8 +54,9 @@ public abstract String encode(AbsContentElement content)
 
     /**
      * Encodes a content into a string using a given ontology.
-     * @param ontology the ontology 
-     * @param content the content as an abstract descriptor.
+     *
+     * @param ontology the ontology
+     * @param content  the content as an abstract descriptor.
      * @return the content as a string.
      * @throws CodecException
      */
@@ -62,6 +65,7 @@ public abstract String encode(Ontology ontology, AbsContentElement content)
 
     /**
      * Decodes the content to an abstract description.
+     *
      * @param content the content as a string.
      * @return the content as an abstract description.
      * @throws CodecException
@@ -70,10 +74,11 @@ public abstract AbsContentElement decode(String content)
             throws CodecException;
 
     /**
-     * Decodes the content to an abstract description using a 
+     * Decodes the content to an abstract description using a
      * given ontology.
+     *
      * @param ontology the ontology.
-     * @param content the content as a string.
+     * @param content  the content as a string.
      * @return the content as an abstract description.
      * @throws CodecException
      */
diff --git a/src/jade/content/lang/leap/LEAPCodec.java b/src/jade/content/lang/leap/LEAPCodec.java
index c0b1e57..23abaee 100644
--- a/src/jade/content/lang/leap/LEAPCodec.java
+++ b/src/jade/content/lang/leap/LEAPCodec.java
@@ -35,35 +35,20 @@
 
 /**
  * Content language codec for the LEAP language
+ *
  * @author Federico Bergenti - Universita` di Parma
  */
 public class LEAPCodec extends ByteArrayCodec {
     public static final String NAME = "LEAP";
-
-    private transient ByteArrayOutputStream outBuffer = new ByteArrayOutputStream();
-    private transient DataOutputStream outStream = new DataOutputStream(outBuffer);
-    private transient Vector stringReferences = new Vector<>();
-
-    //#MIDP_EXCLUDE_BEGIN
-    @Serial
-    private void readObject(ObjectInputStream oin) throws IOException, ClassNotFoundException {
-        oin.defaultReadObject();
-        outBuffer = new ByteArrayOutputStream();
-        outStream = new DataOutputStream(outBuffer);
-        stringReferences = new Vector<>();
-    }
-    //#MIDP_EXCLUDE_END
-
     // Types
     private static final byte PRIMITIVE = 0;
     private static final byte AGGREGATE = 1;
     private static final byte CONTENT_ELEMENT_LIST = 2;
     private static final byte OBJECT = 3;
-
+    //#MIDP_EXCLUDE_END
     // Markers for structured types
     private static final byte ELEMENT = 4;
     private static final byte END = 5;
-
     // Primitive types
     private static final byte STRING = 6;
     private static final byte BOOLEAN = 7;
@@ -74,10 +59,18 @@ private void readObject(ObjectInputStream oin) throws IOException, ClassNotFound
     private static final byte DATE = 12;
     private static final byte BYTE_SEQUENCE = 13;
     private static final byte BIG_STRING = 14;
-
     // Modifiers
     private static final byte MODIFIER = (byte) 0x10; // Only bit five set to 1
     private static final byte UNMODIFIER = (byte) 0xEF; // Only bit five cleared to 1
+    private transient ByteArrayOutputStream outBuffer = new ByteArrayOutputStream();
+    private transient DataOutputStream outStream = new DataOutputStream(outBuffer);
+    private transient Vector stringReferences = new Vector<>();
+    /**
+     * Construct a LEAPCodec object i.e. a Codec for the LEAP language
+     */
+    public LEAPCodec() {
+        super(NAME);
+    }
 
 	/* LEAP Language operators
     public static final String INSTANCEOF = "INSTANCEOF";
@@ -87,16 +80,19 @@ private void readObject(ObjectInputStream oin) throws IOException, ClassNotFound
     public static final String IOTA = "IOTA";
 	 */
 
-    /**
-     * Construct a LEAPCodec object i.e. a Codec for the LEAP language
-     */
-    public LEAPCodec() {
-        super(NAME);
+    //#MIDP_EXCLUDE_BEGIN
+    @Serial
+    private void readObject(ObjectInputStream oin) throws IOException, ClassNotFoundException {
+        oin.defaultReadObject();
+        outBuffer = new ByteArrayOutputStream();
+        outStream = new DataOutputStream(outBuffer);
+        stringReferences = new Vector<>();
     }
 
     /**
      * Encodes an abstract descriptor holding a content element
      * into a byte array.
+     *
      * @param content the content as an abstract descriptor.
      * @return the content as a byte array.
      * @throws CodecException
@@ -115,8 +111,9 @@ public synchronized byte[] encode(AbsContentElement content) throws CodecExcepti
 
     /**
      * Encodes a content into a byte array.
+     *
      * @param ontology the ontology
-     * @param content the content as an abstract descriptor.
+     * @param content  the content as an abstract descriptor.
      * @return the content as a byte array.
      * @throws CodecException
      */
@@ -126,6 +123,7 @@ public byte[] encode(Ontology ontology, AbsContentElement content) throws CodecE
 
     /**
      * Decodes the content to an abstract descriptor.
+     *
      * @param content the content as a byte array.
      * @return the content as an abstract description.
      * @throws CodecException
@@ -136,8 +134,9 @@ public AbsContentElement decode(byte[] content) throws CodecException {
 
     /**
      * Decodes the content to an abstract description.
+     *
      * @param ontology the ontology.
-     * @param content the content as a byte array.
+     * @param content  the content as a byte array.
      * @return the content as an abstract description.
      * @throws CodecException
      */
diff --git a/src/jade/content/lang/sl/ExtendedSLParser.java b/src/jade/content/lang/sl/ExtendedSLParser.java
index 41ab4a1..8dce424 100644
--- a/src/jade/content/lang/sl/ExtendedSLParser.java
+++ b/src/jade/content/lang/sl/ExtendedSLParser.java
@@ -25,10 +25,136 @@
 class ExtendedSLParser implements ExtendedSLParserConstants {
 
     private static final String META_EXCEPTION_MESSAGE = "Meta SL expressions are not allowed";
+    static private int[] jj_la1_0;
+    static private int[] jj_la1_1;
+
+    static {
+        jj_la1_init_0();
+        jj_la1_init_1();
+    }
+
     /**
      * This variable is true, when meta symbols are allowed (metas are a semantics-specific extension to the SL Grammar)
      **/
     private final boolean metaAllowed = true; //FIXME to do set/unset this variable
+    final private int[] jj_la1 = new int[23];
+    private final List jj_expentries = new ArrayList<>();
+    /**
+     * Generated Token Manager.
+     */
+    public ExtendedSLParserTokenManager token_source;
+    /**
+     * Current token.
+     */
+    public Token token;
+    /**
+     * Next token.
+     */
+    public Token jj_nt;
+
+    /*   P R O D U C T I O N    R U L E S  */
+    Ontology curOntology = null;
+    /**
+     * (0 for FIPa-SL0, 1 for SL1, 2 for SL2, >2 for full SL)
+     **/
+    int slType = 3;
+
+    // lbrace2 in the OperatorState of the Token Manager
+    SimpleCharStream jj_input_stream;
+    private int jj_ntk;
+    private int jj_gen;
+    private int[] jj_expentry;
+    private int jj_kind = -1;
+
+    /**
+     * Constructor with InputStream.
+     */
+    public ExtendedSLParser(java.io.InputStream stream) {
+        this(stream, null);
+    }
+
+    /**
+     * Constructor with InputStream and supplied encoding
+     */
+    public ExtendedSLParser(java.io.InputStream stream, String encoding) {
+        try {
+            jj_input_stream = new SimpleCharStream(stream, encoding, 1, 1);
+        } catch (UnsupportedEncodingException e) {
+            throw new RuntimeException(e.getMessage(), e);
+        }
+        token_source = new ExtendedSLParserTokenManager(jj_input_stream);
+        token = new Token();
+        jj_ntk = -1;
+        jj_gen = 0;
+        for (int i = 0; i < 23; i++) jj_la1[i] = -1;
+    }
+
+    /**
+     * Constructor.
+     */
+    public ExtendedSLParser(java.io.Reader stream) {
+        jj_input_stream = new SimpleCharStream(stream, 1, 1);
+        token_source = new ExtendedSLParserTokenManager(jj_input_stream);
+        token = new Token();
+        jj_ntk = -1;
+        jj_gen = 0;
+        for (int i = 0; i < 23; i++) jj_la1[i] = -1;
+    }
+
+    /**
+     * Constructor with generated Token Manager.
+     */
+    public ExtendedSLParser(ExtendedSLParserTokenManager tm) {
+        token_source = tm;
+        token = new Token();
+        jj_ntk = -1;
+        jj_gen = 0;
+        for (int i = 0; i < 23; i++) jj_la1[i] = -1;
+    }
+
+    public static void main(String[] args) {
+
+        ExtendedSLParser theParser = null;
+        try {
+            theParser = new ExtendedSLParser(System.in);
+            theParser.setSLType(Integer.parseInt(args[0]));
+        } catch (Exception e) {
+            System.out.println("usage: ExtendedSLParser SLLevel\u005cn  where SLLevel can be 0 for SL0, 1 for SL1, 2 for SL2, 3 or more for full SL");
+            System.exit(0);
+        }
+        if (theParser.slType < 3)
+            System.out.println("SL-" + theParser.slType + " Parser Started ...");
+        else
+            System.out.println("Full-SL" + " Parser Started ...");
+
+        SLCodec codec = new SLCodec();
+        //Ontology o = new DefaultOntology();
+
+        while (true) {
+            System.out.println("insert an SL expression to parse: ");
+            try {
+                AbsContentElementList result = theParser.Content();
+                String resultEncoded = codec.encode(result);
+                System.out.println("\u005cn\u005cn RESULT of ExtendedSLParser.Content()=\u005cn" + resultEncoded);
+                AbsContentElement result2 = codec.decode(resultEncoded);
+                System.out.println("\u005cn\u005cn RESULT of SLCodec.decode(SLCodec.encode(ExtendedSLParser.Content()))=\u005cn" + codec.encode(result2));
+                System.out.println("\u005cn\u005cn");
+                //result.dump();
+                //System.out.println("AFTER ENCODING: "+codec.encode(result,o));
+            } catch (Exception pe) {
+                pe.printStackTrace();
+                System.exit(0);
+            }
+        }
+    }
+
+    private static void jj_la1_init_0() {
+        jj_la1_0 = new int[]{0x210c020, 0x2000020, 0x4000040, 0x210c020, 0xb800c000, 0x5800c000, 0x21cffa0, 0xcff00, 0x21fffa0, 0x4000c000, 0x21cffa0, 0x30000, 0x21fffa0, 0x30000, 0x8000000, 0x2100020, 0x210c020, 0x210c020, 0x21cffa0, 0xa000c000, 0x3f00, 0xc000, 0x100000,};
+    }
+
+    private static void jj_la1_init_1() {
+        jj_la1_1 = new int[]{0x70, 0x0, 0x0, 0x70, 0x3f, 0x31, 0x70, 0x30, 0x70, 0x30, 0x70, 0x0, 0x70, 0x0, 0x1, 0x40, 0x70, 0x70, 0x70, 0x3e, 0x0, 0x30, 0x40,};
+    }
 
     /* Take a quoted FIPA SL0 String and convert to a
      * normal Java-style String.  Remove the
@@ -48,7 +174,6 @@ private String unescape(String s) {
         return result.toString();
     }
 
-
     /**
      * When an ActionExpression is parsed, if it is an AbsConcept then
      * it must be casted upto an AbsAgentAction.
@@ -75,9 +200,6 @@ void setSLType(int slType) {
         this.slType = slType;
     }
 
-
-    Ontology curOntology = null;
-
     /**
      * Reinitialize the parser such as it is ready to parse a new expression.
      *
@@ -106,49 +228,6 @@ AbsContentElement parse(Ontology o, String content) throws ParseException, Token
             return tuple.get(0);
     }
 
-    /**
-     * (0 for FIPa-SL0, 1 for SL1, 2 for SL2, >2 for full SL)
-     **/
-    int slType = 3;
-
-    public static void main(String[] args) {
-
-        ExtendedSLParser theParser = null;
-        try {
-            theParser = new ExtendedSLParser(System.in);
-            theParser.setSLType(Integer.parseInt(args[0]));
-        } catch (Exception e) {
-            System.out.println("usage: ExtendedSLParser SLLevel\u005cn  where SLLevel can be 0 for SL0, 1 for SL1, 2 for SL2, 3 or more for full SL");
-            System.exit(0);
-        }
-        if (theParser.slType < 3)
-            System.out.println("SL-" + theParser.slType + " Parser Started ...");
-        else
-            System.out.println("Full-SL" + " Parser Started ...");
-
-        SLCodec codec = new SLCodec();
-        //Ontology o = new DefaultOntology();
-
-        while (true) {
-            System.out.println("insert an SL expression to parse: ");
-            try {
-                AbsContentElementList result = theParser.Content();
-                String resultEncoded = codec.encode(result);
-                System.out.println("\u005cn\u005cn RESULT of ExtendedSLParser.Content()=\u005cn" + resultEncoded);
-                AbsContentElement result2 = codec.decode(resultEncoded);
-                System.out.println("\u005cn\u005cn RESULT of SLCodec.decode(SLCodec.encode(ExtendedSLParser.Content()))=\u005cn" + codec.encode(result2));
-                System.out.println("\u005cn\u005cn");
-                //result.dump();
-                //System.out.println("AFTER ENCODING: "+codec.encode(result,o));
-            } catch (Exception pe) {
-                pe.printStackTrace();
-                System.exit(0);
-            }
-        }
-    }
-
-    /*   P R O D U C T I O N    R U L E S  */
-
     /**
      * This production rule represents the more general expression that can
      * serve as content for an ACL message. Since different communicative
@@ -201,8 +280,6 @@ final public void LBrace() throws ParseException {
         }
     }
 
-    // lbrace2 in the OperatorState of the Token Manager
-
     /**
      * Right Brace in all of the possible states of the Token Manager
      **/
@@ -951,61 +1028,6 @@ final public String MetaSymbol() throws ParseException {
         throw new Error("Missing return statement in function");
     }
 
-    /**
-     * Generated Token Manager.
-     */
-    public ExtendedSLParserTokenManager token_source;
-    SimpleCharStream jj_input_stream;
-    /**
-     * Current token.
-     */
-    public Token token;
-    /**
-     * Next token.
-     */
-    public Token jj_nt;
-    private int jj_ntk;
-    private int jj_gen;
-    final private int[] jj_la1 = new int[23];
-    static private int[] jj_la1_0;
-    static private int[] jj_la1_1;
-
-    static {
-        jj_la1_init_0();
-        jj_la1_init_1();
-    }
-
-    private static void jj_la1_init_0() {
-        jj_la1_0 = new int[]{0x210c020, 0x2000020, 0x4000040, 0x210c020, 0xb800c000, 0x5800c000, 0x21cffa0, 0xcff00, 0x21fffa0, 0x4000c000, 0x21cffa0, 0x30000, 0x21fffa0, 0x30000, 0x8000000, 0x2100020, 0x210c020, 0x210c020, 0x21cffa0, 0xa000c000, 0x3f00, 0xc000, 0x100000,};
-    }
-
-    private static void jj_la1_init_1() {
-        jj_la1_1 = new int[]{0x70, 0x0, 0x0, 0x70, 0x3f, 0x31, 0x70, 0x30, 0x70, 0x30, 0x70, 0x0, 0x70, 0x0, 0x1, 0x40, 0x70, 0x70, 0x70, 0x3e, 0x0, 0x30, 0x40,};
-    }
-
-    /**
-     * Constructor with InputStream.
-     */
-    public ExtendedSLParser(java.io.InputStream stream) {
-        this(stream, null);
-    }
-
-    /**
-     * Constructor with InputStream and supplied encoding
-     */
-    public ExtendedSLParser(java.io.InputStream stream, String encoding) {
-        try {
-            jj_input_stream = new SimpleCharStream(stream, encoding, 1, 1);
-        } catch (UnsupportedEncodingException e) {
-            throw new RuntimeException(e.getMessage(), e);
-        }
-        token_source = new ExtendedSLParserTokenManager(jj_input_stream);
-        token = new Token();
-        jj_ntk = -1;
-        jj_gen = 0;
-        for (int i = 0; i < 23; i++) jj_la1[i] = -1;
-    }
-
     /**
      * Reinitialise.
      */
@@ -1029,18 +1051,6 @@ public void ReInit(java.io.InputStream stream, String encoding) {
         for (int i = 0; i < 23; i++) jj_la1[i] = -1;
     }
 
-    /**
-     * Constructor.
-     */
-    public ExtendedSLParser(java.io.Reader stream) {
-        jj_input_stream = new SimpleCharStream(stream, 1, 1);
-        token_source = new ExtendedSLParserTokenManager(jj_input_stream);
-        token = new Token();
-        jj_ntk = -1;
-        jj_gen = 0;
-        for (int i = 0; i < 23; i++) jj_la1[i] = -1;
-    }
-
     /**
      * Reinitialise.
      */
@@ -1053,17 +1063,6 @@ public void ReInit(java.io.Reader stream) {
         for (int i = 0; i < 23; i++) jj_la1[i] = -1;
     }
 
-    /**
-     * Constructor with generated Token Manager.
-     */
-    public ExtendedSLParser(ExtendedSLParserTokenManager tm) {
-        token_source = tm;
-        token = new Token();
-        jj_ntk = -1;
-        jj_gen = 0;
-        for (int i = 0; i < 23; i++) jj_la1[i] = -1;
-    }
-
     /**
      * Reinitialise.
      */
@@ -1089,7 +1088,6 @@ private Token jj_consume_token(int kind) throws ParseException {
         throw generateParseException();
     }
 
-
     /**
      * Get the next Token.
      */
@@ -1120,10 +1118,6 @@ private int jj_ntk() {
             return (jj_ntk = jj_nt.kind);
     }
 
-    private final List jj_expentries = new ArrayList<>();
-    private int[] jj_expentry;
-    private int jj_kind = -1;
-
     /**
      * Generate ParseException.
      */
diff --git a/src/jade/content/lang/sl/ExtendedSLParserTokenManager.java b/src/jade/content/lang/sl/ExtendedSLParserTokenManager.java
index 1386942..7b69542 100644
--- a/src/jade/content/lang/sl/ExtendedSLParserTokenManager.java
+++ b/src/jade/content/lang/sl/ExtendedSLParserTokenManager.java
@@ -7,10 +7,86 @@
  * Token Manager.
  */
 public class ExtendedSLParserTokenManager implements ExtendedSLParserConstants {
+    /**
+     * Token literal values.
+     */
+    public static final String[] jjstrLiteralImages = {
+            "", null, null, null, null, "\50", "\51", null, null, null, null, null, null,
+            null, null, null, null, null, null, null, null, null, null, null, null, "\50",
+            "\51", null, null, null, null, null, null, null, null, null, null, null, null,};
+    /**
+     * Lexer state names.
+     */
+    public static final String[] lexStateNames = {
+            "DEFAULT",
+            "OPERATORSTATE",
+    };
+    /**
+     * Lex State array.
+     */
+    public static final int[] jjnewLexState = {
+            -1, -1, -1, -1, -1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+            -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    };
+    static final long[] jjbitVec0 = {
+            0xfffffffffffffffeL, 0xffffffffffffffffL, 0xffffffffffffffffL, 0xffffffffffffffffL
+    };
+    static final long[] jjbitVec2 = {
+            0x0L, 0x0L, 0xffffffffffffffffL, 0xffffffffffffffffL
+    };
+    static final int[] jjnextStates = {
+            14, 16, 17, 55, 60, 46, 48, 50, 38, 43, 25, 31, 27, 28, 29, 48,
+            49, 51, 30, 35, 36, 43, 44, 46, 39, 53, 73, 75, 6, 8, 9, 19,
+            21, 27, 0, 28, 30, 35, 39, 42, 47, 22, 24, 25, 43, 44, 46, 39,
+            48, 49, 51, 30, 76, 78, 79, 33, 34, 37, 38,
+    };
+    static final long[] jjtoToken = {
+            0x7ffe1fffe1L,
+    };
+    static final long[] jjtoSkip = {
+            0x1e0001eL,
+    };
+    private final int[] jjrounds = new int[80];
+    private final int[] jjstateSet = new int[160];
+    private final StringBuffer jjimage = new StringBuffer();
     /**
      * Debug output.
      */
     public java.io.PrintStream debugStream = System.out;
+    protected SimpleCharStream input_stream;
+    protected char curChar;
+    int curLexState = 0;
+    int defaultLexState = 0;
+    int jjnewStateCnt;
+    int jjround;
+    int jjmatchedPos;
+    int jjmatchedKind;
+    private StringBuffer image = jjimage;
+    private int jjimageLen;
+    private int lengthOfMatch;
+
+    /**
+     * Constructor.
+     */
+    public ExtendedSLParserTokenManager(SimpleCharStream stream) {
+        if (SimpleCharStream.staticFlag)
+            throw new Error("ERROR: Cannot use a static CharStream class with a non-static lexical analyzer.");
+        input_stream = stream;
+    }
+    /**
+     * Constructor.
+     */
+    public ExtendedSLParserTokenManager(SimpleCharStream stream, int lexState) {
+        this(stream);
+        SwitchTo(lexState);
+    }
+
+    private static boolean jjCanMove_0(int hiByte, int i1, int i2, long l1, long l2) {
+        return switch (hiByte) {
+            case 0 -> ((jjbitVec2[i2] & l2) != 0L);
+            default -> (jjbitVec0[i1] & l1) != 0L;
+        };
+    }
 
     /**
      * Set debug output.
@@ -116,13 +192,13 @@ private int jjMoveStringLiteralDfa2_1(long old0, long active0) {
             return 2;
         }
         switch (curChar) {
-            case 84:
-            case 116:
+            case 84, 116 -> {
                 if ((active0 & 0x200000000L) != 0L)
                     return jjStartNfaWithStates_1(2, 33, 12);
                 return jjMoveStringLiteralDfa3_1(active0, 0x8000000L);
-            default:
-                break;
+            }
+            default -> {
+            }
         }
         return jjStartNfa_1(1, active0);
     }
@@ -197,13 +273,6 @@ private int jjStartNfaWithStates_1(int pos, int kind, int state) {
         return jjMoveNfa_1(state, pos + 1);
     }
 
-    static final long[] jjbitVec0 = {
-            0xfffffffffffffffeL, 0xffffffffffffffffL, 0xffffffffffffffffL, 0xffffffffffffffffL
-    };
-    static final long[] jjbitVec2 = {
-            0x0L, 0x0L, 0xffffffffffffffffL, 0xffffffffffffffffL
-    };
-
     private int jjMoveNfa_1(int startState, int curPos) {
         int startsAt = 0;
         jjnewStateCnt = 61;
@@ -1135,75 +1204,6 @@ else if (curChar == 63)
         }
     }
 
-    static final int[] jjnextStates = {
-            14, 16, 17, 55, 60, 46, 48, 50, 38, 43, 25, 31, 27, 28, 29, 48,
-            49, 51, 30, 35, 36, 43, 44, 46, 39, 53, 73, 75, 6, 8, 9, 19,
-            21, 27, 0, 28, 30, 35, 39, 42, 47, 22, 24, 25, 43, 44, 46, 39,
-            48, 49, 51, 30, 76, 78, 79, 33, 34, 37, 38,
-    };
-
-    private static boolean jjCanMove_0(int hiByte, int i1, int i2, long l1, long l2) {
-        return switch (hiByte) {
-            case 0 -> ((jjbitVec2[i2] & l2) != 0L);
-            default -> (jjbitVec0[i1] & l1) != 0L;
-        };
-    }
-
-    /**
-     * Token literal values.
-     */
-    public static final String[] jjstrLiteralImages = {
-            "", null, null, null, null, "\50", "\51", null, null, null, null, null, null,
-            null, null, null, null, null, null, null, null, null, null, null, null, "\50",
-            "\51", null, null, null, null, null, null, null, null, null, null, null, null,};
-
-    /**
-     * Lexer state names.
-     */
-    public static final String[] lexStateNames = {
-            "DEFAULT",
-            "OPERATORSTATE",
-    };
-
-    /**
-     * Lex State array.
-     */
-    public static final int[] jjnewLexState = {
-            -1, -1, -1, -1, -1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-            -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-    };
-    static final long[] jjtoToken = {
-            0x7ffe1fffe1L,
-    };
-    static final long[] jjtoSkip = {
-            0x1e0001eL,
-    };
-    protected SimpleCharStream input_stream;
-    private final int[] jjrounds = new int[80];
-    private final int[] jjstateSet = new int[160];
-    private final StringBuffer jjimage = new StringBuffer();
-    private StringBuffer image = jjimage;
-    private int jjimageLen;
-    private int lengthOfMatch;
-    protected char curChar;
-
-    /**
-     * Constructor.
-     */
-    public ExtendedSLParserTokenManager(SimpleCharStream stream) {
-        if (SimpleCharStream.staticFlag)
-            throw new Error("ERROR: Cannot use a static CharStream class with a non-static lexical analyzer.");
-        input_stream = stream;
-    }
-
-    /**
-     * Constructor.
-     */
-    public ExtendedSLParserTokenManager(SimpleCharStream stream, int lexState) {
-        this(stream);
-        SwitchTo(lexState);
-    }
-
     /**
      * Reinitialise parser.
      */
@@ -1264,13 +1264,6 @@ protected Token jjFillToken() {
         return t;
     }
 
-    int curLexState = 0;
-    int defaultLexState = 0;
-    int jjnewStateCnt;
-    int jjround;
-    int jjmatchedPos;
-    int jjmatchedKind;
-
     /**
      * Get the next Token.
      */
diff --git a/src/jade/content/lang/sl/ParseException.java b/src/jade/content/lang/sl/ParseException.java
index 5ec76bf..50c2b39 100644
--- a/src/jade/content/lang/sl/ParseException.java
+++ b/src/jade/content/lang/sl/ParseException.java
@@ -12,6 +12,35 @@
  */
 public class ParseException extends Exception {
 
+    /**
+     * This is the last token that has been consumed successfully.  If
+     * this object has been created due to a parse error, the token
+     * followng this token will (therefore) be the first error token.
+     */
+    public Token currentToken;
+    /**
+     * Each entry in this array is an array of integers.  Each array
+     * of integers represents a sequence of tokens (by their ordinal
+     * values) that is expected at this point of the parse.
+     */
+    public int[][] expectedTokenSequences;
+    /**
+     * This is a reference to the "tokenImage" array of the generated
+     * parser within which the parse error occurred.  This array is
+     * defined in the generated ...Constants interface.
+     */
+    public String[] tokenImage;
+    /**
+     * This variable determines which constructor was used to create
+     * this object and thereby affects the semantics of the
+     * "getMessage" method (see below).
+     */
+    protected boolean specialConstructor;
+    /**
+     * The end of line string for this machine.
+     */
+    protected String eol = System.getProperty("line.separator", "\n");
+
     /**
      * This constructor is used by the method "generateParseException"
      * in the generated parser.  Calling this constructor generates
@@ -55,34 +84,6 @@ public ParseException(String message) {
         specialConstructor = false;
     }
 
-    /**
-     * This variable determines which constructor was used to create
-     * this object and thereby affects the semantics of the
-     * "getMessage" method (see below).
-     */
-    protected boolean specialConstructor;
-
-    /**
-     * This is the last token that has been consumed successfully.  If
-     * this object has been created due to a parse error, the token
-     * followng this token will (therefore) be the first error token.
-     */
-    public Token currentToken;
-
-    /**
-     * Each entry in this array is an array of integers.  Each array
-     * of integers represents a sequence of tokens (by their ordinal
-     * values) that is expected at this point of the parse.
-     */
-    public int[][] expectedTokenSequences;
-
-    /**
-     * This is a reference to the "tokenImage" array of the generated
-     * parser within which the parse error occurred.  This array is
-     * defined in the generated ...Constants interface.
-     */
-    public String[] tokenImage;
-
     /**
      * This method has the standard behavior when this object has been
      * created using the standard constructors.  Otherwise, it uses
@@ -133,11 +134,6 @@ public String getMessage() {
         return retval.toString();
     }
 
-    /**
-     * The end of line string for this machine.
-     */
-    protected String eol = System.getProperty("line.separator", "\n");
-
     /**
      * Used to convert raw characters to their escaped version
      * when these raw version cannot be used as part of an ASCII
diff --git a/src/jade/content/lang/sl/SL0Ontology.java b/src/jade/content/lang/sl/SL0Ontology.java
index 9672c9d..fd2b041 100644
--- a/src/jade/content/lang/sl/SL0Ontology.java
+++ b/src/jade/content/lang/sl/SL0Ontology.java
@@ -32,6 +32,7 @@
 /**
  * Ontology containing schemas for the SL0 language operators.
  * see jade.content.Ontology
+ *
  * @author Giovanni Caire - TILAB
  */
 class SL0Ontology extends Ontology implements SL0Vocabulary {
@@ -41,10 +42,6 @@ class SL0Ontology extends Ontology implements SL0Vocabulary {
     // The singleton instance of this ontology
     private static final Ontology theInstance = new SL0Ontology(ONTOLOGY_NAME, BasicOntology.getInstance(), null);
 
-    public static Ontology getInstance() {
-        return theInstance;
-    }
-
     /**
      * Constructor
      */
@@ -52,6 +49,10 @@ protected SL0Ontology(String name, Ontology base, Introspector intro) {
         super(name, base, intro);
     }
 
+    public static Ontology getInstance() {
+        return theInstance;
+    }
+
     boolean isUnaryLogicalOp(String symbol) {
         // There are no logical operators in SL0
         return false;
diff --git a/src/jade/content/lang/sl/SL0Vocabulary.java b/src/jade/content/lang/sl/SL0Vocabulary.java
index b648ce8..ee672fb 100644
--- a/src/jade/content/lang/sl/SL0Vocabulary.java
+++ b/src/jade/content/lang/sl/SL0Vocabulary.java
@@ -26,6 +26,7 @@
 
 /**
  * The vocabulary of the simbols used in the FIPA SL0 language
+ *
  * @author Giovanni Caire - TILAB
  */
 public interface SL0Vocabulary {
@@ -69,7 +70,9 @@ public interface SL0Vocabulary {
     String RESULT = "result";
     String RESULT_ACTION = "action";
     String RESULT_VALUE = "value";
-    /** @deprecated Use RESULT_VALUE instead */
+    /**
+     * @deprecated Use RESULT_VALUE instead
+     */
     String RESULT_ITEMS = RESULT_VALUE;
 
     String ACTION = "action";
diff --git a/src/jade/content/lang/sl/SL1Ontology.java b/src/jade/content/lang/sl/SL1Ontology.java
index f208536..6ddfbb6 100644
--- a/src/jade/content/lang/sl/SL1Ontology.java
+++ b/src/jade/content/lang/sl/SL1Ontology.java
@@ -35,6 +35,7 @@
 /**
  * Ontology containing schemas for the SL1 language operators.
  * see jade.content.Ontology
+ *
  * @author Giovanni Caire - TILAB
  */
 class SL1Ontology extends SL0Ontology implements SL1Vocabulary {
@@ -45,10 +46,6 @@ class SL1Ontology extends SL0Ontology implements SL1Vocabulary {
     // Note that the SL0Ontology does not add any schema to the BasicOntology
     private static final Ontology theInstance = new SL1Ontology(ONTOLOGY_NAME, BasicOntology.getInstance(), null);
 
-    public static Ontology getInstance() {
-        return theInstance;
-    }
-
     /**
      * Constructor
      */
@@ -76,6 +73,10 @@ protected SL1Ontology(String name, Ontology base, Introspector intro) {
 
     }
 
+    public static Ontology getInstance() {
+        return theInstance;
+    }
+
     boolean isUnaryLogicalOp(String symbol) {
         return (CaseInsensitiveString.equalsIgnoreCase(NOT, symbol));
     }
diff --git a/src/jade/content/lang/sl/SL1Vocabulary.java b/src/jade/content/lang/sl/SL1Vocabulary.java
index 28b9c5e..69da0e0 100644
--- a/src/jade/content/lang/sl/SL1Vocabulary.java
+++ b/src/jade/content/lang/sl/SL1Vocabulary.java
@@ -26,6 +26,7 @@
 
 /**
  * The vocabulary of the simbols used in the FIPA SL1 language
+ *
  * @author Giovanni Caire - TILAB
  */
 public interface SL1Vocabulary extends SL0Vocabulary {
diff --git a/src/jade/content/lang/sl/SL2Ontology.java b/src/jade/content/lang/sl/SL2Ontology.java
index 94f34db..d6b6ee8 100644
--- a/src/jade/content/lang/sl/SL2Ontology.java
+++ b/src/jade/content/lang/sl/SL2Ontology.java
@@ -35,6 +35,7 @@
 /**
  * Ontology containing schemas for the SL2 language operators.
  * see jade.content.Ontology
+ *
  * @author Giovanni Caire - TILAB
  */
 class SL2Ontology extends SL1Ontology implements SL2Vocabulary {
@@ -44,10 +45,6 @@ class SL2Ontology extends SL1Ontology implements SL2Vocabulary {
     // The singleton instance of this ontology
     private static final Ontology theInstance = new SL2Ontology(ONTOLOGY_NAME, SL1Ontology.getInstance(), null);
 
-    public static Ontology getInstance() {
-        return theInstance;
-    }
-
     /**
      * Constructor
      */
@@ -121,6 +118,10 @@ protected SL2Ontology(String name, Ontology base, Introspector intro) {
         }
     }
 
+    public static Ontology getInstance() {
+        return theInstance;
+    }
+
     boolean isQuantifier(String symbol) {
         return (CaseInsensitiveString.equalsIgnoreCase(EXISTS, symbol) ||
                 CaseInsensitiveString.equalsIgnoreCase(FORALL, symbol));
diff --git a/src/jade/content/lang/sl/SL2Vocabulary.java b/src/jade/content/lang/sl/SL2Vocabulary.java
index 86db3cc..9f17ab9 100644
--- a/src/jade/content/lang/sl/SL2Vocabulary.java
+++ b/src/jade/content/lang/sl/SL2Vocabulary.java
@@ -26,6 +26,7 @@
 
 /**
  * The vocabulary of the simbols used in the FIPA SL2 language
+ *
  * @author Giovanni Caire - TILAB
  */
 public interface SL2Vocabulary extends SL1Vocabulary {
diff --git a/src/jade/content/lang/sl/SLCodec.java b/src/jade/content/lang/sl/SLCodec.java
index 0bdba93..ee6e770 100644
--- a/src/jade/content/lang/sl/SLCodec.java
+++ b/src/jade/content/lang/sl/SLCodec.java
@@ -50,7 +50,8 @@
  * grammar.
  * By default the class implements full SL grammar, otherwise the proper
  * value must be used in the constructor.
- * @author Fabio Bellifemine - TILAB 
+ *
+ * @author Fabio Bellifemine - TILAB
  * @author Nicolas Lhuillier - Motorola (added support for byte[] primitive)
  * @version $Date: 2010-07-05 17:38:19 +0200(lun, 05 lug 2010) $ $Revision: 6354 $
  */
@@ -61,16 +62,18 @@ public class SLCodec extends SimpleSLCodec {
 public class SLCodec extends StringCodec {
 
     public static final String PRESERVE_JAVA_TYPES = "SL-preserve-java-types";
-
+    private final SL0Ontology slOnto; // ontology of the content language
+    /**
+     * This variable is true, when meta symbols are allowed (metas are a semantics-specific extension to the SL Grammar)
+     **/
+    private final boolean metaAllowed = true; //FIXME set/unset this variable to do
     private transient SLParser parser;
     private transient ExtendedSLParser extendedParser;
-    private final SL0Ontology slOnto; // ontology of the content language
     private Ontology domainOnto = null; // application ontology
-    /** This is the StringBuffer used by the encode method **/
+    /**
+     * This is the StringBuffer used by the encode method
+     **/
     private transient StringBuffer buffer = null;
-    /** This variable is true, when meta symbols are allowed (metas are a semantics-specific extension to the SL Grammar) **/
-    private final boolean metaAllowed = true; //FIXME set/unset this variable to do
-
     private boolean preserveJavaTypes = false;
 
     /**
@@ -85,6 +88,7 @@ public SLCodec() {
      * (long, int, float, double) must be preserved.
      * This is achieved by encoding long values as L and float values as  1 ? args[1].charAt(0) : 'C');
+        } catch (Exception e) {
+            System.out.println("usage: SLCodec SLLevel [ContentType]\n where SLLevel can be 0 for SL0, 1 for SL1, 2 for SL2, 3 or more for full SL \n and where ContentType is a char representing the type of content to be parsed: C for a contentexpression (default), T for a term, F for a formula");
+            System.exit(0);
+        }
+
+        while (true) {
+            try {
+                System.out.println("insert an SL " + (contentType == 'F' ? "Well-Formed Formula" : (contentType == 'T' ? "Term" : "Content Expression")) + " to parse (all the expression on a single line!): ");
+                BufferedReader buff = new BufferedReader(new InputStreamReader(System.in));
+                String str = buff.readLine();
+                System.out.println("\n\n");
+                if (contentType == 'F') {
+                    AbsPredicate result = codec.decodeFormula(null, str);
+                    System.out.println("DUMP OF THE DECODE OUTPUT (just for debugging):");
+                    System.out.println(result);
+                    System.out.println("\n\n");
+                    System.out.println("AFTER ENCODE:");
+                    System.out.println(codec.encodeFormula(null, result));
+                    System.out.println("\n\n");
+                } else if (contentType == 'T') {
+                    AbsTerm result = codec.decodeTerm(null, str);
+                    System.out.println("DUMP OF THE DECODE OUTPUT (just for debugging):");
+                    System.out.println(result);
+                    System.out.println("\n\n");
+                    System.out.println("AFTER ENCODE:");
+                    System.out.println(codec.encodeTerm(null, result));
+                    System.out.println("\n\n");
+                } else {
+                    AbsContentElement result = codec.decode(str);
+                    System.out.println("DUMP OF THE DECODE OUTPUT (just for debugging):");
+                    System.out.println(result);
+                    System.out.println("\n\n");
+                    System.out.println("AFTER ENCODE:");
+                    System.out.println(codec.encode(result));
+                    System.out.println("\n\n");
+                }
+            } catch (Exception pe) {
+                pe.printStackTrace();
+                //System.exit(0);
+            }
+        }
+    }
+
     private void initParser() {
         int slType = FIPANames.ContentLanguage.FIPA_SL0.equals(getName()) ? 0
                 : FIPANames.ContentLanguage.FIPA_SL2.equals(getName()) ? 1
@@ -144,6 +199,7 @@ public boolean getPreserveJavaTypes() {
 
     /**
      * Encodes a content into a String.
+     *
      * @param content the content as an abstract descriptor.
      * @return the content as a String.
      * @throws CodecException
@@ -154,8 +210,9 @@ public String encode(AbsContentElement content) throws CodecException {
 
     /**
      * Encodes a content into a String.
+     *
      * @param ontology the ontology
-     * @param content the content as an abstract descriptor.
+     * @param content  the content as an abstract descriptor.
      * @return the content as a String.
      * @throws CodecException
      */
@@ -177,7 +234,6 @@ public synchronized String encode(Ontology ontology, AbsContentElement content)
         }
     }
 
-
     /**
      * Encode a string, taking care of quoting separated words and
      * escaping strings, if necessary.
@@ -189,8 +245,9 @@ private void encodeAndAppend(String val) {
         buffer.append(out);
     }
 
-
-    /** Encode the passed Abstract Predicate and append its encoding to buffer **/
+    /**
+     * Encode the passed Abstract Predicate and append its encoding to buffer
+     **/
     private void encodeAndAppend(AbsPredicate val) throws CodecException {
         String propositionSymbol = val.getTypeName();
         if (val.getCount() > 0) { // predicate with arguments
@@ -332,7 +389,6 @@ private void encodeAndAppend(AbsConcept val) throws CodecException {
         buffer.append(')');
     }
 
-
     private void encodeAndAppend(AbsAggregate val) throws CodecException {
         buffer.append('(');
         encodeAndAppend(val.getTypeName());
@@ -343,7 +399,6 @@ private void encodeAndAppend(AbsAggregate val) throws CodecException {
         buffer.append(')');
     }
 
-
     private void encodeAndAppend(AbsPrimitive val) throws CodecException {
         Object v = val.getObject();
         if (v instanceof Date)
@@ -391,9 +446,9 @@ private void encodeAndAppend(AbsObject val) throws CodecException {
         else throw new CodecException("SLCodec cannot encode this object " + val);
     }
 
-
     /**
      * Decodes the content to an abstract description.
+     *
      * @param content the content as a String.
      * @return the content as an abstract description.
      * @throws CodecException
@@ -404,8 +459,9 @@ public AbsContentElement decode(String content) throws CodecException {
 
     /**
      * Decodes the content to an abstract description.
+     *
      * @param ontology the ontology.
-     * @param content the content as a String.
+     * @param content  the content as a String.
      * @return the content as an abstract description.
      * @throws CodecException
      */
@@ -428,11 +484,11 @@ public synchronized AbsContentElement decode(Ontology ontology, String content)
         }
     }
 
-
     /**
      * Decodes the content to an abstract description, where the content is known to be a Term.
+     *
      * @param ontology the ontology.
-     * @param term the term as a String.
+     * @param term     the term as a String.
      * @return the content as an abstract description.
      * @throws CodecException
      * @since JADE 3.4
@@ -451,11 +507,11 @@ public synchronized AbsTerm decodeTerm(Ontology ontology, String term) throws Co
         }
     }
 
-
     /**
      * Encodes the content into a String, where the content is known to be a Term.
+     *
      * @param ontology the ontology.
-     * @param term the termt as an abstract descriptor
+     * @param term     the termt as an abstract descriptor
      * @return the content as a String
      * @throws CodecException
      * @since JADE 3.4
@@ -471,11 +527,11 @@ public synchronized String encodeTerm(Ontology ontology, AbsTerm term) throws Co
         }
     }
 
-
     /**
      * Decodes the content to an abstract description, where the content is known to be a Well-formed Formula
+     *
      * @param ontology the ontology.
-     * @param formula the content as a String.
+     * @param formula  the content as a String.
      * @return the content as an abstract description.
      * @throws CodecException
      * @since JADE 3.4
@@ -494,11 +550,11 @@ public synchronized AbsPredicate decodeFormula(Ontology ontology, String formula
         }
     }
 
-
     /**
      * Encodes the content into a String, where the content is known to be a Well-formed Formula
+     *
      * @param ontology the ontology.
-     * @param formula the formula as an abstract descriptor
+     * @param formula  the formula as an abstract descriptor
      * @return the content as a String
      * @throws CodecException
      * @since JADE 3.4
@@ -514,56 +570,6 @@ public synchronized String encodeFormula(Ontology ontology, AbsPredicate formula
         }
     }
 
-
-    public static void main(String[] args) {
-        SLCodec codec = null;
-        char contentType = 'C';
-        try {
-            codec = new SLCodec(Integer.parseInt(args[0]));
-            contentType = (args.length > 1 ? args[1].charAt(0) : 'C');
-        } catch (Exception e) {
-            System.out.println("usage: SLCodec SLLevel [ContentType]\n where SLLevel can be 0 for SL0, 1 for SL1, 2 for SL2, 3 or more for full SL \n and where ContentType is a char representing the type of content to be parsed: C for a contentexpression (default), T for a term, F for a formula");
-            System.exit(0);
-        }
-
-        while (true) {
-            try {
-                System.out.println("insert an SL " + (contentType == 'F' ? "Well-Formed Formula" : (contentType == 'T' ? "Term" : "Content Expression")) + " to parse (all the expression on a single line!): ");
-                BufferedReader buff = new BufferedReader(new InputStreamReader(System.in));
-                String str = buff.readLine();
-                System.out.println("\n\n");
-                if (contentType == 'F') {
-                    AbsPredicate result = codec.decodeFormula(null, str);
-                    System.out.println("DUMP OF THE DECODE OUTPUT (just for debugging):");
-                    System.out.println(result);
-                    System.out.println("\n\n");
-                    System.out.println("AFTER ENCODE:");
-                    System.out.println(codec.encodeFormula(null, result));
-                    System.out.println("\n\n");
-                } else if (contentType == 'T') {
-                    AbsTerm result = codec.decodeTerm(null, str);
-                    System.out.println("DUMP OF THE DECODE OUTPUT (just for debugging):");
-                    System.out.println(result);
-                    System.out.println("\n\n");
-                    System.out.println("AFTER ENCODE:");
-                    System.out.println(codec.encodeTerm(null, result));
-                    System.out.println("\n\n");
-                } else {
-                    AbsContentElement result = codec.decode(str);
-                    System.out.println("DUMP OF THE DECODE OUTPUT (just for debugging):");
-                    System.out.println(result);
-                    System.out.println("\n\n");
-                    System.out.println("AFTER ENCODE:");
-                    System.out.println(codec.encode(result));
-                    System.out.println("\n\n");
-                }
-            } catch (Exception pe) {
-                pe.printStackTrace();
-                //System.exit(0);
-            }
-        }
-    }
-
     /**
      * @return the ontology containing the schemas of the operator
      * defined in this language
diff --git a/src/jade/content/lang/sl/SLOntology.java b/src/jade/content/lang/sl/SLOntology.java
index 3843c9f..b9b893b 100644
--- a/src/jade/content/lang/sl/SLOntology.java
+++ b/src/jade/content/lang/sl/SLOntology.java
@@ -29,6 +29,7 @@
 /**
  * Ontology containing schemas for the full SL language operators.
  * see jade.content.Ontology
+ *
  * @author Giovanni Caire - TILAB
  */
 public class SLOntology
@@ -46,10 +47,6 @@ public class SLOntology
     // The singleton instance of this ontology
     private static final Ontology theInstance = new SLOntology();
 
-    public static Ontology getInstance() {
-        return theInstance;
-    }
-
     /**
      * Constructor
      */
@@ -60,25 +57,25 @@ protected SLOntology() {
 
 		/*#MIDP_INCLUDE_BEGIN
   	super(ONTOLOGY_NAME, BasicOntology.getInstance(), null);
-  	
+
   	try {
 			// Schemas for the SL1 operators
   		add(new PredicateSchema(AND), AbsPredicate.getJavaClass());
   		add(new PredicateSchema(OR), AbsPredicate.getJavaClass());
 	  	add(new PredicateSchema(NOT), AbsPredicate.getJavaClass());
-  	
+
   		PredicateSchema ps = (PredicateSchema) getSchema(AND);
   		ps.add(AND_LEFT, (PredicateSchema) PredicateSchema.getBaseSchema());
 	  	ps.add(AND_RIGHT, (PredicateSchema) PredicateSchema.getBaseSchema());
-  	
+
   		ps = (PredicateSchema) getSchema(OR);
   		ps.add(OR_LEFT, (PredicateSchema) PredicateSchema.getBaseSchema());
 	  	ps.add(OR_RIGHT, (PredicateSchema) PredicateSchema.getBaseSchema());
-  		
+
   		ps = (PredicateSchema) getSchema(NOT);
 	  	ps.add(NOT_WHAT, (PredicateSchema) PredicateSchema.getBaseSchema());
-	  
-	  
+
+
 			// Schemas for the SL2 operators
     	add(VariableSchema.getBaseSchema());
   		add(new IRESchema(IOTA));
@@ -93,49 +90,53 @@ protected SLOntology() {
 	  	add(new PredicateSchema(FEASIBLE), AbsPredicate.getJavaClass());
 	  	add(new AgentActionSchema(ACTION_SEQUENCE), AbsAgentAction.getJavaClass());
 	  	add(new AgentActionSchema(ACTION_ALTERNATIVE), AbsAgentAction.getJavaClass());
-  	
+
   		ps = (PredicateSchema) getSchema(EXISTS);
   		ps.add(EXISTS_WHAT, (VariableSchema) VariableSchema.getBaseSchema());
 	  	ps.add(EXISTS_CONDITION, (PredicateSchema) PredicateSchema.getBaseSchema());
-  	
+
   		ps = (PredicateSchema) getSchema(FORALL);
   		ps.add(FORALL_WHAT, (VariableSchema) VariableSchema.getBaseSchema());
 	  	ps.add(FORALL_CONDITION, (PredicateSchema) PredicateSchema.getBaseSchema());
-  	
+
   		ps = (PredicateSchema) getSchema(BELIEF);
   		ps.add(BELIEF_AGENT, (ConceptSchema) getSchema(AID));
 	  	ps.add(BELIEF_CONDITION, (PredicateSchema) PredicateSchema.getBaseSchema());
-  	
+
   		ps = (PredicateSchema) getSchema(UNCERTAINTY);
   		ps.add(UNCERTAINTY_AGENT, (ConceptSchema) getSchema(AID));
 	  	ps.add(UNCERTAINTY_CONDITION, (PredicateSchema) PredicateSchema.getBaseSchema());
-  
+
   		ps = (PredicateSchema) getSchema(PERSISTENT_GOAL);
   		ps.add(PERSISTENT_GOAL_AGENT, (ConceptSchema) getSchema(AID));
 	  	ps.add(PERSISTENT_GOAL_CONDITION, (PredicateSchema) PredicateSchema.getBaseSchema());
-  	
+
   		ps = (PredicateSchema) getSchema(INTENTION);
   		ps.add(INTENTION_AGENT, (ConceptSchema) getSchema(AID));
 	  	ps.add(INTENTION_CONDITION, (PredicateSchema) PredicateSchema.getBaseSchema());
-  	
+
   		ps = (PredicateSchema) getSchema(FEASIBLE);
   		ps.add(FEASIBLE_ACTION, (VariableSchema) VariableSchema.getBaseSchema());
 	  	ps.add(FEASIBLE_CONDITION, (PredicateSchema) PredicateSchema.getBaseSchema(), ObjectSchema.OPTIONAL);
-  	
+
   		AgentActionSchema as = (AgentActionSchema) getSchema(ACTION_SEQUENCE);
   		as.add(ACTION_SEQUENCE_FIRST, (AgentActionSchema) AgentActionSchema.getBaseSchema());
   		as.add(ACTION_SEQUENCE_SECOND, (AgentActionSchema) AgentActionSchema.getBaseSchema());
   		as.setEncodingByOrder(true);
-  	
+
   		as = (AgentActionSchema) getSchema(ACTION_ALTERNATIVE);
   		as.add(ACTION_ALTERNATIVE_FIRST, (AgentActionSchema) AgentActionSchema.getBaseSchema());
   		as.add(ACTION_ALTERNATIVE_SECOND, (AgentActionSchema) AgentActionSchema.getBaseSchema());
   		as.setEncodingByOrder(true);
-    } 
+    }
     catch (OntologyException oe) {
       oe.printStackTrace();
-    } 
+    }
 		#MIDP_INCLUDE_END*/
     }
 
+    public static Ontology getInstance() {
+        return theInstance;
+    }
+
 }
diff --git a/src/jade/content/lang/sl/SLParser.java b/src/jade/content/lang/sl/SLParser.java
index ff64e4d..8d1f7fe 100644
--- a/src/jade/content/lang/sl/SLParser.java
+++ b/src/jade/content/lang/sl/SLParser.java
@@ -25,10 +25,136 @@
 class SLParser implements SLParserConstants {
 
     private static final String META_EXCEPTION_MESSAGE = "Meta SL expressions are not allowed";
+    static private int[] jj_la1_0;
+    static private int[] jj_la1_1;
+
+    static {
+        jj_la1_init_0();
+        jj_la1_init_1();
+    }
+
     /**
      * This variable is true, when meta symbols are allowed (metas are a semantics-specific extension to the SL Grammar)
      **/
     private final boolean metaAllowed = true; //FIXME to do set/unset this variable
+    final private int[] jj_la1 = new int[23];
+    private final List jj_expentries = new ArrayList<>();
+    /**
+     * Generated Token Manager.
+     */
+    public SLParserTokenManager token_source;
+    /**
+     * Current token.
+     */
+    public Token token;
+    /**
+     * Next token.
+     */
+    public Token jj_nt;
+
+    /*   P R O D U C T I O N    R U L E S  */
+    Ontology curOntology = null;
+    /**
+     * (0 for FIPa-SL0, 1 for SL1, 2 for SL2, >2 for full SL)
+     **/
+    int slType = 3;
+
+    // lbrace2 in the OperatorState of the Token Manager
+    SimpleCharStream jj_input_stream;
+    private int jj_ntk;
+    private int jj_gen;
+    private int[] jj_expentry;
+    private int jj_kind = -1;
+
+    /**
+     * Constructor with InputStream.
+     */
+    public SLParser(java.io.InputStream stream) {
+        this(stream, null);
+    }
+
+    /**
+     * Constructor with InputStream and supplied encoding
+     */
+    public SLParser(java.io.InputStream stream, String encoding) {
+        try {
+            jj_input_stream = new SimpleCharStream(stream, encoding, 1, 1);
+        } catch (UnsupportedEncodingException e) {
+            throw new RuntimeException(e.getMessage(), e);
+        }
+        token_source = new SLParserTokenManager(jj_input_stream);
+        token = new Token();
+        jj_ntk = -1;
+        jj_gen = 0;
+        for (int i = 0; i < 23; i++) jj_la1[i] = -1;
+    }
+
+    /**
+     * Constructor.
+     */
+    public SLParser(java.io.Reader stream) {
+        jj_input_stream = new SimpleCharStream(stream, 1, 1);
+        token_source = new SLParserTokenManager(jj_input_stream);
+        token = new Token();
+        jj_ntk = -1;
+        jj_gen = 0;
+        for (int i = 0; i < 23; i++) jj_la1[i] = -1;
+    }
+
+    /**
+     * Constructor with generated Token Manager.
+     */
+    public SLParser(SLParserTokenManager tm) {
+        token_source = tm;
+        token = new Token();
+        jj_ntk = -1;
+        jj_gen = 0;
+        for (int i = 0; i < 23; i++) jj_la1[i] = -1;
+    }
+
+    public static void main(String[] args) {
+
+        SLParser theParser = null;
+        try {
+            theParser = new SLParser(System.in);
+            theParser.setSLType(Integer.parseInt(args[0]));
+        } catch (Exception e) {
+            System.out.println("usage: SLParser SLLevel\u005cn  where SLLevel can be 0 for SL0, 1 for SL1, 2 for SL2, 3 or more for full SL");
+            System.exit(0);
+        }
+        if (theParser.slType < 3)
+            System.out.println("SL-" + theParser.slType + " Parser Started ...");
+        else
+            System.out.println("Full-SL" + " Parser Started ...");
+
+        SLCodec codec = new SLCodec();
+        //Ontology o = new DefaultOntology();
+
+        while (true) {
+            System.out.println("insert an SL expression to parse: ");
+            try {
+                AbsContentElementList result = theParser.Content();
+                String resultEncoded = codec.encode(result);
+                System.out.println("\u005cn\u005cn RESULT of SLParser.Content()=\u005cn" + resultEncoded);
+                AbsContentElement result2 = codec.decode(resultEncoded);
+                System.out.println("\u005cn\u005cn RESULT of SLCodec.decode(SLCodec.encode(SLParser.Content()))=\u005cn" + codec.encode(result2));
+                System.out.println("\u005cn\u005cn");
+                //result.dump();
+                //System.out.println("AFTER ENCODING: "+codec.encode(result,o));
+            } catch (Exception pe) {
+                pe.printStackTrace();
+                System.exit(0);
+            }
+        }
+    }
+
+    private static void jj_la1_init_0() {
+        jj_la1_0 = new int[]{0x843020, 0x800020, 0x1000040, 0x843020, 0xee003000, 0x56003000, 0x873fa0, 0x33f00, 0x87ffa0, 0x10003000, 0x873fa0, 0xc000, 0x87ffa0, 0xc000, 0x42000000, 0x840020, 0x843020, 0x843020, 0x873fa0, 0xa8003000, 0xf00, 0x3000, 0x40000,};
+    }
+
+    private static void jj_la1_init_1() {
+        jj_la1_1 = new int[]{0x1c, 0x0, 0x0, 0x1c, 0xf, 0xc, 0x1c, 0xc, 0x1c, 0xc, 0x1c, 0x0, 0x1c, 0x0, 0x0, 0x10, 0x1c, 0x1c, 0x1c, 0xf, 0x0, 0xc, 0x10,};
+    }
 
     /* Take a quoted FIPA SL0 String and convert to a
      * normal Java-style String.  Remove the
@@ -48,7 +174,6 @@ private String unescape(String s) {
         return result.toString();
     }
 
-
     /**
      * When an ActionExpression is parsed, if it is an AbsConcept then
      * it must be casted upto an AbsAgentAction.
@@ -75,9 +200,6 @@ void setSLType(int slType) {
         this.slType = slType;
     }
 
-
-    Ontology curOntology = null;
-
     /**
      * Reinitialize the parser such as it is ready to parse a new expression.
      *
@@ -106,49 +228,6 @@ AbsContentElement parse(Ontology o, String content) throws ParseException, Token
             return tuple.get(0);
     }
 
-    /**
-     * (0 for FIPa-SL0, 1 for SL1, 2 for SL2, >2 for full SL)
-     **/
-    int slType = 3;
-
-    public static void main(String[] args) {
-
-        SLParser theParser = null;
-        try {
-            theParser = new SLParser(System.in);
-            theParser.setSLType(Integer.parseInt(args[0]));
-        } catch (Exception e) {
-            System.out.println("usage: SLParser SLLevel\u005cn  where SLLevel can be 0 for SL0, 1 for SL1, 2 for SL2, 3 or more for full SL");
-            System.exit(0);
-        }
-        if (theParser.slType < 3)
-            System.out.println("SL-" + theParser.slType + " Parser Started ...");
-        else
-            System.out.println("Full-SL" + " Parser Started ...");
-
-        SLCodec codec = new SLCodec();
-        //Ontology o = new DefaultOntology();
-
-        while (true) {
-            System.out.println("insert an SL expression to parse: ");
-            try {
-                AbsContentElementList result = theParser.Content();
-                String resultEncoded = codec.encode(result);
-                System.out.println("\u005cn\u005cn RESULT of SLParser.Content()=\u005cn" + resultEncoded);
-                AbsContentElement result2 = codec.decode(resultEncoded);
-                System.out.println("\u005cn\u005cn RESULT of SLCodec.decode(SLCodec.encode(SLParser.Content()))=\u005cn" + codec.encode(result2));
-                System.out.println("\u005cn\u005cn");
-                //result.dump();
-                //System.out.println("AFTER ENCODING: "+codec.encode(result,o));
-            } catch (Exception pe) {
-                pe.printStackTrace();
-                System.exit(0);
-            }
-        }
-    }
-
-    /*   P R O D U C T I O N    R U L E S  */
-
     /**
      * This production rule represents the more general expression that can
      * serve as content for an ACL message. Since different communicative
@@ -201,8 +280,6 @@ final public void LBrace() throws ParseException {
         }
     }
 
-    // lbrace2 in the OperatorState of the Token Manager
-
     /**
      * Right Brace in all of the possible states of the Token Manager
      **/
@@ -924,61 +1001,6 @@ final public String MetaSymbol() throws ParseException {
         throw new Error("Missing return statement in function");
     }
 
-    /**
-     * Generated Token Manager.
-     */
-    public SLParserTokenManager token_source;
-    SimpleCharStream jj_input_stream;
-    /**
-     * Current token.
-     */
-    public Token token;
-    /**
-     * Next token.
-     */
-    public Token jj_nt;
-    private int jj_ntk;
-    private int jj_gen;
-    final private int[] jj_la1 = new int[23];
-    static private int[] jj_la1_0;
-    static private int[] jj_la1_1;
-
-    static {
-        jj_la1_init_0();
-        jj_la1_init_1();
-    }
-
-    private static void jj_la1_init_0() {
-        jj_la1_0 = new int[]{0x843020, 0x800020, 0x1000040, 0x843020, 0xee003000, 0x56003000, 0x873fa0, 0x33f00, 0x87ffa0, 0x10003000, 0x873fa0, 0xc000, 0x87ffa0, 0xc000, 0x42000000, 0x840020, 0x843020, 0x843020, 0x873fa0, 0xa8003000, 0xf00, 0x3000, 0x40000,};
-    }
-
-    private static void jj_la1_init_1() {
-        jj_la1_1 = new int[]{0x1c, 0x0, 0x0, 0x1c, 0xf, 0xc, 0x1c, 0xc, 0x1c, 0xc, 0x1c, 0x0, 0x1c, 0x0, 0x0, 0x10, 0x1c, 0x1c, 0x1c, 0xf, 0x0, 0xc, 0x10,};
-    }
-
-    /**
-     * Constructor with InputStream.
-     */
-    public SLParser(java.io.InputStream stream) {
-        this(stream, null);
-    }
-
-    /**
-     * Constructor with InputStream and supplied encoding
-     */
-    public SLParser(java.io.InputStream stream, String encoding) {
-        try {
-            jj_input_stream = new SimpleCharStream(stream, encoding, 1, 1);
-        } catch (UnsupportedEncodingException e) {
-            throw new RuntimeException(e.getMessage(), e);
-        }
-        token_source = new SLParserTokenManager(jj_input_stream);
-        token = new Token();
-        jj_ntk = -1;
-        jj_gen = 0;
-        for (int i = 0; i < 23; i++) jj_la1[i] = -1;
-    }
-
     /**
      * Reinitialise.
      */
@@ -1002,18 +1024,6 @@ public void ReInit(java.io.InputStream stream, String encoding) {
         for (int i = 0; i < 23; i++) jj_la1[i] = -1;
     }
 
-    /**
-     * Constructor.
-     */
-    public SLParser(java.io.Reader stream) {
-        jj_input_stream = new SimpleCharStream(stream, 1, 1);
-        token_source = new SLParserTokenManager(jj_input_stream);
-        token = new Token();
-        jj_ntk = -1;
-        jj_gen = 0;
-        for (int i = 0; i < 23; i++) jj_la1[i] = -1;
-    }
-
     /**
      * Reinitialise.
      */
@@ -1026,17 +1036,6 @@ public void ReInit(java.io.Reader stream) {
         for (int i = 0; i < 23; i++) jj_la1[i] = -1;
     }
 
-    /**
-     * Constructor with generated Token Manager.
-     */
-    public SLParser(SLParserTokenManager tm) {
-        token_source = tm;
-        token = new Token();
-        jj_ntk = -1;
-        jj_gen = 0;
-        for (int i = 0; i < 23; i++) jj_la1[i] = -1;
-    }
-
     /**
      * Reinitialise.
      */
@@ -1062,7 +1061,6 @@ private Token jj_consume_token(int kind) throws ParseException {
         throw generateParseException();
     }
 
-
     /**
      * Get the next Token.
      */
@@ -1093,10 +1091,6 @@ private int jj_ntk() {
             return (jj_ntk = jj_nt.kind);
     }
 
-    private final List jj_expentries = new ArrayList<>();
-    private int[] jj_expentry;
-    private int jj_kind = -1;
-
     /**
      * Generate ParseException.
      */
diff --git a/src/jade/content/lang/sl/SLParserTokenManager.java b/src/jade/content/lang/sl/SLParserTokenManager.java
index dc11b39..0619d56 100644
--- a/src/jade/content/lang/sl/SLParserTokenManager.java
+++ b/src/jade/content/lang/sl/SLParserTokenManager.java
@@ -8,10 +8,85 @@
  */
 public class SLParserTokenManager implements SLParserConstants {
 
+    /**
+     * Token literal values.
+     */
+    public static final String[] jjstrLiteralImages = {
+            "", null, null, null, null, "\50", "\51", null, null, null, null, null, null,
+            null, null, null, null, null, null, null, null, null, null, "\50", "\51", null, null,
+            null, null, null, null, null, null, null, null, null, null,};
+    /**
+     * Lexer state names.
+     */
+    public static final String[] lexStateNames = {
+            "DEFAULT",
+            "OPERATORSTATE",
+    };
+    /**
+     * Lex State array.
+     */
+    public static final int[] jjnewLexState = {
+            -1, -1, -1, -1, -1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0,
+            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    };
+    static final long[] jjbitVec0 = {
+            0xfffffffffffffffeL, 0xffffffffffffffffL, 0xffffffffffffffffL, 0xffffffffffffffffL
+    };
+    static final long[] jjbitVec2 = {
+            0x0L, 0x0L, 0xffffffffffffffffL, 0xffffffffffffffffL
+    };
+    static final int[] jjnextStates = {
+            14, 16, 17, 55, 60, 46, 48, 50, 38, 43, 25, 31, 32, 38, 39, 41,
+            3, 33, 34, 43, 62, 64, 11, 13, 14, 24, 26, 32, 0, 3, 33, 37,
+            27, 29, 30, 38, 39, 41, 3, 65, 67, 68, 6, 7, 35, 36,
+    };
+    static final long[] jjtoToken = {
+            0x1fff87ffe1L,
+    };
+    static final long[] jjtoSkip = {
+            0x78001eL,
+    };
+    private final int[] jjrounds = new int[69];
+    private final int[] jjstateSet = new int[138];
+    private final StringBuffer jjimage = new StringBuffer();
     /**
      * Debug output.
      */
     public java.io.PrintStream debugStream = System.out;
+    protected SimpleCharStream input_stream;
+    protected char curChar;
+    int curLexState = 0;
+    int defaultLexState = 0;
+    int jjnewStateCnt;
+    int jjround;
+    int jjmatchedPos;
+    int jjmatchedKind;
+    private StringBuffer image = jjimage;
+    private int jjimageLen;
+    private int lengthOfMatch;
+
+    /**
+     * Constructor.
+     */
+    public SLParserTokenManager(SimpleCharStream stream) {
+        if (SimpleCharStream.staticFlag)
+            throw new Error("ERROR: Cannot use a static CharStream class with a non-static lexical analyzer.");
+        input_stream = stream;
+    }
+    /**
+     * Constructor.
+     */
+    public SLParserTokenManager(SimpleCharStream stream, int lexState) {
+        this(stream);
+        SwitchTo(lexState);
+    }
+
+    private static boolean jjCanMove_0(int hiByte, int i1, int i2, long l1, long l2) {
+        if (hiByte == 0) {
+            return ((jjbitVec2[i2] & l2) != 0L);
+        }
+        return (jjbitVec0[i1] & l1) != 0L;
+    }
 
     /**
      * Set debug output.
@@ -117,13 +192,13 @@ private int jjMoveStringLiteralDfa2_1(long old0, long active0) {
             return 2;
         }
         switch (curChar) {
-            case 84:
-            case 116:
+            case 84, 116 -> {
                 if ((active0 & 0x80000000L) != 0L)
                     return jjStartNfaWithStates_1(2, 31, 12);
                 return jjMoveStringLiteralDfa3_1(active0, 0x2000000L);
-            default:
-                break;
+            }
+            default -> {
+            }
         }
         return jjStartNfa_1(1, active0);
     }
@@ -198,13 +273,6 @@ private int jjStartNfaWithStates_1(int pos, int kind, int state) {
         return jjMoveNfa_1(state, pos + 1);
     }
 
-    static final long[] jjbitVec0 = {
-            0xfffffffffffffffeL, 0xffffffffffffffffL, 0xffffffffffffffffL, 0xffffffffffffffffL
-    };
-    static final long[] jjbitVec2 = {
-            0x0L, 0x0L, 0xffffffffffffffffL, 0xffffffffffffffffL
-    };
-
     private int jjMoveNfa_1(int startState, int curPos) {
         int startsAt = 0;
         jjnewStateCnt = 61;
@@ -1092,74 +1160,6 @@ else if (curChar == 63)
         }
     }
 
-    static final int[] jjnextStates = {
-            14, 16, 17, 55, 60, 46, 48, 50, 38, 43, 25, 31, 32, 38, 39, 41,
-            3, 33, 34, 43, 62, 64, 11, 13, 14, 24, 26, 32, 0, 3, 33, 37,
-            27, 29, 30, 38, 39, 41, 3, 65, 67, 68, 6, 7, 35, 36,
-    };
-
-    private static boolean jjCanMove_0(int hiByte, int i1, int i2, long l1, long l2) {
-        if (hiByte == 0) {
-            return ((jjbitVec2[i2] & l2) != 0L);
-        }
-        return (jjbitVec0[i1] & l1) != 0L;
-    }
-
-    /**
-     * Token literal values.
-     */
-    public static final String[] jjstrLiteralImages = {
-            "", null, null, null, null, "\50", "\51", null, null, null, null, null, null,
-            null, null, null, null, null, null, null, null, null, null, "\50", "\51", null, null,
-            null, null, null, null, null, null, null, null, null, null,};
-
-    /**
-     * Lexer state names.
-     */
-    public static final String[] lexStateNames = {
-            "DEFAULT",
-            "OPERATORSTATE",
-    };
-
-    /**
-     * Lex State array.
-     */
-    public static final int[] jjnewLexState = {
-            -1, -1, -1, -1, -1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0,
-            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-    };
-    static final long[] jjtoToken = {
-            0x1fff87ffe1L,
-    };
-    static final long[] jjtoSkip = {
-            0x78001eL,
-    };
-    protected SimpleCharStream input_stream;
-    private final int[] jjrounds = new int[69];
-    private final int[] jjstateSet = new int[138];
-    private final StringBuffer jjimage = new StringBuffer();
-    private StringBuffer image = jjimage;
-    private int jjimageLen;
-    private int lengthOfMatch;
-    protected char curChar;
-
-    /**
-     * Constructor.
-     */
-    public SLParserTokenManager(SimpleCharStream stream) {
-        if (SimpleCharStream.staticFlag)
-            throw new Error("ERROR: Cannot use a static CharStream class with a non-static lexical analyzer.");
-        input_stream = stream;
-    }
-
-    /**
-     * Constructor.
-     */
-    public SLParserTokenManager(SimpleCharStream stream, int lexState) {
-        this(stream);
-        SwitchTo(lexState);
-    }
-
     /**
      * Reinitialise parser.
      */
@@ -1220,13 +1220,6 @@ protected Token jjFillToken() {
         return t;
     }
 
-    int curLexState = 0;
-    int defaultLexState = 0;
-    int jjnewStateCnt;
-    int jjround;
-    int jjmatchedPos;
-    int jjmatchedKind;
-
     /**
      * Get the next Token.
      */
diff --git a/src/jade/content/lang/sl/SLVocabulary.java b/src/jade/content/lang/sl/SLVocabulary.java
index 9b45cd3..aabae2c 100644
--- a/src/jade/content/lang/sl/SLVocabulary.java
+++ b/src/jade/content/lang/sl/SLVocabulary.java
@@ -26,6 +26,7 @@
 
 /**
  * The vocabulary of the simbols used in the FIPA SL language
+ *
  * @author Giovanni Caire - TILAB
  */
 public interface SLVocabulary
diff --git a/src/jade/content/lang/sl/SimpleCharStream.java b/src/jade/content/lang/sl/SimpleCharStream.java
index e5a2aa9..c6105ac 100644
--- a/src/jade/content/lang/sl/SimpleCharStream.java
+++ b/src/jade/content/lang/sl/SimpleCharStream.java
@@ -8,34 +8,79 @@
 
 public class SimpleCharStream {
     public static final boolean staticFlag = false;
-    int bufsize;
-    int available;
-    int tokenBegin;
     public int bufpos = -1;
     protected int[] bufline;
     protected int[] bufcolumn;
-
     protected int column = 0;
     protected int line = 1;
-
     protected boolean prevCharIsCR = false;
     protected boolean prevCharIsLF = false;
-
     protected java.io.Reader inputStream;
-
     protected char[] buffer;
     protected int maxNextCharInd = 0;
     protected int inBuf = 0;
     protected int tabSize = 8;
+    int bufsize;
+    int available;
+    int tokenBegin;
 
-    protected void setTabSize(int i) {
-        tabSize = i;
+    public SimpleCharStream(java.io.Reader dstream, int startline,
+                            int startcolumn, int buffersize) {
+        inputStream = dstream;
+        line = startline;
+        column = startcolumn - 1;
+
+        available = bufsize = buffersize;
+        buffer = new char[buffersize];
+        bufline = new int[buffersize];
+        bufcolumn = new int[buffersize];
+    }
+
+    public SimpleCharStream(java.io.Reader dstream, int startline,
+                            int startcolumn) {
+        this(dstream, startline, startcolumn, 4096);
+    }
+
+
+    public SimpleCharStream(java.io.Reader dstream) {
+        this(dstream, 1, 1, 4096);
+    }
+
+    public SimpleCharStream(java.io.InputStream dstream, String encoding, int startline,
+                            int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException {
+        this(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize);
+    }
+
+    public SimpleCharStream(java.io.InputStream dstream, int startline,
+                            int startcolumn, int buffersize) {
+        this(new java.io.InputStreamReader(dstream), startline, startcolumn, buffersize);
+    }
+
+    public SimpleCharStream(java.io.InputStream dstream, String encoding, int startline,
+                            int startcolumn) throws java.io.UnsupportedEncodingException {
+        this(dstream, encoding, startline, startcolumn, 4096);
+    }
+
+    public SimpleCharStream(java.io.InputStream dstream, int startline,
+                            int startcolumn) {
+        this(dstream, startline, startcolumn, 4096);
+    }
+
+    public SimpleCharStream(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException {
+        this(dstream, encoding, 1, 1, 4096);
+    }
+
+    public SimpleCharStream(java.io.InputStream dstream) {
+        this(dstream, 1, 1, 4096);
     }
 
     protected int getTabSize() {
         return tabSize;
     }
 
+    protected void setTabSize(int i) {
+        tabSize = i;
+    }
 
     protected void ExpandBuff(boolean wrapAround) {
         char[] newbuffer = new char[bufsize + 2048];
@@ -139,18 +184,14 @@ protected void UpdateLineColumn(char c) {
         }
 
         switch (c) {
-            case '\r':
-                prevCharIsCR = true;
-                break;
-            case '\n':
-                prevCharIsLF = true;
-                break;
-            case '\t':
+            case '\r' -> prevCharIsCR = true;
+            case '\n' -> prevCharIsLF = true;
+            case '\t' -> {
                 column--;
                 column += (tabSize - (column % tabSize));
-                break;
-            default:
-                break;
+            }
+            default -> {
+            }
         }
 
         bufline[bufpos] = line;
@@ -217,27 +258,6 @@ public void backup(int amount) {
             bufpos += bufsize;
     }
 
-    public SimpleCharStream(java.io.Reader dstream, int startline,
-                            int startcolumn, int buffersize) {
-        inputStream = dstream;
-        line = startline;
-        column = startcolumn - 1;
-
-        available = bufsize = buffersize;
-        buffer = new char[buffersize];
-        bufline = new int[buffersize];
-        bufcolumn = new int[buffersize];
-    }
-
-    public SimpleCharStream(java.io.Reader dstream, int startline,
-                            int startcolumn) {
-        this(dstream, startline, startcolumn, 4096);
-    }
-
-    public SimpleCharStream(java.io.Reader dstream) {
-        this(dstream, 1, 1, 4096);
-    }
-
     public void ReInit(java.io.Reader dstream, int startline,
                        int startcolumn, int buffersize) {
         inputStream = dstream;
@@ -264,34 +284,6 @@ public void ReInit(java.io.Reader dstream) {
         ReInit(dstream, 1, 1, 4096);
     }
 
-    public SimpleCharStream(java.io.InputStream dstream, String encoding, int startline,
-                            int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException {
-        this(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize);
-    }
-
-    public SimpleCharStream(java.io.InputStream dstream, int startline,
-                            int startcolumn, int buffersize) {
-        this(new java.io.InputStreamReader(dstream), startline, startcolumn, buffersize);
-    }
-
-    public SimpleCharStream(java.io.InputStream dstream, String encoding, int startline,
-                            int startcolumn) throws java.io.UnsupportedEncodingException {
-        this(dstream, encoding, startline, startcolumn, 4096);
-    }
-
-    public SimpleCharStream(java.io.InputStream dstream, int startline,
-                            int startcolumn) {
-        this(dstream, startline, startcolumn, 4096);
-    }
-
-    public SimpleCharStream(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException {
-        this(dstream, encoding, 1, 1, 4096);
-    }
-
-    public SimpleCharStream(java.io.InputStream dstream) {
-        this(dstream, 1, 1, 4096);
-    }
-
     public void ReInit(java.io.InputStream dstream, String encoding, int startline,
                        int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException {
         ReInit(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize);
diff --git a/src/jade/content/lang/sl/SimpleSLCodec.java b/src/jade/content/lang/sl/SimpleSLCodec.java
index 315ea84..f8e33bd 100644
--- a/src/jade/content/lang/sl/SimpleSLCodec.java
+++ b/src/jade/content/lang/sl/SimpleSLCodec.java
@@ -38,12 +38,12 @@
 
 /**
  * MIDP implementation of the SLCodec. Actually the MIDP version of the SLCodec just extends SimpleSLCodec
+ *
  * @version $Date: 2013-02-25 11:10:22 +0100 (lun, 25 feb 2013) $ $Revision: 6642 $
  **/
 public class SimpleSLCodec extends StringCodec {
-    private int indent = 0;
-
     private final Logger logger = Logger.getMyLogger(this.getClass().getName());
+    private int indent = 0;
 
     public SimpleSLCodec() {
         super(jade.domain.FIPANames.ContentLanguage.FIPA_SL);
@@ -51,8 +51,9 @@ public SimpleSLCodec() {
 
     /**
      * Encodes a content into a string using a given ontology.
+     *
      * @param ontology the ontology
-     * @param content the content as an abstract descriptor.
+     * @param content  the content as an abstract descriptor.
      * @return the content as a string.
      * @throws CodecException
      */
@@ -174,8 +175,9 @@ private void stringifyPrimitive(AbsPrimitive val, StringBuffer str) throws Codec
     /**
      * Decodes a content expression to an abstract description using a
      * given ontology.
+     *
      * @param ontology the ontology.
-     * @param content the content as a string.
+     * @param content  the content as a string.
      * @return the content as an abstract description.
      * @throws CodecException
      */
@@ -332,12 +334,14 @@ private AbsObject parseSimple(SimpleSLTokenizer p) throws CodecException {
     }
 
     /**
+     *
      */
     public AbsContentElement decode(String content) throws CodecException {
         throw new CodecException("Unsupported operation");
     }
 
     /**
+     *
      */
     public String encode(AbsContentElement content) throws CodecException {
         throw new CodecException("Unsupported operation");
diff --git a/src/jade/content/lang/sl/SimpleSLTokenizer.java b/src/jade/content/lang/sl/SimpleSLTokenizer.java
index 556a30e..d63f9ed 100644
--- a/src/jade/content/lang/sl/SimpleSLTokenizer.java
+++ b/src/jade/content/lang/sl/SimpleSLTokenizer.java
@@ -34,6 +34,7 @@
  */
 public class SimpleSLTokenizer {
     private static final String msg = "Parse error: unexpected end of content at #";
+    private static final String illegalFirstChar = "#0123456789:-?";
     private final String content;
     private int current = 0;
 
@@ -44,6 +45,51 @@ public SimpleSLTokenizer(String s) {
         content = s;
     }
 
+    /**
+     * Test if the given string is a legal SL word using the FIPA XC00008D spec.
+     * In addition to FIPA's restrictions, place the additional restriction
+     * that a Word can not contain a '\"', that would confuse the parser at
+     * the other end.
+     */
+    public final static boolean isAWord(String s) {
+        // This should permit strings of length 0 to be encoded.
+        if (s == null || s.length() == 0) {
+            return false; // words must have at least one character
+        }
+
+        if (illegalFirstChar.indexOf(s.charAt(0)) >= 0) {
+            return false;
+        }
+        for (int i = 0; i < s.length(); i++) {
+            char c = s.charAt(i);
+            if (c == '"' || c == '(' || c == ')' || c <= 0x20 || c >= 0x80) {
+                return false;
+            }
+        }
+        return true;
+    }
+
+    /**
+     * Take a java String and quote it to form a legal FIPA SL0 string.
+     * Add quotation marks to the beginning/end and escape any
+     * quotation marks inside the string.
+     */
+    public static String quoteString(String s) {
+        // Make the stringBuffer a little larger than strictly
+        // necessary in case we need to insert any additional
+        // characters.  (If our size estimate is wrong, the
+        // StringBuffer will automatically grow as needed).
+        StringBuilder result = new StringBuilder(s.length() + 20);
+        result.append("\"");
+        for (int i = 0; i < s.length(); i++)
+            if (s.charAt(i) == '"')
+                result.append("\\\"");
+            else
+                result.append(s.charAt(i));
+        result.append("\"");
+        return result.toString();
+    }
+
     /**
      * Return the next SL token (i.e. '(', ')' or a generic element)
      * without advancing the pointer
@@ -156,6 +202,8 @@ private String getWord(boolean removeColon) {
         }
         return content.substring(start, current);
     }
+    //FIXME We might improve performance if we merged isAWord and quoteString into a single method
+    // infact they both have to loop over the chars of the String.
 
     private void skipSpaces() {
         while (isSpace(content.charAt(current))) {
@@ -166,53 +214,4 @@ private void skipSpaces() {
     private boolean isSpace(char c) {
         return (c == ' ' || c == '\t' || c == '\n');
     }
-
-    private static final String illegalFirstChar = "#0123456789:-?";
-    //FIXME We might improve performance if we merged isAWord and quoteString into a single method
-    // infact they both have to loop over the chars of the String.
-
-    /**
-     * Test if the given string is a legal SL word using the FIPA XC00008D spec.
-     * In addition to FIPA's restrictions, place the additional restriction
-     * that a Word can not contain a '\"', that would confuse the parser at
-     * the other end.
-     */
-    public final static boolean isAWord(String s) {
-        // This should permit strings of length 0 to be encoded.
-        if (s == null || s.length() == 0) {
-            return false; // words must have at least one character
-        }
-
-        if (illegalFirstChar.indexOf(s.charAt(0)) >= 0) {
-            return false;
-        }
-        for (int i = 0; i < s.length(); i++) {
-            char c = s.charAt(i);
-            if (c == '"' || c == '(' || c == ')' || c <= 0x20 || c >= 0x80) {
-                return false;
-            }
-        }
-        return true;
-    }
-
-    /**
-     * Take a java String and quote it to form a legal FIPA SL0 string.
-     * Add quotation marks to the beginning/end and escape any
-     * quotation marks inside the string.
-     */
-    public static String quoteString(String s) {
-        // Make the stringBuffer a little larger than strictly
-        // necessary in case we need to insert any additional
-        // characters.  (If our size estimate is wrong, the
-        // StringBuffer will automatically grow as needed).
-        StringBuilder result = new StringBuilder(s.length() + 20);
-        result.append("\"");
-        for (int i = 0; i < s.length(); i++)
-            if (s.charAt(i) == '"')
-                result.append("\\\"");
-            else
-                result.append(s.charAt(i));
-        result.append("\"");
-        return result.toString();
-    }
 }
diff --git a/src/jade/content/lang/sl/Token.java b/src/jade/content/lang/sl/Token.java
index 69e54d9..831985d 100644
--- a/src/jade/content/lang/sl/Token.java
+++ b/src/jade/content/lang/sl/Token.java
@@ -50,13 +50,6 @@ public class Token {
      */
     public Token specialToken;
 
-    /**
-     * Returns the image.
-     */
-    public String toString() {
-        return image;
-    }
-
     /**
      * Returns a new Token object, by default. However, if you want, you
      * can create and return subclass objects based on the value of ofKind.
@@ -73,4 +66,11 @@ public static final Token newToken(int ofKind) {
         return new Token();
     }
 
+    /**
+     * Returns the image.
+     */
+    public String toString() {
+        return image;
+    }
+
 }
diff --git a/src/jade/content/lang/sl/TokenMgrError.java b/src/jade/content/lang/sl/TokenMgrError.java
index fa8fbcb..8e64240 100644
--- a/src/jade/content/lang/sl/TokenMgrError.java
+++ b/src/jade/content/lang/sl/TokenMgrError.java
@@ -32,6 +32,22 @@ public class TokenMgrError extends Error {
      */
     int errorCode;
 
+    public TokenMgrError() {
+    }
+
+    public TokenMgrError(String message, int reason) {
+        super(message);
+        errorCode = reason;
+    }
+
+    public TokenMgrError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar, int reason) {
+        this(LexicalError(EOFSeen, lexState, errorLine, errorColumn, errorAfter, curChar), reason);
+    }
+
+    /*
+     * Constructors of various flavors follow.
+     */
+
     /**
      * Replaces unprintable characters by their espaced (or unicode escaped)
      * equivalents in the given string
@@ -112,20 +128,4 @@ protected static String LexicalError(boolean EOFSeen, int lexState, int errorLin
     public String getMessage() {
         return super.getMessage();
     }
-
-    /*
-     * Constructors of various flavors follow.
-     */
-
-    public TokenMgrError() {
-    }
-
-    public TokenMgrError(String message, int reason) {
-        super(message);
-        errorCode = reason;
-    }
-
-    public TokenMgrError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar, int reason) {
-        this(LexicalError(EOFSeen, lexState, errorLine, errorColumn, errorAfter, curChar), reason);
-    }
 }
diff --git a/src/jade/content/onto/BasicOntology.java b/src/jade/content/onto/BasicOntology.java
index f973651..125701d 100644
--- a/src/jade/content/onto/BasicOntology.java
+++ b/src/jade/content/onto/BasicOntology.java
@@ -42,23 +42,17 @@
 
 
 /**
- * This class implements an ontology containing schemas for 
- * Primitive types and SL0 operators i.e. basic ontological elements 
+ * This class implements an ontology containing schemas for
+ * Primitive types and SL0 operators i.e. basic ontological elements
  * required for minimal agent interaction.
- * Users should always extend this ontology when defining their 
+ * Users should always extend this ontology when defining their
  * ontologies.
+ *
  * @author Federico Bergenti - Universita` di Parma
  * @author Giovanni Caire - TILAB
  */
 public class BasicOntology extends Ontology implements SL0Vocabulary {
 
-    // The singleton instance of this ontology
-    private static final BasicOntology theInstance = new BasicOntology();
-
-    static {
-        theInstance.initialize();
-    }
-
     // Primitive types names
     public static final String STRING = "BO_String";
     public static final String FLOAT = "BO_Float";
@@ -66,9 +60,14 @@ public class BasicOntology extends Ontology implements SL0Vocabulary {
     public static final String BOOLEAN = "BO_Boolean";
     public static final String DATE = "BO_Date";
     public static final String BYTE_SEQUENCE = "BO_Byte-sequence";
-
     // Content element list
     public static final String CONTENT_ELEMENT_LIST = ContentElementListSchema.BASE_NAME;
+    // The singleton instance of this ontology
+    private static final BasicOntology theInstance = new BasicOntology();
+
+    static {
+        theInstance.initialize();
+    }
 
     //#MIDP_EXCLUDE_BEGIN
     private transient Map, ObjectSchema> primitiveSchemas;
@@ -81,6 +80,97 @@ private BasicOntology() {
         super("BASIC_ONTOLOGY", (Ontology) null, null);
     }
 
+    /**
+     * Returns the singleton instance of the BasicOntology.
+     *
+     * @return the singleton instance of the BasicOntology
+     */
+    public static Ontology getInstance() {
+        return theInstance;
+    }
+
+    /**
+     * Convert, if possible, the numeric value srcValue into an instance of destClass
+     */
+    public static Object adjustPrimitiveValue(Object srcValue, Class destClass) {
+        Object destValue = srcValue;
+        if (srcValue != null) {
+            Class srcClass = srcValue.getClass();
+            // Note that we deal with Integer, int, Long, long... classes only --> we can compare the classes using == and != instead of using instanceof
+            if (srcClass != destClass) {
+                if (destClass == Integer.class ||
+                        destClass == int.class) {
+                    if (srcClass == Long.class) {
+                        destValue = ((Long) srcValue).intValue();
+                    } else if (srcClass == String.class) {
+                        destValue = Integer.valueOf((String) srcValue);
+                    }
+                } else if (destClass == Long.class ||
+                        destClass == long.class) {
+                    if (srcClass == Integer.class) {
+                        destValue = ((Integer) srcValue).longValue();
+                    } else if (srcClass == String.class) {
+                        destValue = Long.valueOf((String) srcValue);
+                    }
+                } else if (destClass == Float.class ||
+                        destClass == float.class) {
+                    if (srcClass == Integer.class) {
+                        destValue = ((Integer) srcValue).floatValue();
+                    } else if (srcClass == Long.class) {
+                        destValue = ((Long) srcValue).floatValue();
+                    } else if (srcClass == Double.class) {
+                        destValue = ((Double) srcValue).floatValue();
+                    } else if (srcClass == String.class) {
+                        destValue = Float.valueOf((String) srcValue);
+                    }
+                } else if (destClass == Double.class ||
+                        destClass == double.class) {
+                    if (srcClass == Integer.class) {
+                        destValue = ((Integer) srcValue).doubleValue();
+                    } else if (srcClass == Long.class) {
+                        destValue = ((Long) srcValue).doubleValue();
+                    } else if (srcClass == Float.class) {
+                        destValue = ((Float) srcValue).doubleValue();
+                    } else if (srcClass == String.class) {
+                        destValue = Double.valueOf((String) srcValue);
+                    }
+                } else if (destClass == String.class) {
+                    destValue = srcValue.toString();
+                } else if (destClass == Boolean.class ||
+                        destClass == boolean.class) {
+                    if (srcClass == String.class) {
+                        String s = (String) srcValue;
+                        if (s.equalsIgnoreCase("true") || s.equalsIgnoreCase("false")) {
+                            destValue = Boolean.valueOf(s);
+                        }
+                    }
+                } else if (destClass == Date.class) {
+                    try {
+                        // Try to convert string from FIPA-ISO8601 format
+                        destValue = ISO8601.toDate(srcValue.toString());
+                    } catch (Exception e) {
+                        try {
+                            // Try to convert string from W3C-ISO8601 format
+                            java.text.SimpleDateFormat W3CISO8601DateFormat = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
+                            destValue = W3CISO8601DateFormat.parse(srcValue.toString());
+                        } catch (java.text.ParseException e1) {
+                            // Date format not correct
+                        }
+                    }
+                }
+            }
+        }
+        return destValue;
+    }
+
+    /**
+     * @deprecated Use adjustPrimitiveValue() instead
+     */
+    public static Object resolveNumericValue(Object srcValue, Class destClass) {
+        return adjustPrimitiveValue(srcValue, destClass);
+    }
+    //#MIDP_EXCLUDE_END
+
     private void initialize() {
         // Note that the association between schemas and classes is not
         // necessary for the elements of the BasicOntology as the
@@ -117,8 +207,8 @@ private void initialize() {
 			add(new PrimitiveSchema(STRING));
 			add(new PrimitiveSchema(DATE));
 			add(new PrimitiveSchema(BYTE_SEQUENCE));
-			add(new ConceptSchema(AID)); 
-			add(new AgentActionSchema(ACLMSG)); 
+			add(new ConceptSchema(AID));
+			add(new AgentActionSchema(ACLMSG));
 			add(new PredicateSchema(TRUE_PROPOSITION));
 			add(new PredicateSchema(FALSE_PROPOSITION));
 			add(new AgentActionSchema(ACTION));
@@ -178,6 +268,8 @@ private void initialize() {
         }
     }
 
+    //#APIDOC_EXCLUDE_BEGIN
+
     //#MIDP_EXCLUDE_BEGIN
     private void fillPrimitiveSchemas() throws OntologyException {
         // This map is only needed to make the getSchema(Class) method work properly also in the case of java primitives
@@ -205,21 +297,12 @@ private void readObject(java.io.ObjectInputStream in) throws java.io.IOException
             oe.printStackTrace();
         }
     }
-    //#MIDP_EXCLUDE_END
-
-    /**
-     * Returns the singleton instance of the BasicOntology.
-     * @return the singleton instance of the BasicOntology
-     */
-    public static Ontology getInstance() {
-        return theInstance;
-    }
-
-    //#APIDOC_EXCLUDE_BEGIN
+    //#APIDOC_EXCLUDE_END
 
     /**
      * This method is redefined as BasicOntology does not use an
      * Introspector for performance reason
+     *
      * @see Ontology#toObject(AbsObject)
      */
     protected Object toObject(AbsObject abs, String lcType, Ontology referenceOnto) throws OntologyException {
@@ -315,6 +398,7 @@ protected Object toObject(AbsObject abs, String lcType, Ontology referenceOnto)
     /**
      * This method is redefined as BasicOntology does not use an
      * Introspector for performance reason
+     *
      * @see Ontology#toObject(AbsObject)
      */
     protected AbsObject fromObject(Object obj, Ontology referenceOnto) throws OntologyException {
@@ -428,11 +512,11 @@ protected AbsObject fromObject(Object obj, Ontology referenceOnto) throws Ontolo
             throw new OntologyException("Unexpected error externalising " + obj + ".", t);
         }
     }
-    //#APIDOC_EXCLUDE_END
 
     /**
      * Redefine the getSchema() method to take into
      * account ACL performatives.
+     *
      * @param name the name of the schema in the vocabulary.
      * @return the schema or null if the schema is not found.
      * @throws OntologyException
@@ -448,9 +532,12 @@ public ObjectSchema getSchema(String name) throws OntologyException {
         return ret;
     }
 
+    //#MIDP_EXCLUDE_BEGIN
+
     /**
      * Redefine the getSchema() method to take into
      * account java primitives.
+     *
      * @param clazz the class whose associated schema must be retrieved.
      * @return the schema associated to the given class or null if the schema is not found.
      * @throws OntologyException
@@ -469,97 +556,14 @@ public ObjectSchema getSchema(Class clazz) throws OntologyException {
     }
 
     /**
-     Note that we don't want to keep 22 different schemas for the 22 
-     FIPA communicative acts --> We generate the schemas for communicative
-     acts on the fly as needed.
+     * Note that we don't want to keep 22 different schemas for the 22
+     * FIPA communicative acts --> We generate the schemas for communicative
+     * acts on the fly as needed.
      */
     private ObjectSchema createMsgSchema(String performative) throws OntologyException {
         AgentActionSchema msgSchema = new AgentActionSchema(performative);
         msgSchema.addSuperSchema((AgentActionSchema) getSchema(ACLMSG));
         return msgSchema;
     }
-
-    //#MIDP_EXCLUDE_BEGIN
-
-    /**
-     Convert, if possible, the numeric value srcValue into an instance of destClass
-     */
-    public static Object adjustPrimitiveValue(Object srcValue, Class destClass) {
-        Object destValue = srcValue;
-        if (srcValue != null) {
-            Class srcClass = srcValue.getClass();
-            // Note that we deal with Integer, int, Long, long... classes only --> we can compare the classes using == and != instead of using instanceof
-            if (srcClass != destClass) {
-                if (destClass == Integer.class ||
-                        destClass == int.class) {
-                    if (srcClass == Long.class) {
-                        destValue = ((Long) srcValue).intValue();
-                    } else if (srcClass == String.class) {
-                        destValue = Integer.valueOf((String) srcValue);
-                    }
-                } else if (destClass == Long.class ||
-                        destClass == long.class) {
-                    if (srcClass == Integer.class) {
-                        destValue = ((Integer) srcValue).longValue();
-                    } else if (srcClass == String.class) {
-                        destValue = Long.valueOf((String) srcValue);
-                    }
-                } else if (destClass == Float.class ||
-                        destClass == float.class) {
-                    if (srcClass == Integer.class) {
-                        destValue = ((Integer) srcValue).floatValue();
-                    } else if (srcClass == Long.class) {
-                        destValue = ((Long) srcValue).floatValue();
-                    } else if (srcClass == Double.class) {
-                        destValue = ((Double) srcValue).floatValue();
-                    } else if (srcClass == String.class) {
-                        destValue = Float.valueOf((String) srcValue);
-                    }
-                } else if (destClass == Double.class ||
-                        destClass == double.class) {
-                    if (srcClass == Integer.class) {
-                        destValue = ((Integer) srcValue).doubleValue();
-                    } else if (srcClass == Long.class) {
-                        destValue = ((Long) srcValue).doubleValue();
-                    } else if (srcClass == Float.class) {
-                        destValue = ((Float) srcValue).doubleValue();
-                    } else if (srcClass == String.class) {
-                        destValue = Double.valueOf((String) srcValue);
-                    }
-                } else if (destClass == String.class) {
-                    destValue = srcValue.toString();
-                } else if (destClass == Boolean.class ||
-                        destClass == boolean.class) {
-                    if (srcClass == String.class) {
-                        String s = (String) srcValue;
-                        if (s.equalsIgnoreCase("true") || s.equalsIgnoreCase("false")) {
-                            destValue = Boolean.valueOf(s);
-                        }
-                    }
-                } else if (destClass == Date.class) {
-                    try {
-                        // Try to convert string from FIPA-ISO8601 format
-                        destValue = ISO8601.toDate(srcValue.toString());
-                    } catch (Exception e) {
-                        try {
-                            // Try to convert string from W3C-ISO8601 format
-                            java.text.SimpleDateFormat W3CISO8601DateFormat = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
-                            destValue = W3CISO8601DateFormat.parse(srcValue.toString());
-                        } catch (java.text.ParseException e1) {
-                            // Date format not correct
-                        }
-                    }
-                }
-            }
-        }
-        return destValue;
-    }
-
-    /**
-     * @deprecated Use adjustPrimitiveValue() instead
-     */
-    public static Object resolveNumericValue(Object srcValue, Class destClass) {
-        return adjustPrimitiveValue(srcValue, destClass);
-    }
     //#MIDP_EXCLUDE_END
 }
diff --git a/src/jade/content/onto/BeanOntology.java b/src/jade/content/onto/BeanOntology.java
index 1ef2a05..9b1f9eb 100644
--- a/src/jade/content/onto/BeanOntology.java
+++ b/src/jade/content/onto/BeanOntology.java
@@ -147,6 +147,19 @@ public BeanOntology(String name, Ontology[] base) {
         bob = new BeanOntologyBuilder(this);
     }
 
+    private static Ontology[] ensureBasicOntology(Ontology[] base) {
+        if (base == null) {
+            return new Ontology[]{BasicOntology.getInstance()};
+        } else if (!Ontology.isBaseOntology(base, BasicOntology.getInstance().getName())) {
+            Ontology[] newBase = new Ontology[base.length + 1];
+            System.arraycopy(base, 0, newBase, 0, base.length);
+            newBase[base.length] = BasicOntology.getInstance();
+            return newBase;
+        } else {
+            return base;
+        }
+    }
+
     /**
      * Adds to the ontology the schema built from the class clazz.
      * The class must implement either Concept
@@ -208,17 +221,4 @@ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundE
         // Create a new instance of BOB
         bob = new BeanOntologyBuilder(this);
     }
-
-    private static Ontology[] ensureBasicOntology(Ontology[] base) {
-        if (base == null) {
-            return new Ontology[]{BasicOntology.getInstance()};
-        } else if (!Ontology.isBaseOntology(base, BasicOntology.getInstance().getName())) {
-            Ontology[] newBase = new Ontology[base.length + 1];
-            System.arraycopy(base, 0, newBase, 0, base.length);
-            newBase[base.length] = BasicOntology.getInstance();
-            return newBase;
-        } else {
-            return base;
-        }
-    }
 }
diff --git a/src/jade/content/onto/BeanOntologyBuilder.java b/src/jade/content/onto/BeanOntologyBuilder.java
index 0a1b815..98de9a6 100644
--- a/src/jade/content/onto/BeanOntologyBuilder.java
+++ b/src/jade/content/onto/BeanOntologyBuilder.java
@@ -42,9 +42,8 @@
 
 class BeanOntologyBuilder {
 
-    private final static Logger logger = Logger.getMyLogger(BeanOntologyBuilder.class.getName());
-
     public static final String ENUM_SLOT_NAME = "name";
+    private final static Logger logger = Logger.getMyLogger(BeanOntologyBuilder.class.getName());
     private static final String GETTER_PREFIX = "get";
     private static final String BOOLEAN_GETTER_PREFIX = "is";
     private static final String SETTER_PREFIX = "set";
@@ -147,10 +146,9 @@ private static String buildPropertyNameFromGetter(Method getter) {
     }
 
     private static String buildSetterNameFromBeanPropertyName(String beanPropertyName) {
-        StringBuilder sb = new StringBuilder(SETTER_PREFIX);
-        sb.append(Character.toUpperCase(beanPropertyName.charAt(0)));
-        sb.append(beanPropertyName.substring(1));
-        return sb.toString();
+        String sb = SETTER_PREFIX + Character.toUpperCase(beanPropertyName.charAt(0)) +
+                beanPropertyName.substring(1);
+        return sb;
     }
 
     private static boolean accessorsAreConsistent(Method getter, Method setter) {
@@ -273,8 +271,7 @@ private static Map buildAccessorsMap(String schemaName,
                             aggregateType = slotClazz.getComponentType();
                         }
                         Type slotType = getter.getGenericReturnType();
-                        if (slotType instanceof ParameterizedType) {
-                            ParameterizedType slotParameterizedType = (ParameterizedType) slotType;
+                        if (slotType instanceof ParameterizedType slotParameterizedType) {
                             Type[] actuals = slotParameterizedType.getActualTypeArguments();
                             // slotType must be an array or a Collection => we expect only 1 item in actuals
                             // get first element
diff --git a/src/jade/content/onto/ConceptSlotFunction.java b/src/jade/content/onto/ConceptSlotFunction.java
index bce9813..62d1a3a 100644
--- a/src/jade/content/onto/ConceptSlotFunction.java
+++ b/src/jade/content/onto/ConceptSlotFunction.java
@@ -40,6 +40,7 @@
  * (iota ?x (= (age (Person :name John)) ?x))
  * In order to exploit this feature it is necessary to instruct an ontology to use concept slots as functions by means of the
  * useConceptSlotsAsFunctions method of the Ontology class.
+ *
  * @since JADE 3.7
  */
 public class ConceptSlotFunction extends AbsConceptSlotFunction {
diff --git a/src/jade/content/onto/Introspectable.java b/src/jade/content/onto/Introspectable.java
index 5a48d75..77f51b7 100644
--- a/src/jade/content/onto/Introspectable.java
+++ b/src/jade/content/onto/Introspectable.java
@@ -29,32 +29,35 @@
 import jade.content.abs.AbsObject;
 
 /**
- This interface must be implemented by ontological classes that
- belong to an ontology using the MicroIntrospector.
- It includes methods by means of which an object can be converted
- into/from an abstract descriptor.
- see MicroIntrospector
- @author Giovanni Caire - TILAB
+ * This interface must be implemented by ontological classes that
+ * belong to an ontology using the MicroIntrospector.
+ * It includes methods by means of which an object can be converted
+ * into/from an abstract descriptor.
+ * see MicroIntrospector
+ *
+ * @author Giovanni Caire - TILAB
  */
 public interface Introspectable {
 
     /**
      * Externalise this object into the given abstract descriptor
-     * @param abs The abstract descriptor this object must externalise 
-     * itself into.
-     * @param onto The reference ontology 
+     *
+     * @param abs  The abstract descriptor this object must externalise
+     *             itself into.
+     * @param onto The reference ontology
      * @throws OntologyException If some error occurs during the externalisation
      */
     void externalise(AbsObject abs, Ontology onto) throws OntologyException;
 
     /**
-     * Internalise this object from a given abstract descriptor 
-     * @param abs The abstract descriptor this object must internalise 
-     * itself from
-     * @param onto The reference ontology 
-     * @throws UngroundedException If the abstract descriptor  
-     * contains a variable
-     * @throws OntologyException If some error occurs during the internalisation
+     * Internalise this object from a given abstract descriptor
+     *
+     * @param abs  The abstract descriptor this object must internalise
+     *             itself from
+     * @param onto The reference ontology
+     * @throws UngroundedException If the abstract descriptor
+     *                             contains a variable
+     * @throws OntologyException   If some error occurs during the internalisation
      */
     void internalise(AbsObject abs, Ontology onto) throws UngroundedException, OntologyException;
 }
diff --git a/src/jade/content/onto/Introspector.java b/src/jade/content/onto/Introspector.java
index a4fe2d8..22e48c6 100644
--- a/src/jade/content/onto/Introspector.java
+++ b/src/jade/content/onto/Introspector.java
@@ -31,22 +31,24 @@
 import java.io.Serializable;
 
 /**
- This interface defines the methods to convert objects of
- ontological classes into/from abstract descriptors. Each ontology
- has an Introspector and delegates it the conversion.
- @author Federico Bergenti - Universita` di Parma
+ * This interface defines the methods to convert objects of
+ * ontological classes into/from abstract descriptors. Each ontology
+ * has an Introspector and delegates it the conversion.
+ *
+ * @author Federico Bergenti - Universita` di Parma
  */
 public interface Introspector extends Serializable {
 
     /**
-     Check the structure of a java class associated to an ontological element
-     to ensure that translations to/from abstract descriptors and java objects
-     (instances of that class) can be accomplished by this introspector.
-     @param schema The schema of the ontological element
-     @param javaClass The java class associated to the ontologcal element
-     @param onto The Ontology that uses this Introspector
-     @throws OntologyException if the java class does not have the correct
-     structure
+     * Check the structure of a java class associated to an ontological element
+     * to ensure that translations to/from abstract descriptors and java objects
+     * (instances of that class) can be accomplished by this introspector.
+     *
+     * @param schema    The schema of the ontological element
+     * @param javaClass The java class associated to the ontologcal element
+     * @param onto      The Ontology that uses this Introspector
+     * @throws OntologyException if the java class does not have the correct
+     *                           structure
      */
     void checkClass(ObjectSchema schema, Class javaClass, Ontology onto)
             throws OntologyException;
diff --git a/src/jade/content/onto/JavaCollectionOntology.java b/src/jade/content/onto/JavaCollectionOntology.java
index 23e31b2..b68ede7 100644
--- a/src/jade/content/onto/JavaCollectionOntology.java
+++ b/src/jade/content/onto/JavaCollectionOntology.java
@@ -37,21 +37,23 @@ public class JavaCollectionOntology extends Ontology {
 
     private final Introspector introspector = new CFReflectiveIntrospector();
 
+    private JavaCollectionOntology() {
+        super("Java-Collection-ontology", (Ontology) null, null);
+    }
+
     /**
      * Returns the singleton instance of the JavaCollectionOntology.
+     *
      * @return the singleton instance of the JavaCollectionOntology
      */
     public static Ontology getInstance() {
         return theInstance;
     }
 
-    private JavaCollectionOntology() {
-        super("Java-Collection-ontology", (Ontology) null, null);
-    }
-
     //#APIDOC_EXCLUDE_BEGIN
 
     /**
+     *
      */
     protected Object toObject(AbsObject abs, String lcType, Ontology globalOnto) throws OntologyException {
         if (abs instanceof AbsAggregate) {
@@ -61,6 +63,7 @@ protected Object toObject(AbsObject abs, String lcType, Ontology globalOnto) thr
     }
 
     /**
+     *
      */
     protected AbsObject fromObject(Object obj, Ontology globalOnto) throws OntologyException {
         try {
diff --git a/src/jade/content/onto/MicroIntrospector.java b/src/jade/content/onto/MicroIntrospector.java
index 339909d..b69807d 100644
--- a/src/jade/content/onto/MicroIntrospector.java
+++ b/src/jade/content/onto/MicroIntrospector.java
@@ -31,26 +31,28 @@
 import jade.content.schema.ObjectSchema;
 
 /**
- This introspector does nothing but "asking objects to convert
- themselves into/from abstract descriptors". It could be used
- when working in Java environments where the reflection is not
- supported (MIDP). All classes in an ontology using this introspector
- must implement the Introspectable interface.
- @author Giovanni Caire - TILAB
+ * This introspector does nothing but "asking objects to convert
+ * themselves into/from abstract descriptors". It could be used
+ * when working in Java environments where the reflection is not
+ * supported (MIDP). All classes in an ontology using this introspector
+ * must implement the Introspectable interface.
+ *
+ * @author Giovanni Caire - TILAB
  */
 public class MicroIntrospector implements Introspector {
 
     /**
-     Check the structure of a java class associated to an ontological element
-     to ensure that translations to/from abstract descriptors and java objects
-     (instances of that class) can be accomplished by this introspector.
-     This is the case if javaClass implements the
-     Introspectable
-     @param schema The schema of the ontological element
-     @param javaClass The java class associated to the ontologcal element
-     @param onto The Ontology that uses this Introspector
-     @throws OntologyException if the java class does not have the correct
-     structure
+     * Check the structure of a java class associated to an ontological element
+     * to ensure that translations to/from abstract descriptors and java objects
+     * (instances of that class) can be accomplished by this introspector.
+     * This is the case if javaClass implements the
+     * Introspectable
+     *
+     * @param schema    The schema of the ontological element
+     * @param javaClass The java class associated to the ontologcal element
+     * @param onto      The Ontology that uses this Introspector
+     * @throws OntologyException if the java class does not have the correct
+     *                           structure
      */
     public void checkClass(ObjectSchema schema, Class javaClass, Ontology onto) throws OntologyException {
         // FIXME: Not yet implemented
diff --git a/src/jade/content/onto/Ontology.java b/src/jade/content/onto/Ontology.java
index 5b30893..5b21f60 100644
--- a/src/jade/content/onto/Ontology.java
+++ b/src/jade/content/onto/Ontology.java
@@ -150,19 +150,6 @@
  */
 public class Ontology implements Serializable {
     private static final String DEFAULT_INTROSPECTOR_CLASS = "jade.content.onto.ReflectiveIntrospector";
-    private final Ontology[] base;
-    private final String name;
-    private Introspector introspector;
-
-    private final Hashtable elements = new Hashtable<>(); // Maps type-names to schemas
-    private final Hashtable> classes = new Hashtable<>(); // Maps type-names to java classes
-    private final Hashtable, ObjectSchema> schemas = new Hashtable<>(); // Maps java classes to schemas
-
-    // We use an Hashtable as if it was a Set
-    private Hashtable conceptSlots;
-
-    private final Logger logger = Logger.getMyLogger(this.getClass().getName());
-
     // This is required for compatibility with CLDC MIDP where XXX.class
     // is not supported
     private static Class absObjectClass = null;
@@ -176,6 +163,16 @@ public class Ontology implements Serializable {
         }
     }
 
+    private final Ontology[] base;
+    private final String name;
+    private final Hashtable elements = new Hashtable<>(); // Maps type-names to schemas
+    private final Hashtable> classes = new Hashtable<>(); // Maps type-names to java classes
+    private final Hashtable, ObjectSchema> schemas = new Hashtable<>(); // Maps java classes to schemas
+    private final Logger logger = Logger.getMyLogger(this.getClass().getName());
+    private Introspector introspector;
+    // We use an Hashtable as if it was a Set
+    private Hashtable conceptSlots;
+
     /**
      * Construct an Ontology object with a given name
      * that extends a given ontology.
@@ -234,6 +231,101 @@ public Ontology(String name, Ontology[] base, Introspector introspector) {
         this.base = (base != null ? base : new Ontology[0]);
     }
 
+    /**
+     * Check whether a given object is a valid term.
+     * If it is an Aggregate (i.e. a List) it also check
+     * the elements.
+     *
+     * @throws OntologyException if the given object is not a valid term
+     */
+    public static void checkIsTerm(Object obj) throws OntologyException {
+        // FIXME: This method is likely to be removed as it does not add any value and creates problems
+        // when using the Serializable Ontology
+		/*if (obj instanceof String ||
+    		  obj instanceof Boolean ||
+    		  obj instanceof Integer ||
+    		  obj instanceof Long ||
+    		  //#MIDP_EXCLUDE_BEGIN
+    		  obj instanceof Float ||
+    		  obj instanceof Double ||
+    		  //#MIDP_EXCLUDE_END
+    		  obj instanceof Date ||
+    		  obj instanceof Term) {
+    		return;
+    	}
+    	if (obj instanceof List) {
+    		Iterator it = ((List) obj).iterator();
+    		while (it.hasNext()) {
+    			checkIsTerm(it.next());
+    		}
+    		return;
+    	}
+
+    	// If we reach this point the object is not a term
+    	throw new OntologyException("Object "+obj+" of class "+obj.getClass().getName()+" is not a term");
+		 */
+    }
+
+    public static AbsObject externalizeSlotValue(Object obj, Introspector introspector, Ontology referenceOnto) throws OntologyException {
+        try {
+            return introspector.externalizeAggregate(null, obj, null, referenceOnto);
+        } catch (NotAnAggregate nan) {
+
+            return referenceOnto.fromObject(obj);
+        }
+    }
+
+    public static Object internalizeSlotValue(AbsObject abs, Introspector introspector, Ontology referenceOnto) throws OntologyException {
+        if (abs.getAbsType() == AbsObject.ABS_AGGREGATE) {
+            return introspector.internalizeAggregate(null, (AbsAggregate) abs, null, referenceOnto);
+        }
+
+        return referenceOnto.toObject(abs);
+    }
+
+    //#J2ME_EXCLUDE_BEGIN
+    private static void addReferencedSchemas(ObjectSchema schema, List schemas) throws OntologyException {
+        ObjectSchema[] superSchemas = schema.getSuperSchemas();
+        for (ObjectSchema superSchema : superSchemas) {
+            addReferencedSchemas(superSchema, schemas);
+        }
+
+        if (schema instanceof AggregateSchema) {
+            ObjectSchema elementsSchema = ((AggregateSchema) schema).getElementsSchema();
+            if (elementsSchema != null) {
+                addReferencedSchemas(elementsSchema, schemas);
+            }
+        } else if (schema instanceof ConceptSchema) {
+            if (!schemas.contains(schema)) {
+                schemas.add(schema);
+            }
+
+            for (String slotName : schema.getNames()) {
+                ObjectSchema slotSchema = schema.getSchema(slotName);
+                addReferencedSchemas(slotSchema, schemas);
+            }
+        }
+    }
+
+    public static List getReferencedSchemas(ObjectSchema rootSchema) throws OntologyException {
+        List schemas = new ArrayList<>();
+        addReferencedSchemas(rootSchema, schemas);
+        return schemas;
+    }
+
+    public static boolean isBaseOntology(Ontology[] oo, String name) {
+        if (oo != null) {
+            for (Ontology o : oo) {
+                if (o.getName().equals(name)) {
+                    return true;
+                } else if (isBaseOntology(o.base, name)) {
+                    return true;
+                }
+            }
+        }
+        return false;
+    }
+
     /**
      * Retrieves the name of this ontology.
      *
@@ -256,7 +348,6 @@ public void add(ObjectSchema schema) throws OntologyException {
         add(schema, null);
     }
 
-
     /**
      * Adds a schema to the ontology and associates it to the class
      * javaClass
@@ -289,6 +380,8 @@ public void add(ObjectSchema schema, Class javaClass) throws OntologyExceptio
         }
     }
 
+    //#APIDOC_EXCLUDE_BEGIN
+
     /**
      * Retrieves the schema of element name in this ontology.
      * The search is extended to the base ontologies if the schema is not
@@ -469,8 +562,6 @@ private Ontology getDefiningOntology(String lcName) {
         return definingOntology;
     }
 
-    //#APIDOC_EXCLUDE_BEGIN
-
     /**
      * Converts an abstract descriptor to a Java object of the proper class.
      *
@@ -640,6 +731,12 @@ protected AbsObject fromObject(Object obj, Ontology globalOnto) throws UnknownSc
 
         throw new UnknownSchemaException();
     }
+    //#APIDOC_EXCLUDE_END
+
+
+    /////////////////////////
+    // Utility static methods
+    /////////////////////////
 
     private AbsObject externalizeSpecialType(Object obj, ObjectSchema schema, Class javaClass, Ontology globalOnto) throws OntologyException {
         if (introspector == null) {
@@ -684,6 +781,9 @@ protected void externalize(Object obj, AbsObject abs, ObjectSchema schema, Ontol
         }
     }
 
+
+    //#J2ME_EXCLUDE_BEGIN
+
     /**
      * Set the value of slot slotName as slotValue to object obj
      */
@@ -768,55 +868,11 @@ private Object getSlotValue(String slotName, Object obj, ObjectSchema schema) th
         }
         throw new UnknownSlotException(slotName);
     }
-    //#APIDOC_EXCLUDE_END
-
-
-    /////////////////////////
-    // Utility static methods
-    /////////////////////////
-
-    /**
-     * Check whether a given object is a valid term.
-     * If it is an Aggregate (i.e. a List) it also check
-     * the elements.
-     *
-     * @throws OntologyException if the given object is not a valid term
-     */
-    public static void checkIsTerm(Object obj) throws OntologyException {
-        // FIXME: This method is likely to be removed as it does not add any value and creates problems
-        // when using the Serializable Ontology
-		/*if (obj instanceof String ||
-    		  obj instanceof Boolean ||
-    		  obj instanceof Integer ||
-    		  obj instanceof Long ||
-    		  //#MIDP_EXCLUDE_BEGIN
-    		  obj instanceof Float ||
-    		  obj instanceof Double ||
-    		  //#MIDP_EXCLUDE_END
-    		  obj instanceof Date ||
-    		  obj instanceof Term) {
-    		return;
-    	}
-    	if (obj instanceof List) {
-    		Iterator it = ((List) obj).iterator();
-    		while (it.hasNext()) {
-    			checkIsTerm(it.next());
-    		}
-    		return;
-    	}
-
-    	// If we reach this point the object is not a term
-    	throw new OntologyException("Object "+obj+" of class "+obj.getClass().getName()+" is not a term");
-		 */
-    }
 
     public String toString() {
         return getClass().getName() + "-" + name;
     }
 
-
-    //#J2ME_EXCLUDE_BEGIN
-
     /**
      * Retrieve the names of the concepts defined in this ontology only (excluding extended ontologies).
      * It should be noticed that an agent-action is itself a concept and therefore the returned list
@@ -857,6 +913,9 @@ public List getConceptNames() {
     public List getOwnActionNames() {
         return getOwnElementNames(AgentActionSchema.class);
     }
+    //#J2ME_EXCLUDE_END
+
+    //#MIDP_EXCLUDE_BEGIN
 
     /**
      * Retrieve the names of all agent actions defined in this ontology (including extended ontologies).
@@ -882,6 +941,7 @@ public List getActionNames() {
     public List getOwnPredicateNames() {
         return getOwnElementNames(PredicateSchema.class);
     }
+    //#MIDP_EXCLUDE_END
 
     /**
      * Retrieve the names of all predicatess defined in this ontology (including extended ontologies).
@@ -919,9 +979,6 @@ private Set getElementNames(Class c) {
         }
         return names;
     }
-    //#J2ME_EXCLUDE_END
-
-    //#MIDP_EXCLUDE_BEGIN
 
     /**
      * Create a ConceptSlotFunction for a given slot of a given Concept.
@@ -988,67 +1045,6 @@ protected void useConceptSlotsAsFunctions() {
             }
         }
     }
-    //#MIDP_EXCLUDE_END
-
-    public static AbsObject externalizeSlotValue(Object obj, Introspector introspector, Ontology referenceOnto) throws OntologyException {
-        try {
-            return introspector.externalizeAggregate(null, obj, null, referenceOnto);
-        } catch (NotAnAggregate nan) {
-
-            return referenceOnto.fromObject(obj);
-        }
-    }
-
-    public static Object internalizeSlotValue(AbsObject abs, Introspector introspector, Ontology referenceOnto) throws OntologyException {
-        if (abs.getAbsType() == AbsObject.ABS_AGGREGATE) {
-            return introspector.internalizeAggregate(null, (AbsAggregate) abs, null, referenceOnto);
-        }
-
-        return referenceOnto.toObject(abs);
-    }
-
-    //#J2ME_EXCLUDE_BEGIN
-    private static void addReferencedSchemas(ObjectSchema schema, List schemas) throws OntologyException {
-        ObjectSchema[] superSchemas = schema.getSuperSchemas();
-        for (ObjectSchema superSchema : superSchemas) {
-            addReferencedSchemas(superSchema, schemas);
-        }
-
-        if (schema instanceof AggregateSchema) {
-            ObjectSchema elementsSchema = ((AggregateSchema) schema).getElementsSchema();
-            if (elementsSchema != null) {
-                addReferencedSchemas(elementsSchema, schemas);
-            }
-        } else if (schema instanceof ConceptSchema) {
-            if (!schemas.contains(schema)) {
-                schemas.add(schema);
-            }
-
-            for (String slotName : schema.getNames()) {
-                ObjectSchema slotSchema = schema.getSchema(slotName);
-                addReferencedSchemas(slotSchema, schemas);
-            }
-        }
-    }
-
-    public static List getReferencedSchemas(ObjectSchema rootSchema) throws OntologyException {
-        List schemas = new ArrayList<>();
-        addReferencedSchemas(rootSchema, schemas);
-        return schemas;
-    }
-
-    public static boolean isBaseOntology(Ontology[] oo, String name) {
-        if (oo != null) {
-            for (Ontology o : oo) {
-                if (o.getName().equals(name)) {
-                    return true;
-                } else if (isBaseOntology(o.base, name)) {
-                    return true;
-                }
-            }
-        }
-        return false;
-    }
 
     /**
      * Dump ontology to default output stream
diff --git a/src/jade/content/onto/OntologyException.java b/src/jade/content/onto/OntologyException.java
index 2d6154c..6ed129b 100644
--- a/src/jade/content/onto/OntologyException.java
+++ b/src/jade/content/onto/OntologyException.java
@@ -37,7 +37,6 @@ public class OntologyException extends ContentException {
      * Construct an OntologyException with a given message.
      *
      * @param message the message
-     *
      */
     public OntologyException(String message) {
         super(message);
diff --git a/src/jade/content/onto/SerializableOntology.java b/src/jade/content/onto/SerializableOntology.java
index 6569b85..83e7b39 100644
--- a/src/jade/content/onto/SerializableOntology.java
+++ b/src/jade/content/onto/SerializableOntology.java
@@ -45,24 +45,12 @@
  * @author Giovanni Caire - TILAB
  */
 public class SerializableOntology extends Ontology {
-    // The singleton instance of this ontology
-    private static final SerializableOntology theInstance = new SerializableOntology();
-
     public static final String SERIALIZABLE = "serializable";
     public static final String SERIALIZABLE_VALUE = "value";
-
-
+    // The singleton instance of this ontology
+    private static final SerializableOntology theInstance = new SerializableOntology();
     private ClassLoader myClassLoader;
 
-    /**
-     * Returns the singleton instance of the SerializableOntology.
-     *
-     * @return the singleton instance of the SerializableOntology
-     */
-    public static Ontology getInstance() {
-        return theInstance;
-    }
-
     /**
      * Construct a SerializableOntology object
      */
@@ -82,6 +70,15 @@ private SerializableOntology() {
         }
     }
 
+    /**
+     * Returns the singleton instance of the SerializableOntology.
+     *
+     * @return the singleton instance of the SerializableOntology
+     */
+    public static Ontology getInstance() {
+        return theInstance;
+    }
+
     public void setClassLoader(ClassLoader cl) {
         myClassLoader = cl;
     }
diff --git a/src/jade/content/onto/SlotAccessData.java b/src/jade/content/onto/SlotAccessData.java
index 6d8f4eb..75b77d8 100644
--- a/src/jade/content/onto/SlotAccessData.java
+++ b/src/jade/content/onto/SlotAccessData.java
@@ -75,10 +75,6 @@ class SlotAccessData implements Serializable {
         setterName = setter.getName();
     }
 
-    boolean isTypized() {
-        return type != null && type != Object.class && type != Term.class;
-    }
-
     static boolean isAggregate(Class clazz) {
         return (clazz.isArray() && clazz != byte[].class) || Collection.class.isAssignableFrom(clazz) || Collection.class.isAssignableFrom(clazz);
     }
@@ -91,6 +87,10 @@ static boolean isSet(Class clazz) {
         return Set.class.isAssignableFrom(clazz) || Set.class.isAssignableFrom(clazz);
     }
 
+    boolean isTypized() {
+        return type != null && type != Object.class && type != Term.class;
+    }
+
     @Override
     public String toString() {
         StringBuilder sb = new StringBuilder("SlotAccessData {");
diff --git a/src/jade/content/onto/UngroundedException.java b/src/jade/content/onto/UngroundedException.java
index 2b3c9aa..25bd376 100644
--- a/src/jade/content/onto/UngroundedException.java
+++ b/src/jade/content/onto/UngroundedException.java
@@ -30,14 +30,13 @@
  * Typically, thrown when applying Ontology.toObject(AbsObject)
  * to an ungrouded abstract descriptor.
  *
- * @see    jade.content.onto
  * @author Federico Bergenti - Universita` di Parma
+ * @see jade.content.onto
  */
 public class UngroundedException extends OntologyException {
 
     /**
      * Constructor
-     *
      */
     public UngroundedException() {
         super("The abstract descriptor contains variables.");
diff --git a/src/jade/content/onto/UnknownSchemaException.java b/src/jade/content/onto/UnknownSchemaException.java
index bc90cbe..ec0af17 100644
--- a/src/jade/content/onto/UnknownSchemaException.java
+++ b/src/jade/content/onto/UnknownSchemaException.java
@@ -31,8 +31,8 @@
  * This particular case of OntologyException is handled differently
  * as the schema can be defined in one of the base ontologies.
  *
- * @see    jade.content.onto
  * @author Giovanni Caire - TILAB
+ * @see jade.content.onto
  */
 public class UnknownSchemaException extends OntologyException {
 
diff --git a/src/jade/content/onto/basic/Action.java b/src/jade/content/onto/basic/Action.java
index 3e4b699..4602c03 100644
--- a/src/jade/content/onto/basic/Action.java
+++ b/src/jade/content/onto/basic/Action.java
@@ -36,9 +36,10 @@
 import jade.core.AID;
 
 /**
- This class implements the action operator of the
- FIPA SL0 action.
- @author Giovanni Caire - TILAB
+ * This class implements the action operator of the
+ * FIPA SL0 action.
+ *
+ * @author Giovanni Caire - TILAB
  */
 public class Action implements AgentAction, Introspectable {
     private AID actor;
diff --git a/src/jade/content/onto/basic/Done.java b/src/jade/content/onto/basic/Done.java
index 6ad3ca6..d44d9f5 100644
--- a/src/jade/content/onto/basic/Done.java
+++ b/src/jade/content/onto/basic/Done.java
@@ -28,9 +28,10 @@
 import jade.content.Predicate;
 
 /**
- This class implements the done operator of the
- FIPA SL0 action.
- @author Giovanni Caire - TILAB
+ * This class implements the done operator of the
+ * FIPA SL0 action.
+ *
+ * @author Giovanni Caire - TILAB
  */
 public class Done implements Predicate {
     private Concept action;
diff --git a/src/jade/content/onto/basic/Equals.java b/src/jade/content/onto/basic/Equals.java
index d3d3306..6da1f36 100644
--- a/src/jade/content/onto/basic/Equals.java
+++ b/src/jade/content/onto/basic/Equals.java
@@ -29,8 +29,9 @@
 import jade.content.onto.OntologyException;
 
 /**
- This class implements the = operator of the FIPA SL0 language.
- @author Giovanni Caire - TILAB
+ * This class implements the = operator of the FIPA SL0 language.
+ *
+ * @author Giovanni Caire - TILAB
  */
 public class Equals implements Predicate {
     private Object left;
diff --git a/src/jade/content/onto/basic/FalseProposition.java b/src/jade/content/onto/basic/FalseProposition.java
index 0e8d099..498719c 100644
--- a/src/jade/content/onto/basic/FalseProposition.java
+++ b/src/jade/content/onto/basic/FalseProposition.java
@@ -27,8 +27,9 @@
 import jade.content.Predicate;
 
 /**
- * This class represents the FALSE proposition i.e. a predicate 
+ * This class represents the FALSE proposition i.e. a predicate
  * that is always false.
+ *
  * @author Filippo Quarta - TILAB
  * @version $Date: 2003-11-24 14:47:00 +0100 (lun, 24 nov 2003) $ $Revision: 4597 $
  */
diff --git a/src/jade/content/onto/basic/TrueProposition.java b/src/jade/content/onto/basic/TrueProposition.java
index cc9260f..b85c856 100644
--- a/src/jade/content/onto/basic/TrueProposition.java
+++ b/src/jade/content/onto/basic/TrueProposition.java
@@ -27,8 +27,9 @@
 import jade.content.Predicate;
 
 /**
- * This class represents the TRUE proposition i.e. a predicate 
+ * This class represents the TRUE proposition i.e. a predicate
  * that is always true.
+ *
  * @author Giovanni Caire - TILAB
  */
 public class TrueProposition implements Predicate {
diff --git a/src/jade/content/package.html b/src/jade/content/package.html
index be985e9..3362b96 100644
--- a/src/jade/content/package.html
+++ b/src/jade/content/package.html
@@ -1,12 +1,12 @@
-
+
 
 
-    
-    
-    
-    
-    
+    
+    
+    
+    
+    
     This package and its sub-packages contain classes that support the user
         in creating and manipulating complex content expressio
     
 
+
     
     
 
diff --git a/src/jade/content/schema/AgentActionSchema.java b/src/jade/content/schema/AgentActionSchema.java
index b6b04f0..fdb63de 100644
--- a/src/jade/content/schema/AgentActionSchema.java
+++ b/src/jade/content/schema/AgentActionSchema.java
@@ -30,16 +30,17 @@
 import jade.content.onto.OntologyException;
 
 /**
- * The class to be used to define schemas of agent actions in 
+ * The class to be used to define schemas of agent actions in
  * an ontology.
  * Note that an AgentActionSchema should also be a ConceptSchema, but
  * this inheritance relation is cut as Java does not support
- * multiple inheritance. As a consequence in practice it will 
- * not be possible to define e.g. a ConceptSchema with a slot 
- * whose value must be instances of a certain type of agent-action 
+ * multiple inheritance. As a consequence in practice it will
+ * not be possible to define e.g. a ConceptSchema with a slot
+ * whose value must be instances of a certain type of agent-action
  * even if in theory this should be
- * possible as a ConceptSchema can have slots of type term and 
+ * possible as a ConceptSchema can have slots of type term and
  * an agent-action is a concept and therefore a term.
+ *
  * @author Federico Bergenti - Universita` di Parma
  */
 public class AgentActionSchema extends ConceptSchema {
@@ -57,6 +58,7 @@ private AgentActionSchema() {
 
     /**
      * Creates an AgentActionSchema with a given type-name.
+     *
      * @param typeName The name of this AgentActionSchema.
      */
     public AgentActionSchema(String typeName) {
@@ -65,6 +67,7 @@ public AgentActionSchema(String typeName) {
 
     /**
      * Retrieve the generic base schema for all agent actions.
+     *
      * @return the generic base schema for all agent actions.
      */
     public static ObjectSchema getBaseSchema() {
@@ -72,8 +75,9 @@ public static ObjectSchema getBaseSchema() {
     }
 
     /**
-     * Add a mandatory slot of type PredicateSchema to this schema. 
-     * @param name The name of the slot.
+     * Add a mandatory slot of type PredicateSchema to this schema.
+     *
+     * @param name       The name of the slot.
      * @param slotSchema The schema of the slot.
      */
     public void add(String name, PredicateSchema slotSchema) {
@@ -81,11 +85,12 @@ public void add(String name, PredicateSchema slotSchema) {
     }
 
     /**
-     * Add a slot of type PredicateSchema to this schema. 
-     * @param name The name of the slot.
-     * @param slotSchema The schema of the slot.
-     * @param optionality The optionality, i.e. OPTIONAL 
-     * or MANDATORY
+     * Add a slot of type PredicateSchema to this schema.
+     *
+     * @param name        The name of the slot.
+     * @param slotSchema  The schema of the slot.
+     * @param optionality The optionality, i.e. OPTIONAL
+     *                    or MANDATORY
      */
     public void add(String name, PredicateSchema slotSchema, int optionality) {
         super.add(name, slotSchema, optionality);
@@ -100,11 +105,12 @@ public AbsObject newInstance() throws OntologyException {
     }
 
     /**
-     Check whether a given abstract descriptor complies with this
-     schema.
-     @param abs The abstract descriptor to be checked
-     @throws OntologyException If the abstract descriptor does not
-     complies with this schema
+     * Check whether a given abstract descriptor complies with this
+     * schema.
+     *
+     * @param abs The abstract descriptor to be checked
+     * @throws OntologyException If the abstract descriptor does not
+     *                           complies with this schema
      */
     public void validate(AbsObject abs, Ontology onto) throws OntologyException {
         // Check the type of the abstract descriptor
@@ -117,19 +123,19 @@ public void validate(AbsObject abs, Ontology onto) throws OntologyException {
     }
 
     /**
-     Return true if
-     - s is the base schema for the XXXSchema class this schema is
-     an instance of (e.g. s is ConceptSchema.getBaseSchema() and this
-     schema is an instance of ConceptSchema)
-     - s is the base schema for a super-class of the XXXSchema class
-     this schema is an instance of (e.g. s is TermSchema.getBaseSchema()
-     and this schema is an instance of ConceptSchema.
-     Moreover, as AgentActionSchema extends GenericActionSchema, but should
-     also extend ConceptSchema (this is not possible in practice as
-     Java does not support multiple inheritance), this method
-     returns true also in the case that s is equals to, or is an
-     ancestor of, ConceptSchema.getBaseSchema() (i.e. TermSchema.getBaseSchema()
-     descends from s)
+     * Return true if
+     * - s is the base schema for the XXXSchema class this schema is
+     * an instance of (e.g. s is ConceptSchema.getBaseSchema() and this
+     * schema is an instance of ConceptSchema)
+     * - s is the base schema for a super-class of the XXXSchema class
+     * this schema is an instance of (e.g. s is TermSchema.getBaseSchema()
+     * and this schema is an instance of ConceptSchema.
+     * Moreover, as AgentActionSchema extends GenericActionSchema, but should
+     * also extend ConceptSchema (this is not possible in practice as
+     * Java does not support multiple inheritance), this method
+     * returns true also in the case that s is equals to, or is an
+     * ancestor of, ConceptSchema.getBaseSchema() (i.e. TermSchema.getBaseSchema()
+     * descends from s)
      */
     protected boolean descendsFrom(ObjectSchema s) {
         if (s != null) {
@@ -148,6 +154,7 @@ protected boolean descendsFrom(ObjectSchema s) {
     /**
      * Define that the result produced by the execution of an action described by this
      * schema has a structure conforming to a given term schema.
+     *
      * @param resultSchema the schema of the result
      */
     public void setResult(TermSchema resultSchema) {
@@ -159,9 +166,10 @@ public void setResult(TermSchema resultSchema) {
      * Define that the result produced by the execution of an action described by this
      * schema is an aggregate of n (with n between cardMin and cardMax) elements each one having
      * a structure conforming to a given term schema.
+     *
      * @param elementsSchema the schema of the elements in the result aggregate
-     * @param cardMin the result must include at least cardMin elements
-     * @param cardMax the result must include at most cardMax elements
+     * @param cardMin        the result must include at least cardMin elements
+     * @param cardMax        the result must include at most cardMax elements
      */
     public void setResult(TermSchema elementsSchema, int cardMin, int cardMax) {
         add(RESULT_SLOT_NAME, elementsSchema, cardMin, cardMax);
diff --git a/src/jade/content/schema/AggregateSchema.java b/src/jade/content/schema/AggregateSchema.java
index b10baaa..dfdc7ed 100644
--- a/src/jade/content/schema/AggregateSchema.java
+++ b/src/jade/content/schema/AggregateSchema.java
@@ -35,6 +35,7 @@
 /**
  * This class represent the schema of aggregate entities in
  * an ontology.
+ *
  * @author Federico Bergenti - Universita` di Parma
  */
 public class AggregateSchema extends TermSchema {
@@ -95,11 +96,12 @@ public TermSchema getElementsSchema() {
     }
 
     /**
-     Check whether a given abstract descriptor complies with this
-     schema.
-     @param abs The abstract descriptor to be checked
-     @throws OntologyException If the abstract descriptor does not
-     complies with this schema
+     * Check whether a given abstract descriptor complies with this
+     * schema.
+     *
+     * @param abs The abstract descriptor to be checked
+     * @throws OntologyException If the abstract descriptor does not
+     *                           complies with this schema
      */
     public void validate(AbsObject abs, Ontology onto) throws OntologyException {
         // Check the type of the abstract descriptor
@@ -121,13 +123,13 @@ public void validate(AbsObject abs, Ontology onto) throws OntologyException {
     }
 
     /**
-     Return true if
-     - s is the base schema for the XXXSchema class this schema is
-     an instance of (e.g. s is ConceptSchema.getBaseSchema() and this
-     schema is an instance of ConceptSchema)
-     - s is the base schema for a super-class of the XXXSchema class
-     this schema is an instance of (e.g. s is TermSchema.getBaseSchema()
-     and this schema is an instance of ConceptSchema)
+     * Return true if
+     * - s is the base schema for the XXXSchema class this schema is
+     * an instance of (e.g. s is ConceptSchema.getBaseSchema() and this
+     * schema is an instance of ConceptSchema)
+     * - s is the base schema for a super-class of the XXXSchema class
+     * this schema is an instance of (e.g. s is TermSchema.getBaseSchema()
+     * and this schema is an instance of ConceptSchema)
      */
     protected boolean descendsFrom(ObjectSchema s) {
         if (s != null) {
@@ -141,9 +143,9 @@ protected boolean descendsFrom(ObjectSchema s) {
     }
 
     /**
-     The difference between types of aggregates (such as SET and
-     SEQUENCE) is quite fuzy. Therefore we don't throw a validation
-     exception if a SET is found where a SEQUENCE is expected and VV.
+     * The difference between types of aggregates (such as SET and
+     * SEQUENCE) is quite fuzy. Therefore we don't throw a validation
+     * exception if a SET is found where a SEQUENCE is expected and VV.
      */
     public boolean equals(Object o) {
         if (o != null) {
diff --git a/src/jade/content/schema/ConceptSchema.java b/src/jade/content/schema/ConceptSchema.java
index a908ca6..02627c2 100644
--- a/src/jade/content/schema/ConceptSchema.java
+++ b/src/jade/content/schema/ConceptSchema.java
@@ -30,8 +30,9 @@
 import jade.content.onto.OntologyException;
 
 /**
- * The class to be used to define schemas of concepts in 
+ * The class to be used to define schemas of concepts in
  * an ontology.
+ *
  * @author Federico Bergenti - Universita` di Parma
  */
 public class ConceptSchema extends TermSchema {
@@ -49,6 +50,7 @@ private ConceptSchema() {
     /**
      * Creates a ConceptSchema with a given type-name,
      * e.g. PERSON, ADDRESS...
+     *
      * @param typeName The name of this ConceptSchema.
      */
     public ConceptSchema(String typeName) {
@@ -57,6 +59,7 @@ public ConceptSchema(String typeName) {
 
     /**
      * Retrieve the generic base schema for all concepts.
+     *
      * @return the generic base schema for all concepts.
      */
     public static ObjectSchema getBaseSchema() {
@@ -66,7 +69,8 @@ public static ObjectSchema getBaseSchema() {
     /**
      * Add a mandatory slot to the schema. The schema for this slot must
      * be a TermSchema.
-     * @param name The name of the slot.
+     *
+     * @param name       The name of the slot.
      * @param slotSchema The schema of the slot.
      */
     public void add(String name, TermSchema slotSchema) {
@@ -76,10 +80,11 @@ public void add(String name, TermSchema slotSchema) {
     /**
      * Add a slot to the schema. The schema for this slot must
      * be a TermSchema.
-     * @param name The name of the slot.
-     * @param slotSchema The schema of the slot.
+     *
+     * @param name        The name of the slot.
+     * @param slotSchema  The schema of the slot.
      * @param optionality The optionality, i.e., OPTIONAL
-     * or MANDATORY
+     *                    or MANDATORY
      */
     public void add(String name, TermSchema slotSchema, int optionality) {
         super.add(name, slotSchema, optionality);
@@ -95,12 +100,13 @@ public void add(String name, TermSchema slotSchema, int optionality) {
      * aggregate contains at least cardMin elements and
      * at most cardMax elements. By default the Aggregate
      * is of type BasicOntology.SEQUENCE.
-     * @param name The name of the slot.
+     *
+     * @param name           The name of the slot.
      * @param elementsSchema The schema for the elements of this slot.
-     * @param cardMin This slot must get at least cardMin
-     * values
-     * @param cardMax This slot can get at most cardMax
-     * values
+     * @param cardMin        This slot must get at least cardMin
+     *                       values
+     * @param cardMax        This slot can get at most cardMax
+     *                       values
      */
     public void add(String name, TermSchema elementsSchema, int cardMin, int cardMax) {
         super.add(name, elementsSchema, cardMin, cardMax);
@@ -110,13 +116,14 @@ public void add(String name, TermSchema elementsSchema, int cardMin, int cardMax
      * Add a slot with cardinality between cardMin
      * and cardMax to this schema and allow specifying the type
      * of Aggregate to be used for this slot.
-     * @param name The name of the slot.
+     *
+     * @param name           The name of the slot.
      * @param elementsSchema The schema for the elements of this slot.
-     * @param cardMin This slot must get at least cardMin
-     * values
-     * @param cardMax This slot can get at most cardMax
-     * values
-     * @param aggType The type of Aggregate to be used
+     * @param cardMin        This slot must get at least cardMin
+     *                       values
+     * @param cardMax        This slot can get at most cardMax
+     *                       values
+     * @param aggType        The type of Aggregate to be used
      * @see #add(String, TermSchema, int, int)
      */
     public void add(String name, TermSchema elementsSchema, int cardMin, int cardMax, String aggType) {
@@ -127,14 +134,15 @@ public void add(String name, TermSchema elementsSchema, int cardMin, int cardMax
      * Add a slot with optionality and cardinality between cardMin
      * and cardMax to this schema and allow specifying the type
      * of Aggregate to be used for this slot.
-     * @param name The name of the slot.
+     *
+     * @param name           The name of the slot.
      * @param elementsSchema The schema for the elements of this slot.
-     * @param cardMin This slot must get at least cardMin
-     * values
-     * @param cardMax This slot can get at most cardMax
-     * values
-     * @param aggType The type of Aggregate to be used
-     * @param optionality The optionality, i.e., OPTIONAL
+     * @param cardMin        This slot must get at least cardMin
+     *                       values
+     * @param cardMax        This slot can get at most cardMax
+     *                       values
+     * @param aggType        The type of Aggregate to be used
+     * @param optionality    The optionality, i.e., OPTIONAL
      * @see #add(String, ObjectSchema, int, int)
      */
     public void add(String name, ObjectSchema elementsSchema, int cardMin, int cardMax, String aggType, int optionality) {
@@ -155,12 +163,13 @@ public void addSuperSchema(ConceptSchema superClassSchema) {
     }
 
     /**
-     Add a Facet on a slot of this schema
-     @param slotName the name of the slot the Facet
-     must be added to.
-     @param f the Facet to be added.
-     @throws OntologyException if slotName does not identify
-     a valid slot in this schema
+     * Add a Facet on a slot of this schema
+     *
+     * @param slotName the name of the slot the Facet
+     *                 must be added to.
+     * @param f        the Facet to be added.
+     * @throws OntologyException if slotName does not identify
+     *                           a valid slot in this schema
      */
     public void addFacet(String slotName, Facet f) throws OntologyException {
         super.addFacet(slotName, f);
@@ -175,11 +184,12 @@ public AbsObject newInstance() throws OntologyException {
     }
 
     /**
-     Check whether a given abstract descriptor complies with this
-     schema.
-     @param abs The abstract descriptor to be checked
-     @throws OntologyException If the abstract descriptor does not
-     complies with this schema
+     * Check whether a given abstract descriptor complies with this
+     * schema.
+     *
+     * @param abs The abstract descriptor to be checked
+     * @throws OntologyException If the abstract descriptor does not
+     *                           complies with this schema
      */
     public void validate(AbsObject abs, Ontology onto) throws OntologyException {
         // Check the type of the abstract descriptor
@@ -192,13 +202,13 @@ public void validate(AbsObject abs, Ontology onto) throws OntologyException {
     }
 
     /**
-     Return true if
-     - s is the base schema for the XXXSchema class this schema is
-     an instance of (e.g. s is ConceptSchema.getBaseSchema() and this
-     schema is an instance of ConceptSchema)
-     - s is the base schema for a super-class of the XXXSchema class
-     this schema is an instance of (e.g. s is TermSchema.getBaseSchema()
-     and this schema is an instance of ConceptSchema)
+     * Return true if
+     * - s is the base schema for the XXXSchema class this schema is
+     * an instance of (e.g. s is ConceptSchema.getBaseSchema() and this
+     * schema is an instance of ConceptSchema)
+     * - s is the base schema for a super-class of the XXXSchema class
+     * this schema is an instance of (e.g. s is TermSchema.getBaseSchema()
+     * and this schema is an instance of ConceptSchema)
      */
     protected boolean descendsFrom(ObjectSchema s) {
         if (s != null) {
diff --git a/src/jade/content/schema/ContentElementListSchema.java b/src/jade/content/schema/ContentElementListSchema.java
index 5ecfd2b..a8be50f 100644
--- a/src/jade/content/schema/ContentElementListSchema.java
+++ b/src/jade/content/schema/ContentElementListSchema.java
@@ -40,9 +40,9 @@ public class ContentElementListSchema extends ContentElementSchema {
     private static final ContentElementListSchema baseSchema = new ContentElementListSchema();
 
     /**
-     * Construct a schema that vinculates an entity to be a content element 
-     * list. Note that there are no different types of content element 
-     * list as it 
+     * Construct a schema that vinculates an entity to be a content element
+     * list. Note that there are no different types of content element
+     * list as it
      * happens for concepts (e.g. Person, Address...), IREs (e.g. IOTA,
      * ANY, ALL...) and the like. Therefore there is no ContentElementListSchema
      * constructor that takes a String parameter.
@@ -53,6 +53,7 @@ private ContentElementListSchema() {
 
     /**
      * Retrieve the generic base schema for all content element lists.
+     *
      * @return the generic base schema for all content element lists.
      */
     public static ObjectSchema getBaseSchema() {
@@ -60,18 +61,19 @@ public static ObjectSchema getBaseSchema() {
     }
 
     /**
-     * Creates an Abstract descriptor to hold a content element list 
+     * Creates an Abstract descriptor to hold a content element list
      */
     public AbsObject newInstance() throws OntologyException {
         return new AbsContentElementList();
     }
 
     /**
-     Check whether a given abstract descriptor complies with this
-     schema.
-     @param abs The abstract descriptor to be checked
-     @throws OntologyException If the abstract descriptor does not
-     complies with this schema
+     * Check whether a given abstract descriptor complies with this
+     * schema.
+     *
+     * @param abs The abstract descriptor to be checked
+     * @throws OntologyException If the abstract descriptor does not
+     *                           complies with this schema
      */
     public void validate(AbsObject abs, Ontology onto) throws OntologyException {
         // Check the type of the abstract descriptor
@@ -93,13 +95,13 @@ public void validate(AbsObject abs, Ontology onto) throws OntologyException {
     }
 
     /**
-     Return true if
-     - s is the base schema for the XXXSchema class this schema is
-     an instance of (e.g. s is ConceptSchema.getBaseSchema() and this
-     schema is an instance of ConceptSchema)
-     - s is the base schema for a super-class of the XXXSchema class
-     this schema is an instance of (e.g. s is TermSchema.getBaseSchema()
-     and this schema is an instance of ConceptSchema)
+     * Return true if
+     * - s is the base schema for the XXXSchema class this schema is
+     * an instance of (e.g. s is ConceptSchema.getBaseSchema() and this
+     * schema is an instance of ConceptSchema)
+     * - s is the base schema for a super-class of the XXXSchema class
+     * this schema is an instance of (e.g. s is TermSchema.getBaseSchema()
+     * and this schema is an instance of ConceptSchema)
      */
     protected boolean descendsFrom(ObjectSchema s) {
         if (s != null) {
diff --git a/src/jade/content/schema/ContentElementSchema.java b/src/jade/content/schema/ContentElementSchema.java
index 9fc6caf..d2e266f 100644
--- a/src/jade/content/schema/ContentElementSchema.java
+++ b/src/jade/content/schema/ContentElementSchema.java
@@ -30,6 +30,7 @@
 /**
  * This class represents the schema of a generic content element in
  * an ontology.
+ *
  * @author Federico Bergenti - Universita` di Parma
  */
 public class ContentElementSchema extends ObjectSchemaImpl {
@@ -46,6 +47,7 @@ private ContentElementSchema() {
 
     /**
      * Creates a ContentElementSchema with a given type-name.
+     *
      * @param typeName The name of this ContentElementSchema.
      */
     protected ContentElementSchema(String typeName) {
@@ -54,6 +56,7 @@ protected ContentElementSchema(String typeName) {
 
     /**
      * Retrieve the generic base schema for all content elements.
+     *
      * @return the generic base schema for all content elements.
      */
     public static ObjectSchema getBaseSchema() {
@@ -69,13 +72,13 @@ public AbsObject newInstance() throws OntologyException {
     }
 
     /**
-     Return true if
-     - s is the base schema for the XXXSchema class this schema is
-     an instance of (e.g. s is ConceptSchema.getBaseSchema() and this
-     schema is an instance of ConceptSchema)
-     - s is the base schema for a super-class of the XXXSchema class
-     this schema is an instance of (e.g. s is TermSchema.getBaseSchema()
-     and this schema is an instance of ConceptSchema)
+     * Return true if
+     * - s is the base schema for the XXXSchema class this schema is
+     * an instance of (e.g. s is ConceptSchema.getBaseSchema() and this
+     * schema is an instance of ConceptSchema)
+     * - s is the base schema for a super-class of the XXXSchema class
+     * this schema is an instance of (e.g. s is TermSchema.getBaseSchema()
+     * and this schema is an instance of ConceptSchema)
      */
     protected boolean descendsFrom(ObjectSchema s) {
         if (s != null) {
diff --git a/src/jade/content/schema/Facet.java b/src/jade/content/schema/Facet.java
index 2ce9e79..64a0b30 100644
--- a/src/jade/content/schema/Facet.java
+++ b/src/jade/content/schema/Facet.java
@@ -31,17 +31,19 @@
 import java.io.Serializable;
 
 /**
- * Represent a generic Facet (i.e. a constraint on the possible 
- * values) that can be applied on a slot in a schema of 
+ * Represent a generic Facet (i.e. a constraint on the possible
+ * values) that can be applied on a slot in a schema of
  * an ontological element.
+ *
  * @author Giovanni Caire - TILAB
  */
 public interface Facet extends Serializable {
     /**
-     Check whether a given value for the slot this Facet applies
-     to is valid.
-     @param value The value to be checked
-     @throws OntologyException If the value is not valid
+     * Check whether a given value for the slot this Facet applies
+     * to is valid.
+     *
+     * @param value The value to be checked
+     * @throws OntologyException If the value is not valid
      */
     void validate(AbsObject value, Ontology onto) throws OntologyException;
 }
\ No newline at end of file
diff --git a/src/jade/content/schema/IRESchema.java b/src/jade/content/schema/IRESchema.java
index b0823b4..5122b19 100644
--- a/src/jade/content/schema/IRESchema.java
+++ b/src/jade/content/schema/IRESchema.java
@@ -31,22 +31,22 @@
 
 /**
  * This class represents the schema of an Identifying Referential
- * Expression (IRE) in an ontology. 
+ * Expression (IRE) in an ontology.
  * Note that an IRESchema should also be a TermSchema, but
  * this inheritance relation is cut as Java does not support
- * multiple inheritance. As a consequence in practice it will 
- * not be possible to define e.g. a ConceptSchema with a slot 
- * whose value must be instances of a certain type of IRE even if in theory 
- * this should be possible as a ConceptSchema can have slots 
+ * multiple inheritance. As a consequence in practice it will
+ * not be possible to define e.g. a ConceptSchema with a slot
+ * whose value must be instances of a certain type of IRE even if in theory
+ * this should be possible as a ConceptSchema can have slots
  * of type term and an IRE is a term.
+ *
  * @author Federico Bergenti - Universita` di Parma
  */
 public class IRESchema extends TermSchema {
     public static final String BASE_NAME = "IRE";
-    private static final IRESchema baseSchema = new IRESchema();
-
     public static final String VARIABLE = "Variable";
     public static final String PROPOSITION = "Proposition";
+    private static final IRESchema baseSchema = new IRESchema();
 
     /**
      * Construct a schema that vinculates an entity to be a generic
@@ -59,8 +59,9 @@ private IRESchema() {
     /**
      * Creates a IRESchema with a given type-name.
      * All ire-s have a variable and a proposition.
-     * @param typeName The name of this IRESchema 
-     * (e.g. IOTA, ANY, ALL).
+     *
+     * @param typeName The name of this IRESchema
+     *                 (e.g. IOTA, ANY, ALL).
      */
     public IRESchema(String typeName) {
         super(typeName);
@@ -71,6 +72,7 @@ public IRESchema(String typeName) {
 
     /**
      * Retrieve the generic base schema for all ire-s.
+     *
      * @return the generic base schema for all ire-s.
      */
     public static ObjectSchema getBaseSchema() {
@@ -86,11 +88,12 @@ public AbsObject newInstance() throws OntologyException {
     }
 
     /**
-     Check whether a given abstract descriptor complies with this
-     schema.
-     @param abs The abstract descriptor to be checked
-     @throws OntologyException If the abstract descriptor does not
-     complies with this schema
+     * Check whether a given abstract descriptor complies with this
+     * schema.
+     *
+     * @param abs The abstract descriptor to be checked
+     * @throws OntologyException If the abstract descriptor does not
+     *                           complies with this schema
      */
     public void validate(AbsObject abs, Ontology onto) throws OntologyException {
         // Check the type of the abstract descriptor
@@ -103,9 +106,9 @@ public void validate(AbsObject abs, Ontology onto) throws OntologyException {
     }
 
     /**
-     An IRE can be put whereever a term of whatever type is
-     required --> An IRESchema is
-     compatible with s if s descends from TermSchema.getBaseSchema()
+     * An IRE can be put whereever a term of whatever type is
+     * required --> An IRESchema is
+     * compatible with s if s descends from TermSchema.getBaseSchema()
      */
     public boolean isCompatibleWith(ObjectSchema s) {
         if (s != null) {
@@ -116,19 +119,19 @@ public boolean isCompatibleWith(ObjectSchema s) {
     }
 
     /**
-     Return true if
-     - s is the base schema for the XXXSchema class this schema is
-     an instance of (e.g. s is ConceptSchema.getBaseSchema() and this
-     schema is an instance of ConceptSchema)
-     - s is the base schema for a super-class of the XXXSchema class
-     this schema is an instance of (e.g. s is TermSchema.getBaseSchema()
-     and this schema is an instance of ConceptSchema.
-     Moreover, as IRESchema extends ContentElementSchema, but should
-     also extend TermSchema (this is not possible in practice as
-     Java does not support multiple inheritance), this method
-     returns true also in the case that s is equals to, or is an
-     ancestor of, TermSchema.getBaseSchema() (i.e. TermSchema.getBaseSchema()
-     descends from s)
+     * Return true if
+     * - s is the base schema for the XXXSchema class this schema is
+     * an instance of (e.g. s is ConceptSchema.getBaseSchema() and this
+     * schema is an instance of ConceptSchema)
+     * - s is the base schema for a super-class of the XXXSchema class
+     * this schema is an instance of (e.g. s is TermSchema.getBaseSchema()
+     * and this schema is an instance of ConceptSchema.
+     * Moreover, as IRESchema extends ContentElementSchema, but should
+     * also extend TermSchema (this is not possible in practice as
+     * Java does not support multiple inheritance), this method
+     * returns true also in the case that s is equals to, or is an
+     * ancestor of, TermSchema.getBaseSchema() (i.e. TermSchema.getBaseSchema()
+     * descends from s)
      */
     protected boolean descendsFrom(ObjectSchema s) {
         if (s != null) {
diff --git a/src/jade/content/schema/ObjectSchema.java b/src/jade/content/schema/ObjectSchema.java
index 7cee176..b2ec744 100644
--- a/src/jade/content/schema/ObjectSchema.java
+++ b/src/jade/content/schema/ObjectSchema.java
@@ -32,23 +32,24 @@
 
 /**
  * The common ancestor of all ontological schemas.
+ *
  * @author Federico Bergenti - Universita` di Parma
  * @author Giovanni Caire - TILAB
  */
 public abstract class ObjectSchema implements Serializable {
     /**
-     Canstant value indicating that a slot in a schema is mandatory,
-     i.e. its value must not be null
+     * Canstant value indicating that a slot in a schema is mandatory,
+     * i.e. its value must not be null
      */
     public static final int MANDATORY = 0;
     /**
-     Canstant value indicating that a slot in a schema is optional,
-     i.e. its value can be null
+     * Canstant value indicating that a slot in a schema is optional,
+     * i.e. its value can be null
      */
     public static final int OPTIONAL = 1;
     /**
-     Canstant value indicating that a slot in a schema has an
-     infinite maximum cardinality
+     * Canstant value indicating that a slot in a schema has an
+     * infinite maximum cardinality
      */
     public static final int UNLIMITED = -1;
 
@@ -59,6 +60,7 @@ public abstract class ObjectSchema implements Serializable {
 
     /**
      * Retrieve the generic base schema for all objects.
+     *
      * @return the generic base schema for all objects.
      */
     public static ObjectSchema getBaseSchema() {
@@ -67,16 +69,18 @@ public static ObjectSchema getBaseSchema() {
 
     /**
      * Add a slot to the schema.
-     * @param name The name of the slot.
-     * @param slotSchema The schema defining the type of the slot.
+     *
+     * @param name        The name of the slot.
+     * @param slotSchema  The schema defining the type of the slot.
      * @param optionality The optionality, i.e., OPTIONAL
-     * or MANDATORY
+     *                    or MANDATORY
      */
     protected abstract void add(String name, ObjectSchema slotSchema, int optionality);
 
     /**
      * Add a mandatory slot to the schema.
-     * @param name name of the slot.
+     *
+     * @param name       name of the slot.
      * @param slotSchema schema of the slot.
      */
     protected abstract void add(String name, ObjectSchema slotSchema);
@@ -91,12 +95,13 @@ public static ObjectSchema getBaseSchema() {
      * aggregate contains at least cardMin elements and
      * at most cardMax elements. By default the Aggregate
      * is of type BasicOntology.SEQUENCE.
-     * @param name The name of the slot.
+     *
+     * @param name           The name of the slot.
      * @param elementsSchema The schema for the elements of this slot.
-     * @param cardMin This slot must get at least cardMin
-     * values
-     * @param cardMax This slot can get at most cardMax
-     * values
+     * @param cardMin        This slot must get at least cardMin
+     *                       values
+     * @param cardMax        This slot can get at most cardMax
+     *                       values
      */
     protected abstract void add(String name, ObjectSchema elementsSchema, int cardMin, int cardMax);
 
@@ -104,13 +109,14 @@ public static ObjectSchema getBaseSchema() {
      * Add a slot with cardinality between cardMin
      * and cardMax to this schema and allow specifying the type
      * of Aggregate to be used for this slot.
-     * @param name The name of the slot.
+     *
+     * @param name           The name of the slot.
      * @param elementsSchema The schema for the elements of this slot.
-     * @param cardMin This slot must get at least cardMin
-     * values
-     * @param cardMax This slot can get at most cardMax
-     * values
-     * @param aggType The type of Aggregate to be used
+     * @param cardMin        This slot must get at least cardMin
+     *                       values
+     * @param cardMax        This slot can get at most cardMax
+     *                       values
+     * @param aggType        The type of Aggregate to be used
      * @see #add(String, ObjectSchema, int, int)
      */
     protected abstract void add(String name, ObjectSchema elementsSchema, int cardMin, int cardMax, String aggType);
@@ -118,20 +124,30 @@ public static ObjectSchema getBaseSchema() {
     /**
      * Add a super schema tho this schema, i.e. this schema will
      * inherit all characteristics from the super schema
+     *
      * @param superSchema the super schema.
      */
     protected abstract void addSuperSchema(ObjectSchema superSchema);
 
     /**
-     Add a Facet on a slot of this schema
-     @param slotName the name of the slot the Facet
-     must be added to.
-     @param f the Facet to be added.
-     @throws OntologyException if slotName does not identify
-     a valid slot in this schema
+     * Add a Facet on a slot of this schema
+     *
+     * @param slotName the name of the slot the Facet
+     *                 must be added to.
+     * @param f        the Facet to be added.
+     * @throws OntologyException if slotName does not identify
+     *                           a valid slot in this schema
      */
     protected abstract void addFacet(String slotName, Facet f) throws OntologyException;
 
+    /**
+     * Get the indication whether the preferred encoding for the slots
+     * of concepts compliant to this schema is by order or by name.
+     */
+    public boolean getEncodingByOrder() {
+        return encodingByOrder;
+    }
+
     /**
      * Sets an indication about whether the preferred encoding for the
      * slots of concepts compliants to this schema is by oredr or by name.
@@ -143,16 +159,9 @@ public void setEncodingByOrder(boolean b) {
         encodingByOrder = b;
     }
 
-    /**
-     * Get the indication whether the preferred encoding for the slots
-     * of concepts compliant to this schema is by order or by name.
-     */
-    public boolean getEncodingByOrder() {
-        return encodingByOrder;
-    }
-
     /**
      * Retrieves the name of the type of this schema.
+     *
      * @return the name of the type of this schema.
      */
     public abstract String getTypeName();
@@ -179,7 +188,7 @@ public boolean getEncodingByOrder() {
      * @param name The name of the slot.
      * @return the Schema of slot name
      * @throws OntologyException If no slot with this name is present
-     * in this schema.
+     *                           in this schema.
      */
     public abstract ObjectSchema getSchema(String name) throws OntologyException;
 
@@ -209,7 +218,7 @@ public boolean getEncodingByOrder() {
      * @param name The name of the slot.
      * @return true if the slot is mandatory.
      * @throws OntologyException If no slot with this name is present
-     * in this schema.
+     *                           in this schema.
      */
     public abstract boolean isMandatory(String name) throws OntologyException;
 
@@ -220,38 +229,39 @@ public boolean getEncodingByOrder() {
     public abstract AbsObject newInstance() throws OntologyException;
 
     /**
-     Check whether a given abstract descriptor complies with this
-     schema.
-     @param abs The abstract descriptor to be checked
-     @throws OntologyException If the abstract descriptor does not
-     complies with this schema
+     * Check whether a given abstract descriptor complies with this
+     * schema.
+     *
+     * @param abs The abstract descriptor to be checked
+     * @throws OntologyException If the abstract descriptor does not
+     *                           complies with this schema
      */
     public abstract void validate(AbsObject abs, Ontology onto) throws OntologyException;
 
 
     /**
-     Check if this schema is compatible with a given schema s.
-     This is the case if
-     1) This schema is equals to s
-     2) s is one of the super-schemas of this schema
-     3) This schema descends from s i.e.
-     - s is the base schema for the XXXSchema class this schema is
-     an instance of (e.g. s is ConceptSchema.getBaseSchema() and this
-     schema is an instance of ConceptSchema)
-     - s is the base schema for a super-class of the XXXSchema class
-     this schema is an instance of (e.g. s is TermSchema.getBaseSchema()
-     and this schema is an instance of ConceptSchema)
+     * Check if this schema is compatible with a given schema s.
+     * This is the case if
+     * 1) This schema is equals to s
+     * 2) s is one of the super-schemas of this schema
+     * 3) This schema descends from s i.e.
+     * - s is the base schema for the XXXSchema class this schema is
+     * an instance of (e.g. s is ConceptSchema.getBaseSchema() and this
+     * schema is an instance of ConceptSchema)
+     * - s is the base schema for a super-class of the XXXSchema class
+     * this schema is an instance of (e.g. s is TermSchema.getBaseSchema()
+     * and this schema is an instance of ConceptSchema)
      */
     public abstract boolean isCompatibleWith(ObjectSchema s);
 
     /**
-     Return true if
-     - s is the base schema for the XXXSchema class this schema is
-     an instance of (e.g. s is ConceptSchema.getBaseSchema() and this
-     schema is an instance of ConceptSchema)
-     - s is the base schema for a super-class of the XXXSchema class
-     this schema is an instance of (e.g. s is TermSchema.getBaseSchema()
-     and this schema is an instance of ConceptSchema)
+     * Return true if
+     * - s is the base schema for the XXXSchema class this schema is
+     * an instance of (e.g. s is ConceptSchema.getBaseSchema() and this
+     * schema is an instance of ConceptSchema)
+     * - s is the base schema for a super-class of the XXXSchema class
+     * this schema is an instance of (e.g. s is TermSchema.getBaseSchema()
+     * and this schema is an instance of ConceptSchema)
      */
     protected abstract boolean descendsFrom(ObjectSchema s);
 
@@ -269,6 +279,7 @@ this schema is an instance of (e.g. s is TermSchema.getBaseSchema()
     /**
      * Retrieves an array containing the direct super-schemas of this schema.
      * If this schema has no super-schema an empty array is returned
+     *
      * @return an array containing the direct super-schemas of this schema.
      * @since JADE 3.7
      */
@@ -278,6 +289,7 @@ this schema is an instance of (e.g. s is TermSchema.getBaseSchema()
      * Retrieves the facets defined upon a slot. More in details this method returns
      * all facets defined in this schema plus all facets defined in super-schemas
      * up to the schema actually declaring the given slot.
+     *
      * @param slotName the name of the slot
      * @return the facets defined upon a slot or null if the specified slot is not found.
      */
diff --git a/src/jade/content/schema/ObjectSchemaImpl.java b/src/jade/content/schema/ObjectSchemaImpl.java
index bc2802e..64cf566 100644
--- a/src/jade/content/schema/ObjectSchemaImpl.java
+++ b/src/jade/content/schema/ObjectSchemaImpl.java
@@ -42,27 +42,13 @@
  * @author Giovanni Caire - TILAB
  */
 class ObjectSchemaImpl extends ObjectSchema {
-    private final Logger logger = Logger.getMyLogger(this.getClass().getName());
-
     static final String RESULT_SLOT_NAME = "__Result_SLOT_123";
 
-    private class SlotDescriptor implements Serializable {
-        private final String name;
-        private final ObjectSchema schema;
-        private final int optionality;
-
-        /**
-         * Construct a SlotDescriptor
-         */
-        private SlotDescriptor(String name, ObjectSchema schema, int optionality) {
-            this.name = name;
-            this.schema = schema;
-            this.optionality = optionality;
-        }
-
+    static {
+        baseSchema = new ObjectSchemaImpl();
     }
 
-
+    private final Logger logger = Logger.getMyLogger(this.getClass().getName());
     private String typeName = null;
     private Hashtable slots;
     private Vector slotNames;
@@ -79,10 +65,6 @@ private SlotDescriptor(String name, ObjectSchema schema, int optionality) {
 
     private Hashtable> facets;
 
-    static {
-        baseSchema = new ObjectSchemaImpl();
-    }
-
     /**
      * Construct a schema that vinculates an entity to be a generic
      * object (i.e. no constraints at all)
@@ -729,5 +711,21 @@ public boolean isAssignableFrom(ObjectSchema s) {
         }
     }
 
+    private class SlotDescriptor implements Serializable {
+        private final String name;
+        private final ObjectSchema schema;
+        private final int optionality;
+
+        /**
+         * Construct a SlotDescriptor
+         */
+        private SlotDescriptor(String name, ObjectSchema schema, int optionality) {
+            this.name = name;
+            this.schema = schema;
+            this.optionality = optionality;
+        }
+
+    }
+
 }
 
diff --git a/src/jade/content/schema/PredicateSchema.java b/src/jade/content/schema/PredicateSchema.java
index 2aa4e5e..297c728 100644
--- a/src/jade/content/schema/PredicateSchema.java
+++ b/src/jade/content/schema/PredicateSchema.java
@@ -30,8 +30,9 @@
 import jade.content.onto.OntologyException;
 
 /**
- * The class to be used to define schemas of predicates in 
+ * The class to be used to define schemas of predicates in
  * an ontology.
+ *
  * @author Federico Bergenti - Universita` di Parma
  */
 public class PredicateSchema extends ContentElementSchema {
@@ -50,6 +51,7 @@ private PredicateSchema() {
     /**
      * Creates a PredicateSchema with a given type-name,
      * e.g. FATHER_OF, WORKS_FOR...
+     *
      * @param typeName The name of this PredicateSchema.
      */
     public PredicateSchema(String typeName) {
@@ -59,6 +61,7 @@ public PredicateSchema(String typeName) {
 
     /**
      * Retrieve the generic base schema for all predicates.
+     *
      * @return the generic base schema for all predicates.
      */
     public static ObjectSchema getBaseSchema() {
@@ -66,8 +69,9 @@ public static ObjectSchema getBaseSchema() {
     }
 
     /**
-     * Add a mandatory slot to this schema. 
-     * @param name The name of the slot.
+     * Add a mandatory slot to this schema.
+     *
+     * @param name       The name of the slot.
      * @param slotSchema The schema of the slot.
      */
     public void add(String name, ObjectSchema slotSchema) {
@@ -75,12 +79,12 @@ public void add(String name, ObjectSchema slotSchema) {
     }
 
     /**
-     * Add a slot to this schema. 
+     * Add a slot to this schema.
      *
-     * @param name The name of the slot.
-     * @param slotSchema The schema of the slot.
-     * @param optionality The optionality, i.e. OPTIONAL 
-     * or MANDATORY
+     * @param name        The name of the slot.
+     * @param slotSchema  The schema of the slot.
+     * @param optionality The optionality, i.e. OPTIONAL
+     *                    or MANDATORY
      */
     public void add(String name, ObjectSchema slotSchema, int optionality) {
         super.add(name, slotSchema, optionality);
@@ -88,20 +92,21 @@ public void add(String name, ObjectSchema slotSchema, int optionality) {
 
     /**
      * Add a slot with cardinality between cardMin
-     * and cardMax to this schema. 
+     * and cardMax to this schema.
      * Adding such a slot corresponds to add a slot
      * of type Aggregate and then to add proper facets (constraints)
      * to check that the type of the elements in the aggregate are
-     * compatible with elementsSchema and that the 
+     * compatible with elementsSchema and that the
      * aggregate contains at least cardMin elements and
-     * at most cardMax elements. By default the Aggregate 
+     * at most cardMax elements. By default the Aggregate
      * is of type BasicOntology.SEQUENCE.
-     * @param name The name of the slot.
+     *
+     * @param name           The name of the slot.
      * @param elementsSchema The schema for the elements of this slot.
-     * @param cardMin This slot must get at least cardMin
-     * values
-     * @param cardMax This slot can get at most cardMax
-     * values
+     * @param cardMin        This slot must get at least cardMin
+     *                       values
+     * @param cardMax        This slot can get at most cardMax
+     *                       values
      */
     public void add(String name, TermSchema elementsSchema, int cardMin, int cardMax) {
         super.add(name, elementsSchema, cardMin, cardMax);
@@ -111,13 +116,14 @@ public void add(String name, TermSchema elementsSchema, int cardMin, int cardMax
      * Add a slot with cardinality between cardMin
      * and cardMax to this schema and allow specifying the type
      * of Aggregate to be used for this slot.
-     * @param name The name of the slot.
+     *
+     * @param name           The name of the slot.
      * @param elementsSchema The schema for the elements of this slot.
-     * @param cardMin This slot must get at least cardMin
-     * values
-     * @param cardMax This slot can get at most cardMax
-     * values
-     * @param aggType The type of Aggregate to be used
+     * @param cardMin        This slot must get at least cardMin
+     *                       values
+     * @param cardMax        This slot can get at most cardMax
+     *                       values
+     * @param aggType        The type of Aggregate to be used
      * @see #add(String, TermSchema, int, int)
      */
     public void add(String name, TermSchema elementsSchema, int cardMin, int cardMax, String aggType) {
@@ -128,14 +134,15 @@ public void add(String name, TermSchema elementsSchema, int cardMin, int cardMax
      * Add a slot with optionality and cardinality between cardMin
      * and cardMax to this schema and allow specifying the type
      * of Aggregate to be used for this slot.
-     * @param name The name of the slot.
+     *
+     * @param name           The name of the slot.
      * @param elementsSchema The schema for the elements of this slot.
-     * @param cardMin This slot must get at least cardMin
-     * values
-     * @param cardMax This slot can get at most cardMax
-     * values
-     * @param aggType The type of Aggregate to be used
-     * @param optionality The optionality, i.e., OPTIONAL
+     * @param cardMin        This slot must get at least cardMin
+     *                       values
+     * @param cardMax        This slot can get at most cardMax
+     *                       values
+     * @param aggType        The type of Aggregate to be used
+     * @param optionality    The optionality, i.e., OPTIONAL
      * @see #add(String, ObjectSchema, int, int)
      */
     public void add(String name, ObjectSchema elementsSchema, int cardMin, int cardMax, String aggType, int optionality) {
@@ -143,9 +150,9 @@ public void add(String name, ObjectSchema elementsSchema, int cardMin, int cardM
     }
 
     /**
-     * Adds a super-schema to this schema. This allows defining 
+     * Adds a super-schema to this schema. This allows defining
      * inheritance relationships between ontological predicates.
-     * It must be noted that a predicate always inherits from another 
+     * It must be noted that a predicate always inherits from another
      * predicate --> A super-schema of a PredicateSchema
      * must be a PredicateSchema too.
      *
@@ -156,12 +163,13 @@ public void addSuperSchema(PredicateSchema superClassSchema) {
     }
 
     /**
-     Add a Facet on a slot of this schema
-     @param slotName the name of the slot the Facet
-     must be added to.
-     @param f the Facet to be added.
-     @throws OntologyException if slotName does not identify
-     a valid slot in this schema
+     * Add a Facet on a slot of this schema
+     *
+     * @param slotName the name of the slot the Facet
+     *                 must be added to.
+     * @param f        the Facet to be added.
+     * @throws OntologyException if slotName does not identify
+     *                           a valid slot in this schema
      */
     public void addFacet(String slotName, Facet f) throws OntologyException {
         super.addFacet(slotName, f);
@@ -176,11 +184,12 @@ public AbsObject newInstance() throws OntologyException {
     }
 
     /**
-     Check whether a given abstract descriptor complies with this
-     schema.
-     @param abs The abstract descriptor to be checked
-     @throws OntologyException If the abstract descriptor does not
-     complies with this schema
+     * Check whether a given abstract descriptor complies with this
+     * schema.
+     *
+     * @param abs The abstract descriptor to be checked
+     * @throws OntologyException If the abstract descriptor does not
+     *                           complies with this schema
      */
     public void validate(AbsObject abs, Ontology onto) throws OntologyException {
         // Check the type of the abstract descriptor
@@ -193,13 +202,13 @@ public void validate(AbsObject abs, Ontology onto) throws OntologyException {
     }
 
     /**
-     Return true if
-     - s is the base schema for the XXXSchema class this schema is
-     an instance of (e.g. s is ConceptSchema.getBaseSchema() and this
-     schema is an instance of ConceptSchema)
-     - s is the base schema for a super-class of the XXXSchema class
-     this schema is an instance of (e.g. s is TermSchema.getBaseSchema()
-     and this schema is an instance of ConceptSchema)
+     * Return true if
+     * - s is the base schema for the XXXSchema class this schema is
+     * an instance of (e.g. s is ConceptSchema.getBaseSchema() and this
+     * schema is an instance of ConceptSchema)
+     * - s is the base schema for a super-class of the XXXSchema class
+     * this schema is an instance of (e.g. s is TermSchema.getBaseSchema()
+     * and this schema is an instance of ConceptSchema)
      */
     protected boolean descendsFrom(ObjectSchema s) {
         if (s != null) {
diff --git a/src/jade/content/schema/PrimitiveSchema.java b/src/jade/content/schema/PrimitiveSchema.java
index 7c0af58..9af2cb7 100644
--- a/src/jade/content/schema/PrimitiveSchema.java
+++ b/src/jade/content/schema/PrimitiveSchema.java
@@ -32,6 +32,7 @@
 /**
  * This class represent the schema of primitive entities in
  * an ontology.
+ *
  * @author Federico Bergenti - Universita` di Parma
  */
 public class PrimitiveSchema extends TermSchema {
@@ -73,11 +74,12 @@ public AbsObject newInstance() throws OntologyException {
     }
 
     /**
-     Check whether a given abstract descriptor complies with this
-     schema.
-     @param abs The abstract descriptor to be checked
-     @throws OntologyException If the abstract descriptor does not
-     complies with this schema
+     * Check whether a given abstract descriptor complies with this
+     * schema.
+     *
+     * @param abs The abstract descriptor to be checked
+     * @throws OntologyException If the abstract descriptor does not
+     *                           complies with this schema
      */
     public void validate(AbsObject abs, Ontology onto) throws OntologyException {
         // Check the type of the abstract descriptor
@@ -87,13 +89,13 @@ public void validate(AbsObject abs, Ontology onto) throws OntologyException {
     }
 
     /**
-     Return true if
-     - s is the base schema for the XXXSchema class this schema is
-     an instance of (e.g. s is ConceptSchema.getBaseSchema() and this
-     schema is an instance of ConceptSchema)
-     - s is the base schema for a super-class of the XXXSchema class
-     this schema is an instance of (e.g. s is TermSchema.getBaseSchema()
-     and this schema is an instance of ConceptSchema)
+     * Return true if
+     * - s is the base schema for the XXXSchema class this schema is
+     * an instance of (e.g. s is ConceptSchema.getBaseSchema() and this
+     * schema is an instance of ConceptSchema)
+     * - s is the base schema for a super-class of the XXXSchema class
+     * this schema is an instance of (e.g. s is TermSchema.getBaseSchema()
+     * and this schema is an instance of ConceptSchema)
      */
     protected boolean descendsFrom(ObjectSchema s) {
         if (s != null) {
diff --git a/src/jade/content/schema/TermSchema.java b/src/jade/content/schema/TermSchema.java
index b901fe9..7a77c69 100644
--- a/src/jade/content/schema/TermSchema.java
+++ b/src/jade/content/schema/TermSchema.java
@@ -30,6 +30,7 @@
 /**
  * This class represents the schema of a generic term in
  * an ontology.
+ *
  * @author Federico Bergenti - Universita` di Parma
  */
 public class TermSchema extends ObjectSchemaImpl {
@@ -71,13 +72,13 @@ public AbsObject newInstance() throws OntologyException {
     }
 
     /**
-     Return true if
-     - s is the base schema for the XXXSchema class this schema is
-     an instance of (e.g. s is ConceptSchema.getBaseSchema() and this
-     schema is an instance of ConceptSchema)
-     - s is the base schema for a super-class of the XXXSchema class
-     this schema is an instance of (e.g. s is TermSchema.getBaseSchema()
-     and this schema is an instance of ConceptSchema)
+     * Return true if
+     * - s is the base schema for the XXXSchema class this schema is
+     * an instance of (e.g. s is ConceptSchema.getBaseSchema() and this
+     * schema is an instance of ConceptSchema)
+     * - s is the base schema for a super-class of the XXXSchema class
+     * this schema is an instance of (e.g. s is TermSchema.getBaseSchema()
+     * and this schema is an instance of ConceptSchema)
      */
     protected boolean descendsFrom(ObjectSchema s) {
         if (s != null) {
diff --git a/src/jade/content/schema/VariableSchema.java b/src/jade/content/schema/VariableSchema.java
index 3f94650..a2fc09b 100644
--- a/src/jade/content/schema/VariableSchema.java
+++ b/src/jade/content/schema/VariableSchema.java
@@ -32,24 +32,24 @@
 
 /**
  * This class represents the schema of a variable.
+ *
  * @author Federico Bergenti - Universita` di Parma
  */
 public class VariableSchema extends TermSchema {
     public static final String BASE_NAME = "Variable";
-    private static final VariableSchema baseSchema = new VariableSchema();
-
     public static final String NAME = "Name";
     public static final String VALUE_TYPE = "ValueType";
+    private static final VariableSchema baseSchema = new VariableSchema();
 
     /**
      * Construct a schema that vinculates an entity to be a generic
      * variable.
-     * Note that there are no different types of variable as it 
+     * Note that there are no different types of variable as it
      * happens for concepts (e.g. Person, Address...), IREs (e.g. IOTA,
      * ANY, ALL...) and the like. Therefore there is no VariableSchema
      * constructor that takes a String parameter.
      * Not also that the type of the values that can be assumed by
-     * the variable is another story and is defined by the 
+     * the variable is another story and is defined by the
      * VARIABLE_VALUE_TYPE slot of the VariableSchema
      */
     private VariableSchema() {
@@ -80,11 +80,12 @@ public AbsObject newInstance() throws OntologyException {
     }
 
     /**
-     Check whether a given abstract descriptor complies with this
-     schema.
-     @param abs The abstract descriptor to be checked
-     @throws OntologyException If the abstract descriptor does not
-     complies with this schema
+     * Check whether a given abstract descriptor complies with this
+     * schema.
+     *
+     * @param abs The abstract descriptor to be checked
+     * @throws OntologyException If the abstract descriptor does not
+     *                           complies with this schema
      */
     public void validate(AbsObject abs, Ontology onto) throws OntologyException {
         // Check the type of the abstract descriptor
@@ -97,9 +98,9 @@ public void validate(AbsObject abs, Ontology onto) throws OntologyException {
     }
 
     /**
-     A variable can be put whereever a term of whatever type is
-     required --> A VariableSchema is
-     compatible with s if s descends from TermSchema.getBaseSchema()
+     * A variable can be put whereever a term of whatever type is
+     * required --> A VariableSchema is
+     * compatible with s if s descends from TermSchema.getBaseSchema()
      */
     public boolean isCompatibleWith(ObjectSchema s) {
         if (s != null) {
@@ -110,13 +111,13 @@ public boolean isCompatibleWith(ObjectSchema s) {
     }
 
     /**
-     Return true if
-     - s is the base schema for the XXXSchema class this schema is
-     an instance of (e.g. s is ConceptSchema.getBaseSchema() and this
-     schema is an instance of ConceptSchema)
-     - s is the base schema for a super-class of the XXXSchema class
-     this schema is an instance of (e.g. s is TermSchema.getBaseSchema()
-     and this schema is an instance of ConceptSchema)
+     * Return true if
+     * - s is the base schema for the XXXSchema class this schema is
+     * an instance of (e.g. s is ConceptSchema.getBaseSchema() and this
+     * schema is an instance of ConceptSchema)
+     * - s is the base schema for a super-class of the XXXSchema class
+     * this schema is an instance of (e.g. s is TermSchema.getBaseSchema()
+     * and this schema is an instance of ConceptSchema)
      */
     protected boolean descendsFrom(ObjectSchema s) {
         if (s != null) {
diff --git a/src/jade/content/schema/facets/CardinalityFacet.java b/src/jade/content/schema/facets/CardinalityFacet.java
index b609f0f..38de061 100644
--- a/src/jade/content/schema/facets/CardinalityFacet.java
+++ b/src/jade/content/schema/facets/CardinalityFacet.java
@@ -33,8 +33,9 @@
 import jade.content.schema.ObjectSchema;
 
 /**
- * This facet forces an AbsAggregate to contain a number of 
+ * This facet forces an AbsAggregate to contain a number of
  * elements that is comprised between a given min and a given max.
+ *
  * @author Giovanni Caire - TILAB
  */
 public class CardinalityFacet implements Facet {
@@ -42,11 +43,12 @@ public class CardinalityFacet implements Facet {
     private final int cardMax;
 
     /**
-     Construct a CardinalityFacet that forces
-     the number of elements in an AbsAggregate to be within
-     a given range
-     @param cardMin The range lower bound
-     @param cardMax The range upper bound
+     * Construct a CardinalityFacet that forces
+     * the number of elements in an AbsAggregate to be within
+     * a given range
+     *
+     * @param cardMin The range lower bound
+     * @param cardMax The range upper bound
      */
     public CardinalityFacet(int cardMin, int cardMax) {
         this.cardMin = cardMin;
@@ -62,11 +64,12 @@ public int getCardMax() {
     }
 
     /**
-     Check that
-     the number of elements in an AbsAggregate is within
-     a given range
-     @param value The value to be checked
-     @throws OntologyException If the value is not valid
+     * Check that
+     * the number of elements in an AbsAggregate is within
+     * a given range
+     *
+     * @param value The value to be checked
+     * @throws OntologyException If the value is not valid
      */
     public void validate(AbsObject value, Ontology onto) throws OntologyException {
         if (value instanceof AbsVariable) {
diff --git a/src/jade/content/schema/facets/DefaultValueFacet.java b/src/jade/content/schema/facets/DefaultValueFacet.java
index f523fce..91f0d7b 100644
--- a/src/jade/content/schema/facets/DefaultValueFacet.java
+++ b/src/jade/content/schema/facets/DefaultValueFacet.java
@@ -36,25 +36,26 @@ public class DefaultValueFacet implements Facet {
     private final Object defaultValue;
 
     /**
-     Construct a DefaultValueFacet that
-     set the default value of an AbsObject
+     * Construct a DefaultValueFacet that
+     * set the default value of an AbsObject
      */
     public DefaultValueFacet(Object defaultValue) {
         this.defaultValue = defaultValue;
     }
 
     /**
-     Get the default value associated to this facet
+     * Get the default value associated to this facet
      */
     public Object getDefaultValue() {
         return defaultValue;
     }
 
     /**
-     Check whether a given value for the slot this Facet applies
-     to is valid.
-     @param value The value to be checked
-     @throws OntologyException If the value is not valid
+     * Check whether a given value for the slot this Facet applies
+     * to is valid.
+     *
+     * @param value The value to be checked
+     * @throws OntologyException If the value is not valid
      */
     public void validate(AbsObject value, Ontology onto) throws OntologyException {
     }
diff --git a/src/jade/content/schema/facets/DocumentationFacet.java b/src/jade/content/schema/facets/DocumentationFacet.java
index 053b355..b4a8eca 100644
--- a/src/jade/content/schema/facets/DocumentationFacet.java
+++ b/src/jade/content/schema/facets/DocumentationFacet.java
@@ -33,25 +33,26 @@ public class DocumentationFacet implements Facet {
     private final String documentation;
 
     /**
-     Construct a DocumentationFacet that
-     set the documentation of an AbsObject
+     * Construct a DocumentationFacet that
+     * set the documentation of an AbsObject
      */
     public DocumentationFacet(String documentation) {
         this.documentation = documentation;
     }
 
     /**
-     Get the documentation associated to this facet
+     * Get the documentation associated to this facet
      */
     public String getDocumentation() {
         return documentation;
     }
 
     /**
-     Check whether a given value for the slot this Facet applies
-     to is valid.
-     @param value The value to be checked
-     @throws OntologyException If the value is not valid
+     * Check whether a given value for the slot this Facet applies
+     * to is valid.
+     *
+     * @param value The value to be checked
+     * @throws OntologyException If the value is not valid
      */
     public void validate(AbsObject value, Ontology onto) throws OntologyException {
     }
diff --git a/src/jade/content/schema/facets/JavaTypeFacet.java b/src/jade/content/schema/facets/JavaTypeFacet.java
index 6d74f2e..9c9891b 100644
--- a/src/jade/content/schema/facets/JavaTypeFacet.java
+++ b/src/jade/content/schema/facets/JavaTypeFacet.java
@@ -33,25 +33,26 @@ public class JavaTypeFacet implements Facet {
     private final String javaType;
 
     /**
-     Construct a JavaTypeFacet that
-     set the java type
+     * Construct a JavaTypeFacet that
+     * set the java type
      */
     public JavaTypeFacet(String javaType) {
         this.javaType = javaType;
     }
 
     /**
-     Get the java type associated to this facet
+     * Get the java type associated to this facet
      */
     public String getJavaType() {
         return javaType;
     }
 
     /**
-     Check whether a given value for the slot this Facet applies
-     to is valid.
-     @param value The value to be checked
-     @throws OntologyException If the value is not valid
+     * Check whether a given value for the slot this Facet applies
+     * to is valid.
+     *
+     * @param value The value to be checked
+     * @throws OntologyException If the value is not valid
      */
     public void validate(AbsObject value, Ontology onto) throws OntologyException {
     }
diff --git a/src/jade/content/schema/facets/PermittedValuesFacet.java b/src/jade/content/schema/facets/PermittedValuesFacet.java
index 142352c..4fccfa1 100644
--- a/src/jade/content/schema/facets/PermittedValuesFacet.java
+++ b/src/jade/content/schema/facets/PermittedValuesFacet.java
@@ -40,22 +40,22 @@ public class PermittedValuesFacet implements Facet {
     private final Object[] permittedValues;
 
     /**
-     Construct a PermittedValuesFacet that
-     forces an AbsPrimitive to contain a specific set of values
+     * Construct a PermittedValuesFacet that
+     * forces an AbsPrimitive to contain a specific set of values
      */
     public PermittedValuesFacet(Object[] permittedValues) {
         this.permittedValues = permittedValues;
     }
 
     /**
-     Get the permitted values associated to this facet
+     * Get the permitted values associated to this facet
      */
     public Object[] getPermittedValues() {
         return permittedValues;
     }
 
     /**
-     Get the permitted values as string associated to this facet
+     * Get the permitted values as string associated to this facet
      */
     public String getPermittedValuesAsString() {
         StringBuilder sb = new StringBuilder();
@@ -71,10 +71,11 @@ public String getPermittedValuesAsString() {
     }
 
     /**
-     Check whether a given value for the slot this Facet applies
-     to is valid.
-     @param value The value to be checked
-     @throws OntologyException If the value is not valid
+     * Check whether a given value for the slot this Facet applies
+     * to is valid.
+     *
+     * @param value The value to be checked
+     * @throws OntologyException If the value is not valid
      */
     public void validate(AbsObject value, Ontology onto) throws OntologyException {
         if (!(value instanceof AbsPrimitive absPrimitive)) {
diff --git a/src/jade/content/schema/facets/RegexFacet.java b/src/jade/content/schema/facets/RegexFacet.java
index 0f21317..8ad4527 100644
--- a/src/jade/content/schema/facets/RegexFacet.java
+++ b/src/jade/content/schema/facets/RegexFacet.java
@@ -41,26 +41,27 @@ public class RegexFacet implements Facet {
     private final String regex;
 
     /**
-     Construct a PermittedValuesFacet that
-     forces an AbsPrimitive to contain a specific set of values
-     expressed as a regular expression
+     * Construct a PermittedValuesFacet that
+     * forces an AbsPrimitive to contain a specific set of values
+     * expressed as a regular expression
      */
     public RegexFacet(String regex) {
         this.regex = regex;
     }
 
     /**
-     Get the regex associated to this facet
+     * Get the regex associated to this facet
      */
     public String getRegex() {
         return regex;
     }
 
     /**
-     Check whether a given value for the slot this Facet applies
-     to is valid.
-     @param value The value to be checked
-     @throws OntologyException If the value is not valid
+     * Check whether a given value for the slot this Facet applies
+     * to is valid.
+     *
+     * @param value The value to be checked
+     * @throws OntologyException If the value is not valid
      */
     public void validate(AbsObject value, Ontology onto) throws OntologyException {
         if (!(value instanceof AbsPrimitive absPrimitive)) {
diff --git a/src/jade/content/schema/facets/TypedAggregateFacet.java b/src/jade/content/schema/facets/TypedAggregateFacet.java
index 16c7968..0242e98 100644
--- a/src/jade/content/schema/facets/TypedAggregateFacet.java
+++ b/src/jade/content/schema/facets/TypedAggregateFacet.java
@@ -38,32 +38,34 @@
 /**
  * This facet forces the elements in an AbsAggregate
  * to be compliant to a given schema.
+ *
  * @author Giovanni Caire - TILAB
  */
 public class TypedAggregateFacet implements Facet {
     private final ObjectSchema type;
 
     /**
-     Construct a TypedAggregateFacet that forces
-     the elements in an AbsAggregate to be instances of a given
-     schema
+     * Construct a TypedAggregateFacet that forces
+     * the elements in an AbsAggregate to be instances of a given
+     * schema
      */
     public TypedAggregateFacet(ObjectSchema s) {
         type = s;
     }
 
     /**
-     Get the schema associated to this facet
+     * Get the schema associated to this facet
      */
     public ObjectSchema getType() {
         return type;
     }
 
     /**
-     Check whether a given value for the slot this Facet applies
-     to is valid.
-     @param value The value to be checked
-     @throws OntologyException If the value is not valid
+     * Check whether a given value for the slot this Facet applies
+     * to is valid.
+     *
+     * @param value The value to be checked
+     * @throws OntologyException If the value is not valid
      */
     public void validate(AbsObject value, Ontology onto) throws OntologyException {
         if (value instanceof AbsVariable) {
diff --git a/src/jade/core/AID.java b/src/jade/core/AID.java
index 53ea3b4..c6d32d9 100644
--- a/src/jade/core/AID.java
+++ b/src/jade/core/AID.java
@@ -40,27 +40,37 @@
  */
 public class AID implements Comparable, Serializable {
     public static final char HAP_SEPARATOR = '@';
-
+    /**
+     * constant to be used in the constructor of the AID
+     **/
+    public static final boolean ISGUID = true;
+    /**
+     * constant to be used in the constructor of the AID
+     **/
+    public static final boolean ISLOCALNAME = false;
+    /**
+     * Key to retrieve the agent class name as a user defined slot of
+     * the AID included in the AMSAgentDescription registered with
+     * the AMS.
+     */
+    public static final String AGENT_CLASSNAME = "JADE-agent-classname";
+    private static final int EXPECTED_ADDRESSES_SIZE = 1;
+    private static final int EXPECTED_RESOLVERS_SIZE = 1;
     // Unique ID of the platform, used to build the GUID of resident agents.
     private static String platformID;
-
     private String name;
-    private int hashCode;
-
-    private static final int EXPECTED_ADDRESSES_SIZE = 1;
-    private static final int EXPECTED_RESOLVERS_SIZE = 1;
-
-    //#MIDP_EXCLUDE_BEGIN
-    private List addresses = new ArrayList<>(EXPECTED_ADDRESSES_SIZE);
-    private List resolvers = new ArrayList<>(EXPECTED_RESOLVERS_SIZE);
     //#MIDP_EXCLUDE_END
 	/*#MIDP_INCLUDE_BEGIN
 	 private Vector addresses = new Vector(EXPECTED_ADDRESSES_SIZE,1);
 	 private Vector resolvers = new Vector(EXPECTED_RESOLVERS_SIZE,1);
 	 #MIDP_INCLUDE_END*/
-
+    private int hashCode;
+    //#MIDP_EXCLUDE_BEGIN
+    private List addresses = new ArrayList<>(EXPECTED_ADDRESSES_SIZE);
+    private List resolvers = new ArrayList<>(EXPECTED_RESOLVERS_SIZE);
     private Properties userDefSlots = new Properties();
-
+    // For persistence service
+    private transient Long persistentID;
 
     /**
      * Constructs an Agent-Identifier whose slot name is set to an empty string
@@ -87,8 +97,6 @@ public AID() {
     public AID(String guid) {
         this(guid, ISGUID);
     }
-
-
     /**
      * Constructor for an Agent-identifier
      *
@@ -115,21 +123,17 @@ static final void setPlatformID(String id) {
         platformID = id;
     }
 
-    /**
-     * constant to be used in the constructor of the AID
-     **/
-    public static final boolean ISGUID = true;
-    /**
-     * constant to be used in the constructor of the AID
-     **/
-    public static final boolean ISLOCALNAME = false;
+    public static String createGUID(String localName, String platformName) {
+        String n = localName.trim();
+        return n.concat(HAP_SEPARATOR + platformName);
+    }
 
     /**
-     * Key to retrieve the agent class name as a user defined slot of
-     * the AID included in the AMSAgentDescription registered with
-     * the AMS.
+     * This method returns the name of the agent.
      */
-    public static final String AGENT_CLASSNAME = "JADE-agent-classname";
+    public String getName() {
+        return name;
+    }
 
     /**
      * This method permits to set the symbolic name of an agent.
@@ -140,32 +144,6 @@ public void setName(String n) {
         hashCode = name.toLowerCase().hashCode();
     }
 
-    /**
-     * This method permits to set the symbolic name of an agent.
-     * The passed parameter must be a local name.
-     */
-    public void setLocalName(String n) {
-        String hap = getPlatformID();
-        if (hap == null) {
-            throw new RuntimeException("Unknown Platform Name");
-        }
-        name = n.trim();
-        name = createGUID(name, hap);
-        hashCode = name.toLowerCase().hashCode();
-    }
-
-    public static String createGUID(String localName, String platformName) {
-        String n = localName.trim();
-        return n.concat(HAP_SEPARATOR + platformName);
-    }
-
-    /**
-     * This method returns the name of the agent.
-     */
-    public String getName() {
-        return name;
-    }
-
     /**
      * This method permits to add a transport address where
      * the agent can be contacted.
@@ -542,6 +520,20 @@ public String getLocalName() {
             return name.substring(0, atPos);
     }
 
+    /**
+     * This method permits to set the symbolic name of an agent.
+     * The passed parameter must be a local name.
+     */
+    public void setLocalName(String n) {
+        String hap = getPlatformID();
+        if (hap == null) {
+            throw new RuntimeException("Unknown Platform Name");
+        }
+        name = n.trim();
+        name = createGUID(name, hap);
+        hashCode = name.toLowerCase().hashCode();
+    }
+
     /**
      * Returns the HAP of the agent or null if the GUID of this
      * AID is not of the form @
@@ -554,10 +546,6 @@ public String getHap() {
             return name.substring(atPos + 1);
     }
 
-
-    // For persistence service
-    private transient Long persistentID;
-
     // For persistence service
     private Long getPersistentID() {
         return persistentID;
diff --git a/src/jade/core/Agent.java b/src/jade/core/Agent.java
index 0106cf9..b64039b 100644
--- a/src/jade/core/Agent.java
+++ b/src/jade/core/Agent.java
@@ -131,10 +131,12 @@ public class Agent implements Runnable, Serializable, TimerListener {
     @Serial
     private static final long serialVersionUID = 3487495895819000L;
     private final Logger log = Logger.getJADELogger(this.getClass().getName());
-    private transient AgentToolkit myToolkit;
+    //#MIDP_EXCLUDE_END
+    //E.ADAM map service name, service description
+    protected DFAgentDescription servicesList;
 
     //#MIDP_EXCLUDE_BEGIN
-
+    private transient AgentToolkit myToolkit;
     /**
      * These constants represent the various Domain Life Cycle states
      */
@@ -199,9 +201,6 @@ public class Agent implements Runnable, Serializable, TimerListener {
     private transient Hashtable helpersTable;
     // For persistence service -- Hibernate needs java.util collections
     private transient Set persistentPendingTimers = new HashSet<>();
-    //#MIDP_EXCLUDE_END
-    //E.ADAM map service name, service description
-    protected DFAgentDescription servicesList;
 
     /**
      * Default constructor.
@@ -1170,7 +1169,7 @@ public Object getO2AObject() {
 
             // If some thread issued a blocking putO2AObject() call with this
             // object, wake it up. cond.set is synchronized on CondVar object
-            cond =  o2aLocks.remove(result);
+            cond = o2aLocks.remove(result);
         }
 
         if (cond != null) {
@@ -1982,6 +1981,49 @@ private void setPendingTimers(Set timers) {
     }
     //#MIDP_EXCLUDE_END
 
+    /**
+     * add a service description into the agent description
+     *
+     * @param service description of the service
+     * @return the new agent description with this service
+     * @author Emmanuel Adam
+     * @since 2022
+     */
+    public DFAgentDescription addService(ServiceDescription service) {
+        if (servicesList == null) servicesList = new DFAgentDescription();
+        servicesList.addServices(service);
+        return servicesList;
+    }
+
+    /**
+     * @return collection of the service descriptions of the agent
+     * @author Emmanuel Adam
+     * @since 2022
+     */
+    public List getServices() {
+//        var l = new ArrayList();
+//        servicesList.getAllServices().forEachRemaining(l::add);
+        return servicesList.getAllServices();
+    }
+
+    /**
+     * @return the agent description
+     * @author Emmanuel Adam
+     * @since 2022
+     */
+    public DFAgentDescription getServicesList() {
+        return servicesList;
+    }
+
+    /**
+     * @return the agent description
+     * @author Emmanuel Adam
+     * @since 2022
+     */
+    public void setServicesList(DFAgentDescription servicesList) {
+        this.servicesList = servicesList;
+    }
+
     /**
      * Inner class Interrupted.
      * This class is used to handle change state requests that occur
@@ -2081,6 +2123,8 @@ public synchronized void set() {
 
     } // End of inner class CondVar
 
+    //#J2ME_EXCLUDE_END
+
     /**
      * Inner class AssociationTB.
      * This class manages bidirectional associations between Timer and
@@ -2329,52 +2373,4 @@ public boolean transitionTo(LifeCycle to) {
         }
     } // END of inner class SuspendedLifeCycle
 
-    //#J2ME_EXCLUDE_END
-
-    /**
-     * add a service description into the agent description
-     * @param service description of the service
-     * @return the new agent description with this service
-     * @author Emmanuel Adam
-     * @since 2022
-     * */
-    public DFAgentDescription addService(ServiceDescription service)
-    {
-        if(servicesList==null) servicesList = new DFAgentDescription();
-        servicesList.addServices(service);
-        return servicesList;
-    }
-
-    /**
-     * @return collection of the service descriptions of the agent
-     * @author Emmanuel Adam
-     * @since 2022
-     * */
-    public List getServices()
-    {
-//        var l = new ArrayList();
-//        servicesList.getAllServices().forEachRemaining(l::add);
-        return servicesList.getAllServices();
-    }
-
-    /**
-     * @return the agent description
-     * @author Emmanuel Adam
-     * @since 2022
-     * */
-    public void setServicesList(DFAgentDescription servicesList)
-    {
-        this.servicesList = servicesList;
-    }
-
-    /**
-     * @return the agent description
-     * @author Emmanuel Adam
-     * @since 2022
-     * */
-    public DFAgentDescription getServicesList()
-    {
-        return servicesList;
-    }
-
 }
diff --git a/src/jade/core/AgentContainerImpl.java b/src/jade/core/AgentContainerImpl.java
index 342e863..7b290f1 100644
--- a/src/jade/core/AgentContainerImpl.java
+++ b/src/jade/core/AgentContainerImpl.java
@@ -84,33 +84,24 @@ class AgentContainerImpl implements AgentContainer, AgentToolkit {
     // The agent platform this container belongs to
     protected MainContainerImpl myMainContainer; // FIXME: It should go away
     //#MIDP_EXCLUDE_END
-
+    // The IMTP manager, used to access IMTP-dependent functionalities
+    protected IMTPManager myIMTPManager;
+    //#J2ME_EXCLUDE_END
+    protected ContainerID myID;
+    protected NodeDescriptor myNodeDescriptor;
+    // These are only used at bootstrap-time to initialize the local
+    // NodeDescriptor. Further modifications take no effect
+    protected JADEPrincipal ownerPrincipal;
+    protected Credentials ownerCredentials;
     //#J2ME_EXCLUDE_BEGIN
     // The listener for multicast main detecton
     private MulticastMainDetectionListener mainDetectionListener;
-    //#J2ME_EXCLUDE_END
-
-    // The IMTP manager, used to access IMTP-dependent functionalities
-    protected IMTPManager myIMTPManager;
-
     // The platform Service Manager
     private ServiceManager myServiceManager;
-
     // The platform Service Finder
     private ServiceFinder myServiceFinder;
-
     // The Object managing Thread resources in this container
     private ResourceManager myResourceManager;
-
-    protected ContainerID myID;
-
-    protected NodeDescriptor myNodeDescriptor;
-
-    // These are only used at bootstrap-time to initialize the local
-    // NodeDescriptor. Further modifications take no effect
-    protected JADEPrincipal ownerPrincipal;
-    protected Credentials ownerCredentials;
-
     private AID theAMS;
     private AID theDefaultDF;
 
diff --git a/src/jade/core/AgentDescriptor.java b/src/jade/core/AgentDescriptor.java
index 617f759..83f9473 100644
--- a/src/jade/core/AgentDescriptor.java
+++ b/src/jade/core/AgentDescriptor.java
@@ -43,11 +43,9 @@ public class AgentDescriptor {
 
     public static final boolean NATIVE_AGENT = false;
     public static final boolean FOREIGN_AGENT = true;
-
-
-    private AMSAgentDescription description;
     //  private AgentProxy proxy;
     private final boolean foreign;
+    private AMSAgentDescription description;
     private ContainerID containerID;
     private JADEPrincipal principal;
     private Credentials amsDelegation;
@@ -61,15 +59,15 @@ public AgentDescriptor(boolean isForeign) {
         foreign = isForeign;
     }
 
+    public AMSAgentDescription getDescription() {
+        return description;
+    }
+
     // AMS description
     public void setDescription(AMSAgentDescription dsc) {
         description = dsc;
     }
 
-    public AMSAgentDescription getDescription() {
-        return description;
-    }
-
     // Is this agent a foreign agent?
     public boolean isForeign() {
         return foreign;
@@ -81,13 +79,17 @@ public boolean isNative() {
         return !foreign;
     }
 
+    public ContainerID getContainerID() {
+        return containerID;
+    }
+
     // Container ID
     public void setContainerID(ContainerID cid) {
         containerID = cid;
     }
 
-    public ContainerID getContainerID() {
-        return containerID;
+    public JADEPrincipal getPrincipal() {
+        return principal;
     }
 
     // Agent principal
@@ -95,8 +97,8 @@ public void setPrincipal(JADEPrincipal p) {
         principal = p;
     }
 
-    public JADEPrincipal getPrincipal() {
-        return principal;
+    public Credentials getAMSDelegation() {
+        return amsDelegation;
     }
 
     // AMS delegation
@@ -104,8 +106,4 @@ public void setAMSDelegation(Credentials cf) {
         amsDelegation = cf;
     }
 
-    public Credentials getAMSDelegation() {
-        return amsDelegation;
-    }
-
 }
diff --git a/src/jade/core/AgentManager.java b/src/jade/core/AgentManager.java
index b4dbc94..df3dbdc 100644
--- a/src/jade/core/AgentManager.java
+++ b/src/jade/core/AgentManager.java
@@ -47,14 +47,6 @@
  */
 public interface AgentManager {
 
-    /**
-     * This callback interface is implemented by the AMS in order to be
-     * notified of significant platform-level events (e.g. container
-     * added or removed, agents birth or death, mtp configuration changes, etc.).
-     */
-    interface Listener extends PlatformListener, MTPListener {
-    }
-
     // Listeners related methods
     void addListener(Listener l);
 
@@ -79,8 +71,6 @@ interface Listener extends PlatformListener, MTPListener {
 
     AMSAgentDescription getAMSDescription(AID agentID) throws NotFoundException;
 
-    // JADE actions method
-
     /**
      * Create an agent on the given container. If the container-name is null
      * then the agent is created on the main-container.
@@ -91,6 +81,8 @@ interface Listener extends PlatformListener, MTPListener {
      **/
     void create(String agentName, String className, Object[] arguments, ContainerID cid, JADEPrincipal owner, Credentials initialCredentials, JADEPrincipal requesterPrincipal, Credentials requesterCredentials) throws UnreachableException, JADESecurityException, NotFoundException, NameClashException;
 
+    // JADE actions method
+
     void kill(AID agentID, JADEPrincipal requesterPrincipal, Credentials requesterCredentials) throws NotFoundException, UnreachableException, JADESecurityException;
 
     void suspend(AID agentID) throws NotFoundException, UnreachableException, JADESecurityException;
@@ -131,5 +123,13 @@ interface Listener extends PlatformListener, MTPListener {
     void amsModify(AMSAgentDescription dsc) throws NotRegistered, NotFoundException, UnreachableException, JADESecurityException;
 
     List amsSearch(AMSAgentDescription template, long maxResults);
+
+    /**
+     * This callback interface is implemented by the AMS in order to be
+     * notified of significant platform-level events (e.g. container
+     * added or removed, agents birth or death, mtp configuration changes, etc.).
+     */
+    interface Listener extends PlatformListener, MTPListener {
+    }
 }
 
diff --git a/src/jade/core/AgentServicesTools.java b/src/jade/core/AgentServicesTools.java
index e4382ce..6d3142a 100644
--- a/src/jade/core/AgentServicesTools.java
+++ b/src/jade/core/AgentServicesTools.java
@@ -8,7 +8,6 @@
 
 import java.util.ArrayList;
 import java.util.Arrays;
-import java.util.Collection;
 
 /**
  * tools to help the use of the Directory Facilitator (registration to a
@@ -38,14 +37,14 @@ public static DFAgentDescription createAgentDescription(final String typeService
      * add a description of service to an agent description tof a given agent
* if the agent does'nt own a agent description, a new one is created * - * @param a the agent taht request the addition of a service to its agent description + * @param a the agent taht request the addition of a service to its agent description * @param typeService type of the service * @param nameService name of the service (can be null) * @return the model of the service */ public static DFAgentDescription getAgentDescription(final Agent a, final String typeService, final String nameService) { var model = a.getServicesList(); - if (model==null) model = new DFAgentDescription(); + if (model == null) model = new DFAgentDescription(); var service = new ServiceDescription(); service.setType(typeService); service.setName(nameService); @@ -54,12 +53,13 @@ public static DFAgentDescription getAgentDescription(final Agent a, final String } - /**@return the AID relative to the topic topicName for manage 'radio', broadcast message - * @param agent the agent that create or retrieve the topic - * @param topicName the topic name*/ - public static AID generateTopicAID(Agent agent, String topicName) - { - AID topic=null; + /** + * @param agent the agent that create or retrieve the topic + * @param topicName the topic name + * @return the AID relative to the topic topicName for manage 'radio', broadcast message + */ + public static AID generateTopicAID(Agent agent, String topicName) { + AID topic = null; TopicManagementHelper topicHelper; try { topicHelper = (TopicManagementHelper) agent.getHelper(TopicManagementHelper.SERVICE_NAME); @@ -75,26 +75,31 @@ public static AID generateTopicAID(Agent agent, String topicName) /** * deregister an agent from a service with the Directory Facilitator * - * @param myAgent agent that have to be registered - * @param model description of the service to deregister for this agent + * @param myAgent agent that have to be registered + * @param model description of the service to deregister for this agent */ public synchronized static void deregisterService(final Agent myAgent, final DFAgentDescription model) { - if(model!=null){ - try { DFService.deregister(myAgent, model); } - catch (FIPAException fe) { fe.printStackTrace();} + if (model != null) { + try { + DFService.deregister(myAgent, model); + } catch (FIPAException fe) { + fe.printStackTrace(); + } } } - /** * deregister an agent from all its services with the Directory Facilitator * - * @param myAgent agent that have to be registered + * @param myAgent agent that have to be registered */ public synchronized static void deregisterAll(final Agent myAgent) { - try { DFService.deregister(myAgent); } - catch (FIPAException fe) { fe.printStackTrace();} + try { + DFService.deregister(myAgent); + } catch (FIPAException fe) { + fe.printStackTrace(); + } } /** @@ -106,12 +111,12 @@ public synchronized static void deregisterAll(final Agent myAgent) { * name (like the agent name) */ public synchronized static DFAgentDescription register(final Agent myAgent, final String typeService, final String nameService) { - boolean first = (myAgent.getServicesList()==null); + boolean first = (myAgent.getServicesList() == null); var model = getAgentDescription(myAgent, typeService, nameService); myAgent.setServicesList(model); try { - if(first) DFService.register(myAgent, model); - else DFService.modify(myAgent, model); + if (first) DFService.register(myAgent, model); + else DFService.modify(myAgent, model); } catch (FIPAException fe) { fe.printStackTrace(); } diff --git a/src/jade/core/AgentState.java b/src/jade/core/AgentState.java index 6699304..12416cb 100644 --- a/src/jade/core/AgentState.java +++ b/src/jade/core/AgentState.java @@ -33,6 +33,45 @@ */ public class AgentState { + private static final AgentState[] STATES = new AgentState[]{ + new AgentState("Illegal MIN state", Agent.AP_MIN), + new AgentState("Initiated", Agent.AP_INITIATED), + new AgentState("Active", Agent.AP_ACTIVE), + new AgentState("Idle", Agent.AP_IDLE), + new AgentState("Suspended", Agent.AP_SUSPENDED), + new AgentState("Waiting", Agent.AP_WAITING), + new AgentState("Deleted", Agent.AP_DELETED), + //#MIDP_EXCLUDE_BEGIN + new AgentState("Transit", jade.core.mobility.AgentMobilityService.AP_TRANSIT), + new AgentState("Copy", jade.core.mobility.AgentMobilityService.AP_COPY), + new AgentState("Gone", jade.core.mobility.AgentMobilityService.AP_GONE), + // FIXME: We can't use the constants since they are defined in the Persistence add-on + new AgentState("Saving", 10), + new AgentState("Loading", 11), + new AgentState("Frozen", 12), + //#MIDP_EXCLUDE_END + new AgentState("Illegal MAX state", Agent.AP_MAX) + }; + // For persistence service + private Long persistentID; + private String name; + private int value; + + /** + * Default constructor. A default constructor is necessary for + * this class because it is used in the + * jade-introspection ontology. Application code + * should use the static access method getInstance(), + * however. + */ + public AgentState() { + } + + private AgentState(String n, int v) { + name = n; + value = v; + } + /** * Static access method to retrieve a prototype object for an * agent life-cycle state. @@ -62,19 +101,12 @@ public static AgentState[] getAllInstances() { } /** - * Default constructor. A default constructor is necessary for - * this class because it is used in the - * jade-introspection ontology. Application code - * should use the static access method getInstance(), - * however. + * Retrieve the name of this state. + * + * @return The state name. */ - public AgentState() { - } - - - private AgentState(String n, int v) { - name = n; - value = v; + public String getName() { + return name; } /** @@ -87,12 +119,14 @@ public void setName(String n) { } /** - * Retrieve the name of this state. + * Retrieve the numeric value of this state, in agreement with the + * AP_XXX constants defined in the Agent + * class. * - * @return The state name. + * @return The numeric value set for this state. */ - public String getName() { - return name; + public int getValue() { + return value; } /** @@ -106,17 +140,6 @@ public void setValue(int v) { value = v; } - /** - * Retrieve the numeric value of this state, in agreement with the - * AP_XXX constants defined in the Agent - * class. - * - * @return The numeric value set for this state. - */ - public int getValue() { - return value; - } - /** * Equality operations between agent states. The equality * operation is defined as equality by state name (case @@ -176,29 +199,6 @@ public int hashCode() { return name.toLowerCase().hashCode(); } - private static final AgentState[] STATES = new AgentState[]{ - new AgentState("Illegal MIN state", Agent.AP_MIN), - new AgentState("Initiated", Agent.AP_INITIATED), - new AgentState("Active", Agent.AP_ACTIVE), - new AgentState("Idle", Agent.AP_IDLE), - new AgentState("Suspended", Agent.AP_SUSPENDED), - new AgentState("Waiting", Agent.AP_WAITING), - new AgentState("Deleted", Agent.AP_DELETED), - //#MIDP_EXCLUDE_BEGIN - new AgentState("Transit", jade.core.mobility.AgentMobilityService.AP_TRANSIT), - new AgentState("Copy", jade.core.mobility.AgentMobilityService.AP_COPY), - new AgentState("Gone", jade.core.mobility.AgentMobilityService.AP_GONE), - // FIXME: We can't use the constants since they are defined in the Persistence add-on - new AgentState("Saving", 10), - new AgentState("Loading", 11), - new AgentState("Frozen", 12), - //#MIDP_EXCLUDE_END - new AgentState("Illegal MAX state", Agent.AP_MAX) - }; - - // For persistence service - private Long persistentID; - // For persistence service private Long getPersistentID() { return persistentID; @@ -209,8 +209,5 @@ private void setPersistentID(Long l) { persistentID = l; } - private String name; - private int value; - } diff --git a/src/jade/core/BackEndContainer.java b/src/jade/core/BackEndContainer.java index f16a509..6e239ca 100644 --- a/src/jade/core/BackEndContainer.java +++ b/src/jade/core/BackEndContainer.java @@ -50,30 +50,35 @@ public class BackEndContainer extends AgentContainerImpl implements BackEnd { private static final String ADDR_LIST_DELIMITERS = ", \n\t\r"; - + // The manager of the connection with the FrontEnd + private final BEConnectionManager myConnectionManager; + private final Map agentImages = new HashMap<>(1); + private final Map principals = new HashMap<>(1); + // The original properties passed to this container when it was created + private final Properties creationProperties; + private final Logger myLogger = Logger.getMyLogger(getClass().getName()); + private final Object frontEndSynchLock = new Object(); + private final ArrayList fronEndSynchBuffer = new ArrayList<>(); // This flag is used to prevent two parallel shut-down processes and // also to be sure that threads possibly started by this BEContainer // do not survive after the BEContainer shutdown. private boolean terminating = false; - // The FrontEnd this BackEndContainer is connected to private FrontEnd myFrontEnd; - - // The manager of the connection with the FrontEnd - private final BEConnectionManager myConnectionManager; - private BackEndManager theBEManager; - - private final Map agentImages = new HashMap<>(1); - private Map serviceBECodecs = null; // Lazy initialization + // Flag indicating that the front-end synchronization process is in place + private boolean synchronizing = false; - private final Map principals = new HashMap<>(1); - // The original properties passed to this container when it was created - private final Properties creationProperties; + public BackEndContainer(Properties props, BEConnectionManager cm) throws ProfileException { + // Do not call the parent constructor to avoid creating a big LADT + myProfile = new ProfileImpl(adjustProperties(props)); + localAgents = new LADT(1); - private final Logger myLogger = Logger.getMyLogger(getClass().getName()); + creationProperties = props; + myConnectionManager = cm; + } private static Properties adjustProperties(Properties pp) { // A BackEndContainer is never a Main @@ -106,14 +111,9 @@ private static Properties adjustProperties(Properties pp) { return pp; } - public BackEndContainer(Properties props, BEConnectionManager cm) throws ProfileException { - // Do not call the parent constructor to avoid creating a big LADT - myProfile = new ProfileImpl(adjustProperties(props)); - localAgents = new LADT(1); - - creationProperties = props; - myConnectionManager = cm; - } + ///////////////////////////////////// + // BackEnd interface implementation + ///////////////////////////////////// public boolean connect() { try { @@ -173,7 +173,6 @@ public boolean connect() { } } - protected void startNode() throws IMTPException, ProfileException, ServiceException, JADESecurityException, NotFoundException { // Initialize all services (without activating them) List services = new ArrayList<>(); @@ -210,10 +209,6 @@ void initMandatoryServices(List services) throws ServiceExcep services.add(dsc); } - ///////////////////////////////////// - // BackEnd interface implementation - ///////////////////////////////////// - /** * A new agent has just started on the FrontEnd. * Adjust the agent name taking into account wild-cards. @@ -380,6 +375,11 @@ public void createAgentOnFE(String name, String className, String[] args) throws myFrontEnd.createAgent(name, className, args); } + + ///////////////////////////////////////////////////// + // Redefined methods of the AgentContainer interface + ///////////////////////////////////////////////////// + public void killAgentOnFE(String name) throws IMTPException, NotFoundException { try { myFrontEnd.killAgent(name); @@ -407,11 +407,6 @@ public void resumeAgentOnFE(String name) throws IMTPException, NotFoundException } } - - ///////////////////////////////////////////////////// - // Redefined methods of the AgentContainer interface - ///////////////////////////////////////////////////// - /** * Dispatch a message to an agent in the FrontEnd. * If this method is called by a thread that is serving a message @@ -572,7 +567,6 @@ private void killAgentImages() { } } - private String[] parseAddressList(String toParse) { StringTokenizer lexer = new StringTokenizer(toParse, ADDR_LIST_DELIMITERS); @@ -602,17 +596,6 @@ private BackEndManager initBEManager() { return null; } - - /** - * Inner class AgentImage - */ - public class AgentImage extends Agent { - private AgentImage(AID id) { - super(id); - setToolkit(BackEndContainer.this); - } - } - // Factory method for the inner class public AgentImage createAgentImage(AID id) { return new AgentImage(id); @@ -634,6 +617,22 @@ public AgentImage getAgentImage(AID id) { return agentImages.get(id); } + + //////////////////////////////////////////////////////////// + // Methods and variables related to the front-end synchronization + // mechanism that allows a FrontEnd to re-join the platform after + // his BackEnd got lost (e.g. because of a crash of the hosting + // container). + // + // - The BackEnd waits for the input connection to be ready + // and then asks the FrontEnd to synchronize. + // - In the meanwhile some messages could arrive from the + // FrontEnd and the sender may not have an image in the BackEnd + // yet --> + // - While synchronizing outgoing messages are bufferd and + // actually sent as soon as the synchronization process completes + //////////////////////////////////////////////////////////// + public AID[] getAgentImages() { Object[] objs = agentImages.keySet().toArray(); AID[] result = new AID[objs.length]; @@ -644,7 +643,6 @@ public AID[] getAgentImages() { return result; } - public List removePendingMessages(MessageTemplate template, boolean notifyFailure) { List pendingMsg = ((jade.imtp.leap.FrontEndStub) myFrontEnd).removePendingMessages(template); if (pendingMsg.size() > 0) { @@ -668,27 +666,6 @@ public List removePendingMessages(MessageTemplate template, boolean no return pendingMsg; } - - //////////////////////////////////////////////////////////// - // Methods and variables related to the front-end synchronization - // mechanism that allows a FrontEnd to re-join the platform after - // his BackEnd got lost (e.g. because of a crash of the hosting - // container). - // - // - The BackEnd waits for the input connection to be ready - // and then asks the FrontEnd to synchronize. - // - In the meanwhile some messages could arrive from the - // FrontEnd and the sender may not have an image in the BackEnd - // yet --> - // - While synchronizing outgoing messages are bufferd and - // actually sent as soon as the synchronization process completes - //////////////////////////////////////////////////////////// - - // Flag indicating that the front-end synchronization process is in place - private boolean synchronizing = false; - private final Object frontEndSynchLock = new Object(); - private final ArrayList fronEndSynchBuffer = new ArrayList<>(); - /** * Start the front-end synchronization process. * NOTE that when this method is called it may not be possible @@ -753,6 +730,16 @@ private void notifySynchronized() { } } + /** + * Inner class AgentImage + */ + public class AgentImage extends Agent { + private AgentImage(AID id) { + super(id); + setToolkit(BackEndContainer.this); + } + } + /** * Inner class MessageSenderPair */ diff --git a/src/jade/core/BackEndManager.java b/src/jade/core/BackEndManager.java index 8dd8fe3..ca17843 100644 --- a/src/jade/core/BackEndManager.java +++ b/src/jade/core/BackEndManager.java @@ -37,25 +37,13 @@ public class BackEndManager { // The singleton BackEndManager private static BackEndManager theInstance; - - - // The IMTP manager, used to access IMTP-dependent functionalities - protected IMTPManager myIMTPManager; - // The node acting as parent private final Node myNode; - // The child nodes private final Map children = new HashMap<>(); - private final Logger myLogger = Logger.getMyLogger(getClass().getName()); - - public static BackEndManager getInstance(Profile p) throws ProfileException { - if (theInstance == null) { - theInstance = new BackEndManager(p); - } - return theInstance; - } + // The IMTP manager, used to access IMTP-dependent functionalities + protected IMTPManager myIMTPManager; private BackEndManager(Profile p) throws ProfileException { if (p != null) { @@ -70,6 +58,12 @@ private BackEndManager(Profile p) throws ProfileException { } } + public static BackEndManager getInstance(Profile p) throws ProfileException { + if (theInstance == null) { + theInstance = new BackEndManager(p); + } + return theInstance; + } public Node getNode() { return myNode; diff --git a/src/jade/core/BaseNode.java b/src/jade/core/BaseNode.java index 153cb64..80140e0 100644 --- a/src/jade/core/BaseNode.java +++ b/src/jade/core/BaseNode.java @@ -41,6 +41,16 @@ public abstract class BaseNode implements Node, Serializable { private final transient Logger myLogger; + // A map, indexed by service name, of all the local slices of this + // node. This map is used to dispatch incoming commands to the + // service they belong to. + private final transient Map localSlices; + protected transient ServiceManager myServiceManager; + private transient CommandProcessor processor; + // The name of this node + private String myName; + // True if a local copy of the Platform Manager is deployed at this Node + private boolean hasLocalPM = false; public BaseNode(String name, boolean hasPM) { myName = name; @@ -49,14 +59,14 @@ public BaseNode(String name, boolean hasPM) { myLogger = Logger.getMyLogger(getClass().getName()); } - public void setName(String name) { - myName = name; - } - public String getName() { return myName; } + public void setName(String name) { + myName = name; + } + public boolean hasPlatformManager() { return hasLocalPM; } @@ -73,7 +83,6 @@ protected Slice getSlice(String serviceName) { return localSlices.get(serviceName); } - /** * Provides an IMTP independent implementation for the * horizontal command serving mechanism. IMTP dependent implementations @@ -162,20 +171,6 @@ private Object serveVerticalCommand(VerticalCommand cmd) throws ServiceException return processor.processIncoming(cmd); } - protected transient ServiceManager myServiceManager; - private transient CommandProcessor processor; - - // The name of this node - private String myName; - - // True if a local copy of the Platform Manager is deployed at this Node - private boolean hasLocalPM = false; - - // A map, indexed by service name, of all the local slices of this - // node. This map is used to dispatch incoming commands to the - // service they belong to. - private final transient Map localSlices; - public String toString() { return myName; } diff --git a/src/jade/core/BehaviourID.java b/src/jade/core/BehaviourID.java index 360cbef..15169d1 100644 --- a/src/jade/core/BehaviourID.java +++ b/src/jade/core/BehaviourID.java @@ -39,11 +39,11 @@ */ public class BehaviourID implements Concept { + private final ArrayList children = new ArrayList<>(); private int code; private String name; private String className; private String kind; - private final ArrayList children = new ArrayList<>(); /** * Default constructor. Builds an unspecified behaviour ID. @@ -67,10 +67,9 @@ public BehaviourID(Behaviour b) { // If we have a composite behaviour, add the // children to this behaviour id. - if (b instanceof CompositeBehaviour) { - CompositeBehaviour c = (CompositeBehaviour) b; - for (Object o : c.getChildren()) { - addChildren(new BehaviourID((Behaviour) o)); + if (b instanceof CompositeBehaviour c) { + for (Behaviour o : c.getChildren()) { + addChildren(new BehaviourID(o)); } } } @@ -97,15 +96,6 @@ private String getClassKind(Class c) { } } - /** - * Set the name of this behaviour ID - * - * @param n The name to give to this behaviour ID. - */ - public void setName(String n) { - name = n; - } - /** * Retrieve the name of this behaviour ID. * @@ -116,12 +106,12 @@ public String getName() { } /** - * Set the code of this behaviour ID + * Set the name of this behaviour ID * - * @param code The code to give to this behaviour ID. + * @param n The name to give to this behaviour ID. */ - public void setCode(int code) { - this.code = code; + public void setName(String n) { + name = n; } /** @@ -132,13 +122,12 @@ public int getCode() { } /** - * Set the class name for this behaviour ID. This is the name of - * the Java class implementing the described agent behaviour. + * Set the code of this behaviour ID * - * @param n The class name of the described behaviour. + * @param code The code to give to this behaviour ID. */ - public void setClassName(String n) { - className = n; + public void setCode(int code) { + this.code = code; } /** @@ -153,13 +142,13 @@ public String getClassName() { } /** - * Set the kind of behaviour described by this behaviour ID. + * Set the class name for this behaviour ID. This is the name of + * the Java class implementing the described agent behaviour. * - * @param k A string specifying the kind of the described - * behaviour. + * @param n The class name of the described behaviour. */ - public void setKind(String k) { - kind = k; + public void setClassName(String n) { + className = n; } /** @@ -172,6 +161,16 @@ public String getKind() { return kind; } + /** + * Set the kind of behaviour described by this behaviour ID. + * + * @param k A string specifying the kind of the described + * behaviour. + */ + public void setKind(String k) { + kind = k; + } + /** * Adds a new behaviour ID as a child of this one. The * parent-child relationship between behaviour IDs reflects the @@ -216,8 +215,7 @@ public boolean isSimple() { * true. Otherwise, false is returned. */ public boolean equals(Object o) { - if (o != null && o instanceof BehaviourID) { - BehaviourID b = (BehaviourID) o; + if (o instanceof BehaviourID b) { return (checkEquals(name, b.name) && checkEquals(className, b.className) && checkEquals(kind, b.kind)); } else { return false; diff --git a/src/jade/core/CaseInsensitiveString.java b/src/jade/core/CaseInsensitiveString.java index 6154695..d8316d0 100644 --- a/src/jade/core/CaseInsensitiveString.java +++ b/src/jade/core/CaseInsensitiveString.java @@ -60,6 +60,23 @@ public CaseInsensitiveString(String name) { hashCode = (s == null ? 0 : s.toLowerCase().hashCode()); } + /** + * Static method for case insensitive string comparasion. + * For comparasion used the regionMatches approach which + * doesn't allocate any additional memory. + * + * @param s1, s2 The String objects to compare + * @return true if the strings are equal, apart from case. + */ + public static final boolean equalsIgnoreCase(String s1, String s2) { + if (s1 == null || s2 == null) { + return false; + } else { + return ((s1.length() == s2.length()) + && s1.regionMatches(true, 0, s2, 0, s1.length())); + } + } + /** * Converts the CaseInsensitiveString object into a * string. @@ -105,22 +122,5 @@ public final int hashCode() { return hashCode; } - /** - * Static method for case insensitive string comparasion. - * For comparasion used the regionMatches approach which - * doesn't allocate any additional memory. - * - * @param s1, s2 The String objects to compare - * @return true if the strings are equal, apart from case. - */ - public static final boolean equalsIgnoreCase(String s1, String s2) { - if (s1 == null || s2 == null) { - return false; - } else { - return ((s1.length() == s2.length()) - && s1.regionMatches(true, 0, s2, 0, s1.length())); - } - } - } diff --git a/src/jade/core/Channel.java b/src/jade/core/Channel.java index b5c3a55..4012796 100644 --- a/src/jade/core/Channel.java +++ b/src/jade/core/Channel.java @@ -45,28 +45,28 @@ public Channel(String n, String p, String a) { address = a; } - public void setName(String n) { - name = n; - } - public String getName() { return name; } - public void setProtocol(String p) { - protocol = p; + public void setName(String n) { + name = n; } public String getProtocol() { return protocol; } - public void setAddress(String a) { - address = a; + public void setProtocol(String p) { + protocol = p; } public String getAddress() { return address; } + public void setAddress(String a) { + address = a; + } + } diff --git a/src/jade/core/Command.java b/src/jade/core/Command.java index 6ec834e..2ac29fe 100644 --- a/src/jade/core/Command.java +++ b/src/jade/core/Command.java @@ -60,14 +60,6 @@ public interface Command { */ Object[] getParams(); - /** - * Assign a return value to this command, so that the original - * command issuer can retrieve it. - * - * @param rv The desired return value for this command object. - */ - void setReturnValue(Object rv); - /** * Obtain the return value for this command. * @@ -76,6 +68,14 @@ public interface Command { */ Object getReturnValue(); + /** + * Assign a return value to this command, so that the original + * command issuer can retrieve it. + * + * @param rv The desired return value for this command object. + */ + void setReturnValue(Object rv); + /** * Get the JADEPrincipal of the actor, respnsible for this Command object. * diff --git a/src/jade/core/CommandProcessor.java b/src/jade/core/CommandProcessor.java index ce856dc..8600b26 100644 --- a/src/jade/core/CommandProcessor.java +++ b/src/jade/core/CommandProcessor.java @@ -38,13 +38,12 @@ * @author Giovanni Caire - TILAB */ class CommandProcessor { - private Filter firstDownFilter; - private Filter firstUpFilter; - private final Hashtable downSinks; private final Hashtable upSinks; private final SinksFilter lastDownFilter; private final SinksFilter lastUpFilter; + private Filter firstDownFilter; + private Filter firstUpFilter; public CommandProcessor() { diff --git a/src/jade/core/ContainerID.java b/src/jade/core/ContainerID.java index 4418d6e..0ed1c95 100644 --- a/src/jade/core/ContainerID.java +++ b/src/jade/core/ContainerID.java @@ -71,15 +71,6 @@ public ContainerID(String n, TransportAddress a) { } } - /** - * Set the name of the described container. - * - * @param n The name to give to the described container. - */ - public void setName(String n) { - name = n; - } - /** * Retrieve the name of the described container. * @@ -91,13 +82,12 @@ public String getName() { } /** - * Set the IMTP protocol used to reach the described - * container. + * Set the name of the described container. * - * @param p The name of the chosen IMTP protocol. + * @param n The name to give to the described container. */ - public void setProtocol(String p) { - protocol = p; + public void setName(String n) { + name = n; } /** @@ -110,12 +100,13 @@ public String getProtocol() { } /** - * Set the IP address (as a string) of the host, the described container is running on. + * Set the IMTP protocol used to reach the described + * container. * - * @param a The string representation of the IP address of the host, the described container is running on. + * @param p The name of the chosen IMTP protocol. */ - public void setAddress(String a) { - address = a; + public void setProtocol(String p) { + protocol = p; } /** @@ -127,6 +118,15 @@ public String getAddress() { return address; } + /** + * Set the IP address (as a string) of the host, the described container is running on. + * + * @param a The string representation of the IP address of the host, the described container is running on. + */ + public void setAddress(String a) { + address = a; + } + public String getPort() { return port; } @@ -188,13 +188,13 @@ public int hashCode() { return name.toLowerCase().hashCode(); } + public Boolean getMain() { + return main; + } + public void setMain(Boolean main) { this.main = main; } - public Boolean getMain() { - return main; - } - } diff --git a/src/jade/core/ContainerTable.java b/src/jade/core/ContainerTable.java index bbeafc9..45b13b7 100644 --- a/src/jade/core/ContainerTable.java +++ b/src/jade/core/ContainerTable.java @@ -34,28 +34,6 @@ class ContainerTable { private static final int CONTAINERS_SIZE = 10; private final Logger myLogger = Logger.getMyLogger(getClass().getName()); - - private static class Entry { - private final List mtps = new LinkedList<>(); - - public Entry() { - } - - public void addMTP(MTPDescriptor mtp) { - mtps.add(mtp); - } - - public void removeMTP(MTPDescriptor mtp) { - mtps.remove(mtp); - } - - public List getMTPs() { - return mtps; - } - - } // End of Entry class - - private final Map entries = new HashMap<>(CONTAINERS_SIZE); public synchronized void addContainer(ContainerID cid) { @@ -141,4 +119,24 @@ synchronized boolean waitUntilEmpty(long timeout) { return entries.isEmpty(); } + private static class Entry { + private final List mtps = new LinkedList<>(); + + public Entry() { + } + + public void addMTP(MTPDescriptor mtp) { + mtps.add(mtp); + } + + public void removeMTP(MTPDescriptor mtp) { + mtps.remove(mtp); + } + + public List getMTPs() { + return mtps; + } + + } // End of Entry class + } diff --git a/src/jade/core/Filter.java b/src/jade/core/Filter.java index ef5ad96..d18fc41 100644 --- a/src/jade/core/Filter.java +++ b/src/jade/core/Filter.java @@ -62,19 +62,15 @@ public abstract class Filter { * A constant indicating a filter for outgoing commands */ public static final boolean OUTGOING = true; - + // The preferred position in the filter chain. Package scoped since + // it can be directly accessed by the CommandProcessor + int preferredPosition = LAST - 10; private boolean blocking = false; private boolean skipping = false; - // The next filter in the filter chain private Filter next; - private String myServiceName; - // The preferred position in the filter chain. Package scoped since - // it can be directly accessed by the CommandProcessor - int preferredPosition = LAST - 10; - /** * Receive a command object for processing. * @@ -137,17 +133,6 @@ public final void setPreferredPosition(int pos) { } } - /** - * Sets the blocking state of this filter. A blocked filter does - * not process commands, and also prevents subsequent filters to - * process them. - * - * @param newState The boolean value to set the blocking state to. - */ - public void setBlocking(boolean newState) { - blocking = newState; - } - /** * Inquires the blocking state of this filter. A blocked fliter * does not process commands, and also prevents subsequent filters @@ -160,14 +145,14 @@ public boolean isBlocking() { } /** - * Sets the skipping state of this filter. A skipped filter does - * not process commands, but passes them directly to subsequent - * filters. + * Sets the blocking state of this filter. A blocked filter does + * not process commands, and also prevents subsequent filters to + * process them. * - * @param newState The boolean value to set the skipping state to. + * @param newState The boolean value to set the blocking state to. */ - public void setSkipping(boolean newState) { - skipping = newState; + public void setBlocking(boolean newState) { + blocking = newState; } /** @@ -181,6 +166,17 @@ public boolean isSkipping() { return skipping; } + /** + * Sets the skipping state of this filter. A skipped filter does + * not process commands, but passes them directly to subsequent + * filters. + * + * @param newState The boolean value to set the skipping state to. + */ + public void setSkipping(boolean newState) { + skipping = newState; + } + //////////////////////////////////////////////////// // These methods are called by the CommandProcessor // and ServiceManager when installing the filter @@ -189,11 +185,11 @@ final void setServiceName(String s) { myServiceName = s; } - final void setNext(Filter f) { - next = f; - } - final Filter getNext() { return next; } + + final void setNext(Filter f) { + next = f; + } } diff --git a/src/jade/core/FrontEndContainer.java b/src/jade/core/FrontEndContainer.java index 84dd686..4680394 100644 --- a/src/jade/core/FrontEndContainer.java +++ b/src/jade/core/FrontEndContainer.java @@ -44,27 +44,21 @@ */ class FrontEndContainer implements FrontEnd, AgentToolkit, Runnable { - Logger logger = Logger.getMyLogger(this.getClass().getName()); - // The table of local agents private final Hashtable localAgents = new Hashtable<>(1); // Maps local agent names containing wildcards with their actual names private final Hashtable actualNames = new Hashtable<>(1); - // The table of locally installed services private final Hashtable localServices = new Hashtable<>(1); - //#MIDP_EXCLUDE_BEGIN // The list of FELister private final Vector feListeners = new Vector<>(); + Logger logger = Logger.getMyLogger(this.getClass().getName()); //#MIDP_EXCLUDE_END - - // The ID of this container - private ContainerID myId; - // The addresses of the platform this container belongs to Vector platformAddresses; - + // The ID of this container + private ContainerID myId; // The AID of the AMS private AID amsAID; diff --git a/src/jade/core/FullResourceManager.java b/src/jade/core/FullResourceManager.java index c71fbca..df61394 100644 --- a/src/jade/core/FullResourceManager.java +++ b/src/jade/core/FullResourceManager.java @@ -28,8 +28,8 @@ class FullResourceManager implements ResourceManager { public static final String DISABLE_THREAD_GROUP_INTERRUPT = "jade_core_FullResourceManager_disablethreadgroupinterrupt"; - private static final boolean DEFAULT_DISABLE_THREAD_GROUP_INTERRUPT = false; public static final String THREAD_GROUP_INTERRUPT_TIMEOUT = "jade_core_FullResourceManager_threadgroupinterrupttimeout"; + private static final boolean DEFAULT_DISABLE_THREAD_GROUP_INTERRUPT = false; private static final String DEFAULT_THREAD_GROUP_INTERRUPT_TIMEOUT = "5000"; private static final String USER_AGENTS_GROUP_NAME = "JADE User Agents"; diff --git a/src/jade/core/GenericCommand.java b/src/jade/core/GenericCommand.java index 24da4c8..7bc3dc1 100644 --- a/src/jade/core/GenericCommand.java +++ b/src/jade/core/GenericCommand.java @@ -39,6 +39,14 @@ */ public class GenericCommand implements HorizontalCommand, VerticalCommand { + private final String myName; + private final String myService; + private final String myInteraction; + private final List params; + private jade.security.JADEPrincipal principal = null; + private jade.security.Credentials creds; + private Object returnValue; + /** * Creates a new generic command, with the given name and * belonging to the given service and interaction. @@ -55,7 +63,6 @@ public GenericCommand(String name, String service, String interaction) { params = new LinkedList<>(); } - public String getName() { return myName; } @@ -93,10 +100,6 @@ public void clear() { params.clear(); } - public void setReturnValue(Object rv) { - returnValue = rv; - } - public final Object getParam(int index) { return params.get(index); } @@ -109,6 +112,10 @@ public Object getReturnValue() { return returnValue; } + public void setReturnValue(Object rv) { + returnValue = rv; + } + public jade.security.JADEPrincipal getPrincipal() { return principal; } // end getPrincipal @@ -133,15 +140,4 @@ public void setCredentials(jade.security.Credentials creds) { } } // end setCredentials - - private jade.security.JADEPrincipal principal = null; - private jade.security.Credentials creds; - - private final String myName; - private final String myService; - private final String myInteraction; - - private final List params; - private Object returnValue; - } diff --git a/src/jade/core/InternalMessageQueue.java b/src/jade/core/InternalMessageQueue.java index cbb8f6f..0c4cfae 100644 --- a/src/jade/core/InternalMessageQueue.java +++ b/src/jade/core/InternalMessageQueue.java @@ -44,10 +44,11 @@ class InternalMessageQueue implements MessageQueue { /*#MIDP_INCLUDE_BEGIN private Vector list; #MIDP_INCLUDE_END*/ - - private int maxSize; private final Agent myAgent; private final Logger myLogger = Logger.getJADELogger(getClass().getName()); + private int maxSize; + // For persistence service + private Long persistentID; public InternalMessageQueue(int size, Agent a) { maxSize = size; @@ -68,16 +69,16 @@ public boolean isEmpty() { return list.isEmpty(); } + public int getMaxSize() { + return maxSize; + } + public void setMaxSize(int newSize) throws IllegalArgumentException { if (newSize < 0) throw new IllegalArgumentException("Invalid MsgQueue size"); maxSize = newSize; } - public int getMaxSize() { - return maxSize; - } - /** * @return the number of messages * currently in the queue @@ -110,7 +111,7 @@ public void addLast(ACLMessage msg) { //#MIDP_EXCLUDE_END /*#MIDP_INCLUDE_BEGIN list.removeElementAt(0); - } + } list.addElement(msg); #MIDP_INCLUDE_END*/ } @@ -149,13 +150,6 @@ private Iterator iterator() { #MIDP_INCLUDE_END*/ } - //#J2ME_EXCLUDE_BEGIN - // For persistence service - private void setMessages(List l) { - // FIXME: To be implemented - System.out.println(">>> MessageQueue::setMessages() <<<"); - } - // For persistence service private List getMessages() { // FIXME: To be implemented @@ -164,9 +158,12 @@ private List getMessages() { } //#J2ME_EXCLUDE_END - + //#J2ME_EXCLUDE_BEGIN // For persistence service - private Long persistentID; + private void setMessages(List l) { + // FIXME: To be implemented + System.out.println(">>> MessageQueue::setMessages() <<<"); + } // For persistence service private Long getPersistentID() { diff --git a/src/jade/core/LADT.java b/src/jade/core/LADT.java index a1a441f..8178035 100644 --- a/src/jade/core/LADT.java +++ b/src/jade/core/LADT.java @@ -35,85 +35,8 @@ */ class LADT { - // Rows of the LADT are protected by a recursive mutex lock - private static class Row { - private Agent value; - // DEBUG private Agent bakValue; - // DEBUG private String target = "ma"; - private Thread owner; - private long depth; - - public Row(Agent a) { - value = a; - // DEBUG bakValue = value; - depth = 0; - } - - public synchronized Agent get() { - return value; - } - - public synchronized void clear() { - value = null; - } - - public synchronized void lock() { - if (value != null) { - try { - Thread me = Thread.currentThread(); - while ((owner != null) && (owner != me)) { - // DEBUG boolean b = false; - // DEBUG if (bakValue.getLocalName().equals(target)) { - // DEBUG System.out.println("Thread "+Thread.currentThread().getName()+" start waiting on "+target); - // DEBUG b = true; - // DEBUG } - wait(); - // DEBUG if (b) { - // DEBUG System.out.println("Thread "+Thread.currentThread().getName()+" stop waiting on "+target); - // DEBUG } - if (value == null) { - return; - } - } - - owner = me; - ++depth; - } catch (InterruptedException ie) { - return; - } - } - } - - public synchronized void unlock() { - // Must be owner to unlock - if (owner != Thread.currentThread()) - return; - --depth; - if (depth == 0 || value == null) { - // Note that if the row has just been cleared we must wake up - // hanging threads even if depth is > 0, otherwise they will - // hang forever - owner = null; - // DEBUG try { - // DEBUG if (bakValue.getLocalName().equals(target)) { - // DEBUG System.out.println("Thread "+Thread.currentThread().getName()+" notifying all on "+target); - // DEBUG } - // DEBUG } - // DEBUG catch (Exception e) {} - notifyAll(); - } - } - - // For debugging purpose - public String toString() { - if (value != null) { - return "(" + value.getName() + " :owner " + (owner != null ? owner.toString() : "null") + ")"; - } else { - return "null"; - } - } - - } // End of Row class + //private Map agents = new HashMap(MAP_SIZE, MAP_LOAD_FACTOR); + private final Map agents; // Initial size of agent hash table @@ -123,9 +46,6 @@ public String toString() { //private static final float MAP_LOAD_FACTOR = 0.50f; - //private Map agents = new HashMap(MAP_SIZE, MAP_LOAD_FACTOR); - private final Map agents; - public LADT(int size) { agents = new HashMap<>(size); } @@ -239,4 +159,84 @@ public String[] getStatus() { return status; } } + + // Rows of the LADT are protected by a recursive mutex lock + private static class Row { + private Agent value; + // DEBUG private Agent bakValue; + // DEBUG private String target = "ma"; + private Thread owner; + private long depth; + + public Row(Agent a) { + value = a; + // DEBUG bakValue = value; + depth = 0; + } + + public synchronized Agent get() { + return value; + } + + public synchronized void clear() { + value = null; + } + + public synchronized void lock() { + if (value != null) { + try { + Thread me = Thread.currentThread(); + while ((owner != null) && (owner != me)) { + // DEBUG boolean b = false; + // DEBUG if (bakValue.getLocalName().equals(target)) { + // DEBUG System.out.println("Thread "+Thread.currentThread().getName()+" start waiting on "+target); + // DEBUG b = true; + // DEBUG } + wait(); + // DEBUG if (b) { + // DEBUG System.out.println("Thread "+Thread.currentThread().getName()+" stop waiting on "+target); + // DEBUG } + if (value == null) { + return; + } + } + + owner = me; + ++depth; + } catch (InterruptedException ie) { + return; + } + } + } + + public synchronized void unlock() { + // Must be owner to unlock + if (owner != Thread.currentThread()) + return; + --depth; + if (depth == 0 || value == null) { + // Note that if the row has just been cleared we must wake up + // hanging threads even if depth is > 0, otherwise they will + // hang forever + owner = null; + // DEBUG try { + // DEBUG if (bakValue.getLocalName().equals(target)) { + // DEBUG System.out.println("Thread "+Thread.currentThread().getName()+" notifying all on "+target); + // DEBUG } + // DEBUG } + // DEBUG catch (Exception e) {} + notifyAll(); + } + } + + // For debugging purpose + public String toString() { + if (value != null) { + return "(" + value.getName() + " :owner " + (owner != null ? owner.toString() : "null") + ")"; + } else { + return "null"; + } + } + + } // End of Row class } diff --git a/src/jade/core/MainContainerImpl.java b/src/jade/core/MainContainerImpl.java index ff98f5b..f3f26df 100644 --- a/src/jade/core/MainContainerImpl.java +++ b/src/jade/core/MainContainerImpl.java @@ -93,20 +93,15 @@ public class MainContainerImpl implements MainContainer, AgentManager { private final Vector replicatedAgentClasses; private final boolean ignoreChildNodesOnShutdown; private final boolean verboseShutdown; - - private ContainerID localContainerID; private final PlatformManagerImpl myPlatformManager; - private final CommandProcessor myCommandProcessor; - private final List platformListeners = new LinkedList<>(); private final List platformAddresses = new LinkedList<>(); private final List agentTools = new LinkedList<>(); - private final ContainerTable containers = new ContainerTable(); private final GADT platformAgents = new GADT(); - private final Logger myLogger = Logger.getMyLogger(getClass().getName()); + private ContainerID localContainerID; public MainContainerImpl(Profile p, PlatformManagerImpl pm) throws ProfileException { myCommandProcessor = p.getCommandProcessor(); diff --git a/src/jade/core/MainDetectionManager.java b/src/jade/core/MainDetectionManager.java index 9c53843..f6f29ee 100644 --- a/src/jade/core/MainDetectionManager.java +++ b/src/jade/core/MainDetectionManager.java @@ -14,51 +14,39 @@ public class MainDetectionManager { - private final static Logger logger = Logger.getMyLogger(MainDetectionManager.class.getName()); - - /* - * configuration options with defaults - */ - private final static String OPT_MCAST_ADDR = "jade_core_MainDetectionManager_mcastaddr"; - private final static String OPT_MCAST_ADDR_DEFAULT = "239.255.10.99"; - - private final static String OPT_MCAST_PORT = "jade_core_MainDetectionManager_mcastport"; - private final static String OPT_MCAST_PORT_DEFAULT = "1199"; - - private final static String OPT_MCAST_TTL = "jade_core_MainDetectionManager_mcastttl"; - private final static String OPT_MCAST_TTL_DEFAULT = "4"; - - private final static String OPT_MCAST_FIRST_TIMEOUT = "jade_core_MainDetectionManager_mcastfirsttimeout"; - private final static String OPT_MCAST_FIRST_TIMEOUT_DEFAULT = "500"; - - private final static String OPT_MCAST_TIMEOUT = "jade_core_MainDetectionManager_mcasttimeout"; - private final static String OPT_MCAST_TIMEOUT_DEFAULT = "2500"; - - private final static String OPT_MCAST_RETRIES = "jade_core_MainDetectionManager_mcastretries"; - private final static String OPT_MCAST_RETRIES_DEFAULT = "3"; - /* * protocol data */ // version string public final static String PROTO_VERSION = " MJADE/1.0"; - // charset used to encode/decode packets public final static String PROTO_ENCODING = "ISO-8859-1"; - // protocol commands public final static String PROTO_CMD_GETMAIN = "get-main"; public final static String PROTO_CMD_PING = "ping"; - // constants for get-main command public final static String PROTO_ADDRESSES_SEPARATOR = ";"; public final static String PROTO_ADDR_SEPARATOR = ":"; - // protocol responses public final static String PROTO_RESP_OK = "200 OK "; public final static String PROTO_RESP_ERR = "500 Internal Server Error"; public final static String PROTO_RESP_NOTFOUND = "404 Not Found"; - + private final static Logger logger = Logger.getMyLogger(MainDetectionManager.class.getName()); + /* + * configuration options with defaults + */ + private final static String OPT_MCAST_ADDR = "jade_core_MainDetectionManager_mcastaddr"; + private final static String OPT_MCAST_ADDR_DEFAULT = "239.255.10.99"; + private final static String OPT_MCAST_PORT = "jade_core_MainDetectionManager_mcastport"; + private final static String OPT_MCAST_PORT_DEFAULT = "1199"; + private final static String OPT_MCAST_TTL = "jade_core_MainDetectionManager_mcastttl"; + private final static String OPT_MCAST_TTL_DEFAULT = "4"; + private final static String OPT_MCAST_FIRST_TIMEOUT = "jade_core_MainDetectionManager_mcastfirsttimeout"; + private final static String OPT_MCAST_FIRST_TIMEOUT_DEFAULT = "500"; + private final static String OPT_MCAST_TIMEOUT = "jade_core_MainDetectionManager_mcasttimeout"; + private final static String OPT_MCAST_TIMEOUT_DEFAULT = "2500"; + private final static String OPT_MCAST_RETRIES = "jade_core_MainDetectionManager_mcastretries"; + private final static String OPT_MCAST_RETRIES_DEFAULT = "3"; // buffer size private final static int DGRAM_BUF_LEN = 1024; @@ -67,81 +55,6 @@ public class MainDetectionManager { private static final String MATCH_ALL_PLATFORMS = "*"; - /* - * inner class used to parse and keep addresses from main - */ - private static class MainAddr { - public String protocol; - public String hostname; - public int port; - - public MainAddr(String address) { - StringTokenizer ast; - /* - * Address must be in form "proto:host:port" - * If address has a bad format, the following code - * will throw an exception. The behaviour is by design. - */ - ast = new StringTokenizer(address, PROTO_ADDR_SEPARATOR); - protocol = ast.nextToken(); - hostname = ast.nextToken(); - port = Integer.parseInt(ast.nextToken()); - } - } - - /* - * inner class used to get multicast parameters from Profile - */ - static class MulticastParams { - String address; - int port; - int firstTimeout; - int timeout; - int retries; - int ttl; - - private void checkTrue(boolean condition, String paramName, String paramValue) throws ProfileException { - if (!condition) { - throw new ProfileException("Bad value \"" + paramValue + "\" for option " + paramName); - } - } - - private int parseInt(String paramName, String paramValue) throws ProfileException { - try { - return Integer.parseInt(paramValue); - } catch (NumberFormatException nfe) { - throw new ProfileException("Bad value \"" + paramValue + "\" for option " + paramName + ": integer value required", nfe); - } - } - - public MulticastParams(Profile p) throws ProfileException { - String s; - - address = p.getParameter(OPT_MCAST_ADDR, OPT_MCAST_ADDR_DEFAULT); - checkTrue(address != null && address.length() > 0, OPT_MCAST_ADDR, address); - - s = p.getParameter(OPT_MCAST_PORT, OPT_MCAST_PORT_DEFAULT); - port = parseInt(OPT_MCAST_PORT, s); - checkTrue(port > 0, OPT_MCAST_PORT, s); - - s = p.getParameter(OPT_MCAST_FIRST_TIMEOUT, OPT_MCAST_FIRST_TIMEOUT_DEFAULT); - firstTimeout = parseInt(OPT_MCAST_FIRST_TIMEOUT, s); - checkTrue(firstTimeout > 0, OPT_MCAST_FIRST_TIMEOUT, s); - - s = p.getParameter(OPT_MCAST_TIMEOUT, OPT_MCAST_TIMEOUT_DEFAULT); - timeout = parseInt(OPT_MCAST_TIMEOUT, s); - checkTrue(timeout >= 0, OPT_MCAST_TIMEOUT, s); - - s = p.getParameter(OPT_MCAST_RETRIES, OPT_MCAST_RETRIES_DEFAULT); - retries = parseInt(OPT_MCAST_RETRIES, s); - checkTrue(retries >= 0, OPT_MCAST_RETRIES, s); - - s = p.getParameter(OPT_MCAST_TTL, OPT_MCAST_TTL_DEFAULT); - ttl = parseInt(OPT_MCAST_TTL, s); - checkTrue(ttl > 0, OPT_MCAST_TTL, s); - } - } - /* * decode data using the right protocol charset and throw away trailing '\0's */ @@ -348,7 +261,7 @@ private static List multicAsk(String request, Profile p) throws */ private static String buildGetMainRequest(String platformName, String proto) { // build request - StringBuffer msg = new StringBuffer(PROTO_CMD_GETMAIN); + StringBuilder msg = new StringBuilder(PROTO_CMD_GETMAIN); if (platformName != null) { msg.append('@'); msg.append(platformName); @@ -413,4 +326,79 @@ public static MulticastMainDetectionListener createListener(ProfileImpl profile, listenerThread.start(); return listener; } + + /* + * inner class used to parse and keep addresses from main + */ + private static class MainAddr { + public String protocol; + public String hostname; + public int port; + + public MainAddr(String address) { + StringTokenizer ast; + /* + * Address must be in form "proto:host:port" + * If address has a bad format, the following code + * will throw an exception. The behaviour is by design. + */ + ast = new StringTokenizer(address, PROTO_ADDR_SEPARATOR); + protocol = ast.nextToken(); + hostname = ast.nextToken(); + port = Integer.parseInt(ast.nextToken()); + } + } + + /* + * inner class used to get multicast parameters from Profile + */ + static class MulticastParams { + String address; + int port; + int firstTimeout; + int timeout; + int retries; + int ttl; + + public MulticastParams(Profile p) throws ProfileException { + String s; + + address = p.getParameter(OPT_MCAST_ADDR, OPT_MCAST_ADDR_DEFAULT); + checkTrue(address != null && address.length() > 0, OPT_MCAST_ADDR, address); + + s = p.getParameter(OPT_MCAST_PORT, OPT_MCAST_PORT_DEFAULT); + port = parseInt(OPT_MCAST_PORT, s); + checkTrue(port > 0, OPT_MCAST_PORT, s); + + s = p.getParameter(OPT_MCAST_FIRST_TIMEOUT, OPT_MCAST_FIRST_TIMEOUT_DEFAULT); + firstTimeout = parseInt(OPT_MCAST_FIRST_TIMEOUT, s); + checkTrue(firstTimeout > 0, OPT_MCAST_FIRST_TIMEOUT, s); + + s = p.getParameter(OPT_MCAST_TIMEOUT, OPT_MCAST_TIMEOUT_DEFAULT); + timeout = parseInt(OPT_MCAST_TIMEOUT, s); + checkTrue(timeout >= 0, OPT_MCAST_TIMEOUT, s); + + s = p.getParameter(OPT_MCAST_RETRIES, OPT_MCAST_RETRIES_DEFAULT); + retries = parseInt(OPT_MCAST_RETRIES, s); + checkTrue(retries >= 0, OPT_MCAST_RETRIES, s); + + s = p.getParameter(OPT_MCAST_TTL, OPT_MCAST_TTL_DEFAULT); + ttl = parseInt(OPT_MCAST_TTL, s); + checkTrue(ttl > 0, OPT_MCAST_TTL, s); + } + + private void checkTrue(boolean condition, String paramName, String paramValue) throws ProfileException { + if (!condition) { + throw new ProfileException("Bad value \"" + paramValue + "\" for option " + paramName); + } + } + + private int parseInt(String paramName, String paramValue) throws ProfileException { + try { + return Integer.parseInt(paramValue); + } catch (NumberFormatException nfe) { + throw new ProfileException("Bad value \"" + paramValue + "\" for option " + paramName + ": integer value required", nfe); + } + } + } } diff --git a/src/jade/core/Node.java b/src/jade/core/Node.java index 62511cb..259364b 100644 --- a/src/jade/core/Node.java +++ b/src/jade/core/Node.java @@ -37,10 +37,10 @@ */ public interface Node extends Serializable { - void setName(String name); - String getName(); + void setName(String name); + boolean hasPlatformManager(); void exportSlice(String serviceName, Service.Slice localSlice); diff --git a/src/jade/core/NodeDescriptor.java b/src/jade/core/NodeDescriptor.java index ec9a2a0..9d14038 100644 --- a/src/jade/core/NodeDescriptor.java +++ b/src/jade/core/NodeDescriptor.java @@ -41,6 +41,16 @@ */ public class NodeDescriptor implements Serializable { + private String myName; + private Node myNode; + private Node parentNode; + private ContainerID myContainer; + private String username; + private byte[] password; + private JADEPrincipal myPrincipal; + private JADEPrincipal ownerPrincipal; + private Credentials ownerCredentials; + /** * Builds a new node descriptor, describing the given node with * the given name and properties. @@ -73,15 +83,6 @@ public NodeDescriptor(ContainerID cid, Node node) { public NodeDescriptor() { } - /** - * Change the name (if any) of the described node. - * - * @param nn The name to assign to the described node. - */ - public void setName(String nn) { - myName = nn; - } - /** * Retrieve the name (if any) of the described node. * @@ -93,13 +94,12 @@ public String getName() { } /** - * Change the described node (if any). + * Change the name (if any) of the described node. * - * @param node The Node object that is to be - * described by this node descriptor. + * @param nn The name to assign to the described node. */ - public void setNode(Node node) { - myNode = node; + public void setName(String nn) { + myName = nn; } /** @@ -112,6 +112,16 @@ public Node getNode() { return myNode; } + /** + * Change the described node (if any). + * + * @param node The Node object that is to be + * described by this node descriptor. + */ + public void setNode(Node node) { + myNode = node; + } + /** * Retrieve the ID of the container (if any) hosted by the * described node. @@ -123,19 +133,12 @@ public ContainerID getContainer() { return myContainer; } - public void setParentNode(Node n) { - parentNode = n; - } - public Node getParentNode() { return parentNode; } - /** - * Set the username of the owner of the described node - */ - public void setUsername(String username) { - this.username = username; + public void setParentNode(Node n) { + parentNode = n; } /** @@ -146,10 +149,10 @@ public String getUsername() { } /** - * Set the password of the owner of the described node + * Set the username of the owner of the described node */ - public void setPassword(byte[] password) { - this.password = password; + public void setUsername(String username) { + this.username = username; } /** @@ -160,10 +163,10 @@ public byte[] getPassword() { } /** - * Set the principal of the described node + * Set the password of the owner of the described node */ - public void setPrincipal(JADEPrincipal principal) { - myPrincipal = principal; + public void setPassword(byte[] password) { + this.password = password; } /** @@ -174,10 +177,10 @@ public JADEPrincipal getPrincipal() { } /** - * Set the principal of the owner of this node + * Set the principal of the described node */ - public void setOwnerPrincipal(JADEPrincipal principal) { - ownerPrincipal = principal; + public void setPrincipal(JADEPrincipal principal) { + myPrincipal = principal; } /** @@ -191,10 +194,10 @@ public JADEPrincipal getOwnerPrincipal() { } /** - * Set the credentials of the owner of this node + * Set the principal of the owner of this node */ - public void setOwnerCredentials(Credentials credentials) { - ownerCredentials = credentials; + public void setOwnerPrincipal(JADEPrincipal principal) { + ownerPrincipal = principal; } /** @@ -207,16 +210,11 @@ public Credentials getOwnerCredentials() { return ownerCredentials; } - private String myName; - private Node myNode; - - private Node parentNode; - - private ContainerID myContainer; - private String username; - private byte[] password; - private JADEPrincipal myPrincipal; - private JADEPrincipal ownerPrincipal; - private Credentials ownerCredentials; + /** + * Set the credentials of the owner of this node + */ + public void setOwnerCredentials(Credentials credentials) { + ownerCredentials = credentials; + } } diff --git a/src/jade/core/NodeFailureMonitor.java b/src/jade/core/NodeFailureMonitor.java index 0920262..5845fa5 100644 --- a/src/jade/core/NodeFailureMonitor.java +++ b/src/jade/core/NodeFailureMonitor.java @@ -113,6 +113,39 @@ public abstract class NodeFailureMonitor { protected NodeEventListener listener; protected Map childNodes = new HashMap<>(); + /** + * Factory method to create NodeFailureMonitor objects + * + * @return a new instance of a NodeFailureMonitor. + */ + public static NodeFailureMonitor getFailureMonitor() { + NodeFailureMonitor nfm = null; + if (theMonitoringService != null) { + nfm = theMonitoringService.getFailureMonitor(); + } + + if (nfm == null) { + // Use the default NodeFailureMonitor + nfm = getDefaultFailureMonitor(); + } + + return nfm; + } + + public static NodeFailureMonitor getDefaultFailureMonitor() { + try { + return (NodeFailureMonitor) Class.forName("jade.core.nodeMonitoring.BlockingNodeFailureMonitor").getDeclaredConstructor().newInstance(); + } catch (Throwable t) { + // Should never happen + t.printStackTrace(); + return null; + } + } + + public static void init(NodeMonitoringService nms) { + theMonitoringService = nms; + } + /** * Start the monitoring * @@ -200,6 +233,11 @@ protected synchronized void fireNodeUnreachable() { } } + + ///////////////////////////////////////////////////// + // Static methods + ///////////////////////////////////////////////////// + private void issueNodeReachable(Node n) { if (theMonitoringService != null) { GenericCommand cmd = new GenericCommand(NodeMonitoringService.NODE_REACHABLE, theMonitoringService.getName(), null); @@ -229,43 +267,4 @@ private void issueNodeUnreachable(Node n) { public String requireService() { return null; } - - - ///////////////////////////////////////////////////// - // Static methods - ///////////////////////////////////////////////////// - - /** - * Factory method to create NodeFailureMonitor objects - * - * @return a new instance of a NodeFailureMonitor. - */ - public static NodeFailureMonitor getFailureMonitor() { - NodeFailureMonitor nfm = null; - if (theMonitoringService != null) { - nfm = theMonitoringService.getFailureMonitor(); - } - - if (nfm == null) { - // Use the default NodeFailureMonitor - nfm = getDefaultFailureMonitor(); - } - - return nfm; - } - - public static NodeFailureMonitor getDefaultFailureMonitor() { - try { - return (NodeFailureMonitor) Class.forName("jade.core.nodeMonitoring.BlockingNodeFailureMonitor").getDeclaredConstructor().newInstance(); - } catch (Throwable t) { - // Should never happen - t.printStackTrace(); - return null; - } - } - - - public static void init(NodeMonitoringService nms) { - theMonitoringService = nms; - } } diff --git a/src/jade/core/PlatformID.java b/src/jade/core/PlatformID.java index 86bceac..81e5ef6 100644 --- a/src/jade/core/PlatformID.java +++ b/src/jade/core/PlatformID.java @@ -36,6 +36,7 @@ */ public class PlatformID implements Location { private static final String NO_NAME = "__NO_NAME__"; + private AID _amsAID; public PlatformID() { _amsAID = new AID(FIPANames.AMS + '@' + NO_NAME, AID.ISGUID); @@ -52,6 +53,10 @@ public String getID() { return _amsAID.getName(); } + public void setID(String id) { + _amsAID.setName(id); + } + /* (non-Javadoc) * @see jade.core.Location#getName() */ @@ -60,6 +65,10 @@ public String getName() { return name.substring(name.lastIndexOf('@') + 1); } + public void setName(String name) { + _amsAID.setName(FIPANames.AMS + '@' + name); + } + /* (non-Javadoc) * @see jade.core.Location#getProtocol() */ @@ -75,6 +84,10 @@ public String getProtocol() { return protocol; } + public void setProtocol(String protocol) { + // Do nothing: this is just for ontology support + } + /* (non-Javadoc) * @see jade.core.Location#getAddress() */ @@ -82,30 +95,16 @@ public String getAddress() { return _amsAID.getAllAddresses().next(); } - public AID getAmsAID() { - return _amsAID; - } - - public void setID(String id) { - _amsAID.setName(id); - } - - public void setName(String name) { - _amsAID.setName(FIPANames.AMS + '@' + name); - } - - public void setProtocol(String protocol) { - // Do nothing: this is just for ontology support - } - public void setAddress(String address) { _amsAID.clearAllAddresses(); _amsAID.addAddresses(address); } + public AID getAmsAID() { + return _amsAID; + } + public void setAmsAID(AID amsAID) { _amsAID = amsAID; } - - private AID _amsAID; } diff --git a/src/jade/core/PlatformManagerImpl.java b/src/jade/core/PlatformManagerImpl.java index e01b449..6746658 100644 --- a/src/jade/core/PlatformManagerImpl.java +++ b/src/jade/core/PlatformManagerImpl.java @@ -52,9 +52,9 @@ public class PlatformManagerImpl implements PlatformManager { private final Map services; private final Map replicas; private final Map monitors; + private final Logger myLogger = Logger.getMyLogger(getClass().getName()); private String localAddr; private String platformID; - // These variables hold progressive numbers just used to name new nodes. // By convention, nodes hosting containers with a local copy of the Platform Manager are called // Main-Container-, hosting containers whereas nodes without their own Platform Manager are @@ -64,121 +64,6 @@ public class PlatformManagerImpl implements PlatformManager { private int mainContainerNo = 0; private int nodeNo = 1; - private final Logger myLogger = Logger.getMyLogger(getClass().getName()); - - /** - * Inner class ServiceEntry (package scoped for debugging purpose) - */ - class ServiceEntry { - - public ServiceEntry(Service s) { - myService = s; - slices = new HashMap<>(); - } - - public void addSlice(String name, Slice s, Node n, boolean childNode) { - SliceEntry e = new SliceEntry(s, n, childNode); - slices.put(name, e); - } - - public Slice removeSlice(String name) { - SliceEntry e = slices.remove(name); - if (e == null) { - return null; - } else { - return e.getSlice(); - } - } - - public Vector getSlices() { - Iterator sliceEntries = slices.values().iterator(); - Vector result = new Vector<>(); - - while (sliceEntries.hasNext()) { - SliceEntry e = sliceEntries.next(); - result.addElement(e.getSlice()); - } - - return result; - } - - public Slice getSlice(String name) { - SliceEntry e = slices.get(name); - if (e == null) { - return null; - } else { - return e.getSlice(); - } - } - - public Node[] getNodes() { - Object[] sliceEntries = slices.values().toArray(); - Node[] result = new Node[sliceEntries.length]; - - for (int i = 0; i < result.length; i++) { - SliceEntry e = (SliceEntry) sliceEntries[i]; - result[i] = e.getNode(); - } - - return result; - } - - public Node getNode(String name) { - SliceEntry e = slices.get(name); - if (e == null) { - return null; - } else { - return e.getNode(); - } - } - - public void setService(Service svc) { - myService = svc; - } - - public Service getService() { - return myService; - } - - // For debugging purpose only - Map getSlicesMap() { - return slices; - } - - private Service myService; - private final Map slices; - - } // End of inner class ServiceEntry class - - /** - * Inner class SliceEntry (package-scoped for debugging purpose) - */ - class SliceEntry { - - public SliceEntry(Slice s, Node n, boolean c) { - mySlice = s; - myNode = n; - childNode = c; - } - - public Slice getSlice() { - return mySlice; - } - - public Node getNode() { - return myNode; - } - - public boolean isInChildNode() { - return childNode; - } - - private final Slice mySlice; - private final Node myNode; - private final boolean childNode; - - } // End of inner class SliceEntry class - /** * Constructs a new Service Manager implementation complying with * a given JADE profile. This constructor is package-scoped, so @@ -215,20 +100,20 @@ MainContainerImpl getMain() { return myMain; } - public void setPlatformName(String name) throws IMTPException { - platformID = name; - } - - // Implementation of the PlatformManager interface - public String getPlatformName() throws IMTPException { return platformID; } + public void setPlatformName(String name) throws IMTPException { + platformID = name; + } + public String getLocalAddress() { return localAddr; } + // Implementation of the PlatformManager interface + public void setLocalAddress(String addr) { localAddr = addr; } @@ -521,7 +406,6 @@ public void addReplica(String newAddr, boolean propagated) throws IMTPException, replicas.put(TransportAddressWrapper.getWrapper(newReplica.getLocalAddress(), myIMTPManager), newReplica); } - // This may throw IMTPException since the new replica must be informed about the platform status private void localAddReplica(PlatformManager newReplica, boolean propagated) throws IMTPException, ServiceException { if (myLogger.isLoggable(Logger.INFO)) { @@ -802,11 +686,7 @@ private List getAllNodesInfo() { for (Node serviceNode : serviceNodes) { String nodeName = serviceNode.getName(); - Vector v = nodeServices.get(nodeName); - if (v == null) { - v = new Vector<>(); - nodeServices.put(nodeName, v); - } + Vector v = nodeServices.computeIfAbsent(nodeName, k -> new Vector<>()); Service svc = e.getService(); v.addElement(new ServiceDescriptor(svc.getName(), svc)); } @@ -996,6 +876,136 @@ private void removeTerminatedNode(Node n) { } + // For debugging purpose only + Map getServicesMap() { + return services; + } + + Map getReplicasMap() { + return replicas; + } + + Map getNodesMap() { + return nodes; + } + + Map getMonitorsMap() { + return monitors; + } + + /** + * Inner class ServiceEntry (package scoped for debugging purpose) + */ + class ServiceEntry { + + private final Map slices; + private Service myService; + + public ServiceEntry(Service s) { + myService = s; + slices = new HashMap<>(); + } + + public void addSlice(String name, Slice s, Node n, boolean childNode) { + SliceEntry e = new SliceEntry(s, n, childNode); + slices.put(name, e); + } + + public Slice removeSlice(String name) { + SliceEntry e = slices.remove(name); + if (e == null) { + return null; + } else { + return e.getSlice(); + } + } + + public Vector getSlices() { + Iterator sliceEntries = slices.values().iterator(); + Vector result = new Vector<>(); + + while (sliceEntries.hasNext()) { + SliceEntry e = sliceEntries.next(); + result.addElement(e.getSlice()); + } + + return result; + } + + public Slice getSlice(String name) { + SliceEntry e = slices.get(name); + if (e == null) { + return null; + } else { + return e.getSlice(); + } + } + + public Node[] getNodes() { + Object[] sliceEntries = slices.values().toArray(); + Node[] result = new Node[sliceEntries.length]; + + for (int i = 0; i < result.length; i++) { + SliceEntry e = (SliceEntry) sliceEntries[i]; + result[i] = e.getNode(); + } + + return result; + } + + public Node getNode(String name) { + SliceEntry e = slices.get(name); + if (e == null) { + return null; + } else { + return e.getNode(); + } + } + + public Service getService() { + return myService; + } + + public void setService(Service svc) { + myService = svc; + } + + // For debugging purpose only + Map getSlicesMap() { + return slices; + } + + } // End of inner class ServiceEntry class + + /** + * Inner class SliceEntry (package-scoped for debugging purpose) + */ + class SliceEntry { + + private final Slice mySlice; + private final Node myNode; + private final boolean childNode; + + public SliceEntry(Slice s, Node n, boolean c) { + mySlice = s; + myNode = n; + childNode = c; + } + + public Slice getSlice() { + return mySlice; + } + + public Node getNode() { + return myNode; + } + + public boolean isInChildNode() { + return childNode; + } + + } // End of inner class SliceEntry class + /** * Inner class NodeInfo. * Embeds the node descriptor and the services currently installed @@ -1022,22 +1032,4 @@ public void setServices(Vector ss) { services = ss; } } // END of inner class NodeInfo - - - // For debugging purpose only - Map getServicesMap() { - return services; - } - - Map getReplicasMap() { - return replicas; - } - - Map getNodesMap() { - return nodes; - } - - Map getMonitorsMap() { - return monitors; - } } diff --git a/src/jade/core/Profile.java b/src/jade/core/Profile.java index 23156b0..7babf7a 100644 --- a/src/jade/core/Profile.java +++ b/src/jade/core/Profile.java @@ -283,145 +283,6 @@ public abstract class Profile { public static final String MIDP = "midp"; public static final String ANDROID = "android"; - - /** - * Obtain a reference to the platform Service Manager, with - * which kernel-level services can be added and removed. - * - * @return A ServiceManager object, representing the - * platform service manager. - */ - protected abstract ServiceManager getServiceManager() throws ProfileException; - - /** - * Obtain a reference to the platform Service Finder, with - * which kernel-level services can be looked up. - * - * @return A ServiceFinder object, representing the - * platform service manager. - */ - protected abstract ServiceFinder getServiceFinder() throws ProfileException; - - /** - * Obtain a reference to the container Command Processor, - * which manages kernel-level commands dispatching them to the - * proper platform services. - * - * @return A ServiceManager object, representing the - * platform service manager. - */ - protected abstract CommandProcessor getCommandProcessor() throws ProfileException; - - //#MIDP_EXCLUDE_BEGIN - protected abstract MainContainerImpl getMain() throws ProfileException; - //#MIDP_EXCLUDE_END - - /** - * - */ - protected abstract IMTPManager getIMTPManager() throws ProfileException; - - /** - * - */ - public abstract ResourceManager getResourceManager() throws ProfileException; - - //#APIDOC_EXCLUDE_END - - - //#MIDP_EXCLUDE_BEGIN - - /** - * Retrieve the configuration properties as they were passed to this Profile object, i.e. without - * internal initializations automatically performed by the Profile class. - */ - public abstract Properties getBootProperties(); - //#MIDP_EXCLUDE_END - - /** - * Retrieve a String value from the configuration properties. - * If no parameter corresponding to the specified key is found, - * return the provided default. - * - * @param key The key identifying the parameter to be retrieved - * among the configuration properties. - * @param aDefault The value to return when there is no property - * set for the given key. - */ - public abstract String getParameter(String key, String aDefault); - - /** - * Retrieve a boolean value for a configuration property. If no - * corresponding property is found or if its string value cannot - * be converted to a boolean one, a default value is returned. - * - * @param key The key identifying the parameter to be retrieved - * among the configuration properties. - * @param aDefault The value to return when there is no property - * set for the given key, or its value cannot be converted to a - * boolean value. - */ - public abstract boolean getBooleanProperty(String key, boolean aDefault); - - /** - * Retrieve a list of Specifiers from the configuration properties. - * Agents, MTPs and other items are specified among the configuration - * properties in this way. - * If no list of Specifiers corresponding to the specified key is found, - * an empty list is returned. - * - * @param key The key identifying the list of Specifires to be retrieved - * among the configuration properties. - */ - public abstract List getSpecifiers(String key) throws ProfileException; - - /** - * Assign the given value to the given property name. - * - * @param key is the property name - * @param value is the property value - */ - public abstract void setParameter(String key, String value); - - /** - * Assign the given value to the given property name. - * - * @param key is the property name - * @param value is the property value - */ - public abstract void setSpecifiers(String key, List value); - - - /** - * Provides a boolean indication about whether or not the container using this Profile - * is a Main Container. - * - * @return true if the container using this Profile is a Main Container. false otherwise - */ - public boolean isMain() { - return getBooleanProperty(MAIN, false); - } - - /** - * Provides a boolean indication about whether or not the container using this Profile - * is the Master Main Container. - * - * @return true if the container using this Profile is the Master Main Container. false otherwise - */ - public boolean isMasterMain() { - return isMain() && !getBooleanProperty(LOCAL_SERVICE_MANAGER, false); - } - - /** - * Provides a boolean indication about whether or not the container using this Profile - * is a Backup Main Container. - * - * @return true if the container using this Profile is a Backup Main Container. false otherwise - */ - public boolean isBackupMain() { - return isMain() && getBooleanProperty(LOCAL_SERVICE_MANAGER, false); - } - public static String getDefaultNetworkName() { return getDefaultNetworkName(false); } @@ -472,8 +333,6 @@ public static String getDefaultNetworkName(boolean priviledgeLogicalName) { return host; } - //#MIDP_EXCLUDE_BEGIN - /** * Check whether or not a given host name or address corresponds to a local network interface */ @@ -503,7 +362,7 @@ public static boolean isLocalHost(String host) { } } //#DOTNET_EXCLUDE_END - + /*#DOTNET_INCLUDE_BEGIN return localHostAddr.equals(InetAddress.getLocalHost()); #DOTNET_INCLUDE_END*/ @@ -571,6 +430,7 @@ public static boolean compareHostNames(String host1, String host2) { return false; } } + //#MIDP_EXCLUDE_END /** * Compares two stringified transport addresses. @@ -602,6 +462,144 @@ public static boolean compareTransportAddresses(TransportAddress ta1, TransportA } return false; } + + //#APIDOC_EXCLUDE_END + + + //#MIDP_EXCLUDE_BEGIN + + /** + * Obtain a reference to the platform Service Manager, with + * which kernel-level services can be added and removed. + * + * @return A ServiceManager object, representing the + * platform service manager. + */ + protected abstract ServiceManager getServiceManager() throws ProfileException; + //#MIDP_EXCLUDE_END + + /** + * Obtain a reference to the platform Service Finder, with + * which kernel-level services can be looked up. + * + * @return A ServiceFinder object, representing the + * platform service manager. + */ + protected abstract ServiceFinder getServiceFinder() throws ProfileException; + + /** + * Obtain a reference to the container Command Processor, + * which manages kernel-level commands dispatching them to the + * proper platform services. + * + * @return A ServiceManager object, representing the + * platform service manager. + */ + protected abstract CommandProcessor getCommandProcessor() throws ProfileException; + + //#MIDP_EXCLUDE_BEGIN + protected abstract MainContainerImpl getMain() throws ProfileException; + + /** + * + */ + protected abstract IMTPManager getIMTPManager() throws ProfileException; + + /** + * + */ + public abstract ResourceManager getResourceManager() throws ProfileException; + + /** + * Retrieve the configuration properties as they were passed to this Profile object, i.e. without + * internal initializations automatically performed by the Profile class. + */ + public abstract Properties getBootProperties(); + + /** + * Retrieve a String value from the configuration properties. + * If no parameter corresponding to the specified key is found, + * return the provided default. + * + * @param key The key identifying the parameter to be retrieved + * among the configuration properties. + * @param aDefault The value to return when there is no property + * set for the given key. + */ + public abstract String getParameter(String key, String aDefault); + + /** + * Retrieve a boolean value for a configuration property. If no + * corresponding property is found or if its string value cannot + * be converted to a boolean one, a default value is returned. + * + * @param key The key identifying the parameter to be retrieved + * among the configuration properties. + * @param aDefault The value to return when there is no property + * set for the given key, or its value cannot be converted to a + * boolean value. + */ + public abstract boolean getBooleanProperty(String key, boolean aDefault); + + /** + * Retrieve a list of Specifiers from the configuration properties. + * Agents, MTPs and other items are specified among the configuration + * properties in this way. + * If no list of Specifiers corresponding to the specified key is found, + * an empty list is returned. + * + * @param key The key identifying the list of Specifires to be retrieved + * among the configuration properties. + */ + public abstract List getSpecifiers(String key) throws ProfileException; + + /** + * Assign the given value to the given property name. + * + * @param key is the property name + * @param value is the property value + */ + public abstract void setParameter(String key, String value); + + //#MIDP_EXCLUDE_BEGIN + + /** + * Assign the given value to the given property name. + * + * @param key is the property name + * @param value is the property value + */ + public abstract void setSpecifiers(String key, List value); + + /** + * Provides a boolean indication about whether or not the container using this Profile + * is a Main Container. + * + * @return true if the container using this Profile is a Main Container. false otherwise + */ + public boolean isMain() { + return getBooleanProperty(MAIN, false); + } + + /** + * Provides a boolean indication about whether or not the container using this Profile + * is the Master Main Container. + * + * @return true if the container using this Profile is the Master Main Container. false otherwise + */ + public boolean isMasterMain() { + return isMain() && !getBooleanProperty(LOCAL_SERVICE_MANAGER, false); + } + + /** + * Provides a boolean indication about whether or not the container using this Profile + * is a Backup Main Container. + * + * @return true if the container using this Profile is a Backup Main Container. false otherwise + */ + public boolean isBackupMain() { + return isMain() && getBooleanProperty(LOCAL_SERVICE_MANAGER, false); + } //#MIDP_EXCLUDE_END } diff --git a/src/jade/core/ProfileImpl.java b/src/jade/core/ProfileImpl.java index 48c739b..a3d8275 100644 --- a/src/jade/core/ProfileImpl.java +++ b/src/jade/core/ProfileImpl.java @@ -29,10 +29,7 @@ import java.io.IOException; import java.io.Reader; import java.io.StringReader; -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; -import java.util.Vector; +import java.util.*; /** * This class allows the JADE core to retrieve configuration-dependent classes @@ -49,14 +46,11 @@ */ public class ProfileImpl extends Profile { - private final Properties props; - protected Properties bootProps = null; - - // Keys to retrieve the implementation classes for configurable // functionalities among the bootstrap properties. private static final String RESOURCE = "resource"; - + private final Properties props; + protected Properties bootProps = null; //#MIDP_EXCLUDE_BEGIN private MainContainerImpl myMain = null; //#MIDP_EXCLUDE_END @@ -214,11 +208,7 @@ void init() { // the default port if also the local port is null. if (isMasterMain()) { - if (localPort != null) { - p = localPort; - } else { - p = Integer.toString(DEFAULT_PORT); - } + p = Objects.requireNonNullElseGet(localPort, () -> Integer.toString(DEFAULT_PORT)); } else { // All other cases: use the default port. p = Integer.toString(DEFAULT_PORT); @@ -560,10 +550,7 @@ private void createResourceManager() throws ProfileException { private void setPropertyIfNot(String key, String value) { - Object old = props.get(key); - if (old == null) { - props.put(key, value); - } + props.putIfAbsent(key, value); } private void setIntProperty(String aKey, int aValue) { diff --git a/src/jade/core/Runtime.java b/src/jade/core/Runtime.java index adc5e73..523a0e3 100644 --- a/src/jade/core/Runtime.java +++ b/src/jade/core/Runtime.java @@ -70,20 +70,18 @@ public class Runtime { theInstance = new Runtime(); } + private final LinkedList terminators = new LinkedList<>(); + private final Logger myLogger = Logger.getMyLogger(getClass().getName()); //#MIDP_EXCLUDE_BEGIN private ThreadGroup criticalThreads; //#MIDP_EXCLUDE_END private String version = "UNKNOWN"; private String revision = "UNKNOWN"; private String date = "UNKNOWN"; - private int activeContainers = 0; - private final LinkedList terminators = new LinkedList<>(); private AgentContainerImpl theContainer = null; private int mode = UNKNOWN_MODE; - private final Logger myLogger = Logger.getMyLogger(getClass().getName()); - // Private constructor to forbid instantiation outside the class. private Runtime() { //#MIDP_EXCLUDE_BEGIN @@ -106,6 +104,33 @@ public static Runtime instance() { //#MIDP_EXCLUDE_BEGIN + /** + * Return a String with copyright Notice, Name and Version of this version of JADE + */ + public static String getCopyrightNotice() { + return (" This is " + getVersionInfo() + "\n downloaded in Open Source, under LGPL restrictions,\n at http://jade.tilab.com/\n"); + } + + /** + * Return the version number and date of this JADE Runtime. + */ + public static String getVersionInfo() { + return "JADE " + getVersion() + " - revision " + getRevision() + " of " + getDate(); + } + + public static String getVersion() { + return theInstance.version; + } + //#MIDP_EXCLUDE_END + + public static String getRevision() { + return theInstance.revision; + } + + public static String getDate() { + return theInstance.date; + } + /** * Creates a new agent container in the current JVM, providing * access through a proxy object. @@ -137,6 +162,8 @@ public jade.wrapper.AgentContainer createAgentContainer(Profile p) { } } + //#APIDOC_EXCLUDE_BEGIN + /** * Creates a new main container in the current JVM, providing * access through a proxy object. @@ -167,6 +194,7 @@ public jade.wrapper.AgentContainer createMainContainer(Profile p) { throw new IllegalStateException("Single-container modality already activated"); } } + //#APIDOC_EXCLUDE_END /** * Causes the local JVM to be closed when the last container in this @@ -185,8 +213,6 @@ public void setCloseVM(boolean flag) { }); } } - //#MIDP_EXCLUDE_END - /** * Starts a JADE container in the Single-container modality. @@ -218,6 +244,10 @@ public void shutDown() { theContainer.shutDown(); } } + //#APIDOC_EXCLUDE_END + + + //#APIDOC_EXCLUDE_BEGIN /** * Allows setting a Runnable that is executed when @@ -226,8 +256,7 @@ public void shutDown() { public void invokeOnTermination(Runnable r) { terminators.addFirst(r); } - - //#APIDOC_EXCLUDE_BEGIN + //#APIDOC_EXCLUDE_END /** * Reset the list of Runnable objects to be executed on JADE termination @@ -236,7 +265,6 @@ public void invokeOnTermination(Runnable r) { public void resetTerminators() { terminators.clear(); } - //#APIDOC_EXCLUDE_END // Called by a starting up container. void beginContainer() { @@ -306,36 +334,5 @@ void endContainer() { public TimerDispatcher getTimerDispatcher() { return TimerDispatcher.getTimerDispatcher(); } - //#APIDOC_EXCLUDE_END - - - //#APIDOC_EXCLUDE_BEGIN - - /** - * Return a String with copyright Notice, Name and Version of this version of JADE - */ - public static String getCopyrightNotice() { - return (" This is " + getVersionInfo() + "\n downloaded in Open Source, under LGPL restrictions,\n at http://jade.tilab.com/\n"); - } - //#APIDOC_EXCLUDE_END - - /** - * Return the version number and date of this JADE Runtime. - */ - public static String getVersionInfo() { - return "JADE " + getVersion() + " - revision " + getRevision() + " of " + getDate(); - } - - public static String getVersion() { - return theInstance.version; - } - - public static String getRevision() { - return theInstance.revision; - } - - public static String getDate() { - return theInstance.date; - } } diff --git a/src/jade/core/ScalabilityTest.java b/src/jade/core/ScalabilityTest.java index 185abe8..b1085bf 100644 --- a/src/jade/core/ScalabilityTest.java +++ b/src/jade/core/ScalabilityTest.java @@ -73,7 +73,7 @@ public class ScalabilityTest { private static final Object terminatedLock = new Object(); private static final Object readyLock = new Object(); private static final Object semaphore = new Object(); - + private static final Random random = new Random(); private static byte[] content; private static long timeInterval; private static int nIterations; @@ -84,14 +84,10 @@ public class ScalabilityTest { private static int measure; private static int readyCnt = 0; private static int terminatedCnt = 0; - private static long totalTime = 0; private static long totalTime2 = 0; - private static BufferedReader inputReader; - private static final Random random = new Random(); - public static void main(String[] args) { ExtendedProperties pp = parseArguments(args); Properties jadeProps = pp.extractSubset("jade."); diff --git a/src/jade/core/Scheduler.java b/src/jade/core/Scheduler.java index 734ea36..9bc93da 100644 --- a/src/jade/core/Scheduler.java +++ b/src/jade/core/Scheduler.java @@ -54,23 +54,20 @@ class Scheduler implements Serializable { + /** + * @serial + */ + private final Agent owner; //#MIDP_EXCLUDE_BEGIN protected List readyBehaviours = new LinkedList<>(); - protected List blockedBehaviours = new LinkedList<>(); //#MIDP_EXCLUDE_END /*#MIDP_INCLUDE_BEGIN protected Vector readyBehaviours = new Vector(); protected Vector blockedBehaviours = new Vector(); #MIDP_INCLUDE_END*/ - - - /** - @serial - */ - private final Agent owner; - + protected List blockedBehaviours = new LinkedList<>(); /** - @serial + * @serial */ private int currentIndex; @@ -128,16 +125,16 @@ public synchronized void restart(Behaviour b) { } /** - Restarts all behaviours. This method simply calls - Behaviour.restart() on every behaviour. The - Behaviour.restart() method then notifies the agent (with the - Agent.notifyRestarted() method), causing Scheduler.restart() to - be called (this also moves behaviours from the blocked queue to - the ready queue --> we must copy all behaviours into a temporary - buffer to avoid concurrent modification exceptions). - Why not restarting only blocked behaviours? - Some ready behaviour can be a ParallelBehaviour with some of its - children blocked. These children must be restarted too. + * Restarts all behaviours. This method simply calls + * Behaviour.restart() on every behaviour. The + * Behaviour.restart() method then notifies the agent (with the + * Agent.notifyRestarted() method), causing Scheduler.restart() to + * be called (this also moves behaviours from the blocked queue to + * the ready queue --> we must copy all behaviours into a temporary + * buffer to avoid concurrent modification exceptions). + * Why not restarting only blocked behaviours? + * Some ready behaviour can be a ParallelBehaviour with some of its + * children blocked. These children must be restarted too. */ public synchronized void restartAll() { @@ -189,7 +186,7 @@ public synchronized void restartAll() { } /** - Removes a specified behaviour from the scheduler + * Removes a specified behaviour from the scheduler */ public synchronized void remove(Behaviour b) { boolean found = removeFromBlocked(b); @@ -204,8 +201,8 @@ public synchronized void remove(Behaviour b) { } /** - Selects the appropriate behaviour for execution, with a trivial - round-robin algorithm. + * Selects the appropriate behaviour for execution, with a trivial + * round-robin algorithm. */ public synchronized Behaviour schedule() throws InterruptedException { while (readyBehaviours.isEmpty()) { diff --git a/src/jade/core/Service.java b/src/jade/core/Service.java index 84353c6..8f04238 100644 --- a/src/jade/core/Service.java +++ b/src/jade/core/Service.java @@ -90,116 +90,6 @@ public interface Service { */ String RECONNECTED = "Reconnected"; - /** - * The Slice nested interface represents that part of - * a service that is deployed at a given network node. - */ - interface Slice extends Serializable { - - /** - * Access the service object which this slice is a part of. - * - * @return A Service object, that has - * this as one of its slices. - * @see Service#getSlice(String name) - */ - Service getService(); - - /** - * Access the node where this slice resides. - * - * @returns The node where this service slice is actually - * running. - * throws ServiceException If some problems occur in - * retrieving the local node. - */ - Node getNode() throws ServiceException; - - /** - * Serves an incoming horizontal command, performing any - * required immediate processing, before turning it into a - * vertical command to be processed by the incoming filter - * chain. - * - * @param cmd The command that is to be served. - * @return A vertical command, that will be processed by the - * incoming filter chain of the receiving node. If - * null is returned, no filter/sink processing - * will happen. This feature can be used to decouple incoming - * horizontal interaction patterns from vertical incoming - * commands (e.g. no incoming vertical command is generated - * until a required set of horizontal commands has been - * received). - */ - VerticalCommand serve(HorizontalCommand cmd); - - - } - - //#APIDOC_EXCLUDE_BEGIN - //#DOTNET_EXCLUDE_BEGIN - // 15/4/05 We had to deprecate this class because of the .NET integration - - /** - * An implementation of the Slice interface, - * supporting routed dispatching of horizontal commands. - * - * @deprecated use the class jade.core.SliceProxy instead of this inner class - */ - class SliceProxy extends jade.core.SliceProxy implements Slice { - - public SliceProxy() { - super(); - } - - public SliceProxy(Service svc, Node n) { - super(svc, n); - } - /*public SliceProxy() { - this(null, null); - } - - public SliceProxy(Service svc, Node n) { - myService = svc; - myNode = n; - } - - public Service getService() { - return myService; - } - - public Node getNode() throws ServiceException { - return myNode; - } - - public void setNode(Node n) { - myNode = n; - }*/ - - /* - Try to serve an incoming horizontal command, routing it to - a remote slice implementation. - - @param cmd The command to serve, possibly through the network. - * - public VerticalCommand serve(HorizontalCommand cmd) { - try { - cmd.setReturnValue(myNode.accept(cmd)); - } - catch(IMTPException imtpe) { - cmd.setReturnValue(new ServiceException("An error occurred while routing the command to the remote implementation", imtpe)); - } - // No local processing of this command is required - return null; - } - - private Node myNode; - private transient Service myService; - */ - } - //#DOTNET_EXCLUDE_END - //#APIDOC_EXCLUDE_END - /** * Retrieve the name of this service, that can be used to look up * its slices in the Service Finder. @@ -209,6 +99,10 @@ public VerticalCommand serve(HorizontalCommand cmd) { */ String getName(); + //#APIDOC_EXCLUDE_BEGIN + //#DOTNET_EXCLUDE_BEGIN + // 15/4/05 We had to deprecate this class because of the .NET integration + /** * Retrieve by name a slice of this service. For distributed * services, the returned slice will generally be some kind of @@ -226,6 +120,8 @@ public VerticalCommand serve(HorizontalCommand cmd) { * the requested slice exists or not. */ Slice getSlice(String name) throws ServiceException; + //#DOTNET_EXCLUDE_END + //#APIDOC_EXCLUDE_END /** * Retrieve the locally installed slice of this service. A service @@ -275,7 +171,6 @@ public VerticalCommand serve(HorizontalCommand cmd) { */ int getNumberOfSlices(); - /** * Access the command filter this service needs to perform its * tasks. This filter will be installed within the local command @@ -296,7 +191,6 @@ public VerticalCommand serve(HorizontalCommand cmd) { */ Filter getCommandFilter(boolean direction); - /** * Access the command sink this service uses to handle its own * vertical commands. @@ -315,7 +209,6 @@ public VerticalCommand serve(HorizontalCommand cmd) { */ Sink getCommandSink(boolean side); - /** * Access the names of the vertical commands this service wants to * handle as their final destination. This set must not overlap @@ -388,7 +281,6 @@ public VerticalCommand serve(HorizontalCommand cmd) { */ void shutdown(); - /** * Allows submitting a vertical command for processing. * The given vertical command must be owned by this service @@ -405,4 +297,108 @@ public VerticalCommand serve(HorizontalCommand cmd) { */ Object submit(VerticalCommand cmd) throws ServiceException; + /** + * The Slice nested interface represents that part of + * a service that is deployed at a given network node. + */ + interface Slice extends Serializable { + + /** + * Access the service object which this slice is a part of. + * + * @return A Service object, that has + * this as one of its slices. + * @see Service#getSlice(String name) + */ + Service getService(); + + /** + * Access the node where this slice resides. + * + * @returns The node where this service slice is actually + * running. + * throws ServiceException If some problems occur in + * retrieving the local node. + */ + Node getNode() throws ServiceException; + + /** + * Serves an incoming horizontal command, performing any + * required immediate processing, before turning it into a + * vertical command to be processed by the incoming filter + * chain. + * + * @param cmd The command that is to be served. + * @return A vertical command, that will be processed by the + * incoming filter chain of the receiving node. If + * null is returned, no filter/sink processing + * will happen. This feature can be used to decouple incoming + * horizontal interaction patterns from vertical incoming + * commands (e.g. no incoming vertical command is generated + * until a required set of horizontal commands has been + * received). + */ + VerticalCommand serve(HorizontalCommand cmd); + + + } + + /** + * An implementation of the Slice interface, + * supporting routed dispatching of horizontal commands. + * + * @deprecated use the class jade.core.SliceProxy instead of this inner class + */ + class SliceProxy extends jade.core.SliceProxy implements Slice { + + public SliceProxy() { + super(); + } + + public SliceProxy(Service svc, Node n) { + super(svc, n); + } + /*public SliceProxy() { + this(null, null); + } + + public SliceProxy(Service svc, Node n) { + myService = svc; + myNode = n; + } + + public Service getService() { + return myService; + } + + public Node getNode() throws ServiceException { + return myNode; + } + + public void setNode(Node n) { + myNode = n; + }*/ + + /* + Try to serve an incoming horizontal command, routing it to + a remote slice implementation. + + @param cmd The command to serve, possibly through the network. + * + public VerticalCommand serve(HorizontalCommand cmd) { + try { + cmd.setReturnValue(myNode.accept(cmd)); + } + catch(IMTPException imtpe) { + cmd.setReturnValue(new ServiceException("An error occurred while routing the command to the remote implementation", imtpe)); + } + // No local processing of this command is required + return null; + } + + private Node myNode; + private transient Service myService; + */ + } + } diff --git a/src/jade/core/ServiceDescriptor.java b/src/jade/core/ServiceDescriptor.java index 3247655..2c9cf5a 100644 --- a/src/jade/core/ServiceDescriptor.java +++ b/src/jade/core/ServiceDescriptor.java @@ -40,6 +40,12 @@ */ public class ServiceDescriptor implements Serializable { + private String myName; + private boolean myIsMandatory; + private transient Service myService; + //#MIDP_EXCLUDE_BEGIN + private String serviceClass; + /** * Builds a new service descriptor, describing the given service * with the given name and properties. @@ -63,15 +69,6 @@ public ServiceDescriptor() { this(null, null); } - /** - * Change the name (if any) of the described service. - * - * @param sn The name to assign to the described service. - */ - public void setName(String sn) { - myName = sn; - } - /** * Retrieve the name (if any) of the described service. * @@ -83,13 +80,12 @@ public String getName() { } /** - * Change the described service (if any). + * Change the name (if any) of the described service. * - * @param svc The Service object that is to be - * described by this service descriptor. + * @param sn The name to assign to the described service. */ - public void setService(Service svc) { - myService = svc; + public void setName(String sn) { + myName = sn; } /** @@ -102,20 +98,23 @@ public Service getService() { return myService; } - public void setMandatory(boolean isMandatory) { - myIsMandatory = isMandatory; + /** + * Change the described service (if any). + * + * @param svc The Service object that is to be + * described by this service descriptor. + */ + public void setService(Service svc) { + myService = svc; } public boolean isMandatory() { return myIsMandatory; } - private String myName; - private boolean myIsMandatory; - private transient Service myService; - - //#MIDP_EXCLUDE_BEGIN - private String serviceClass; + public void setMandatory(boolean isMandatory) { + myIsMandatory = isMandatory; + } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { if (myService != null) { diff --git a/src/jade/core/ServiceManagerImpl.java b/src/jade/core/ServiceManagerImpl.java index edd5364..3bef346 100644 --- a/src/jade/core/ServiceManagerImpl.java +++ b/src/jade/core/ServiceManagerImpl.java @@ -47,18 +47,16 @@ public class ServiceManagerImpl implements ServiceManager, ServiceFinder { private final IMTPManager myIMTPManager; private final CommandProcessor myCommandProcessor; + private final Map localServices; + private final Map backupManagers; + private final Logger myLogger; private PlatformManager myPlatformManager; private boolean invalidPlatformManager; private String platformName; private Node localNode; private NodeDescriptor localNodeDescriptor; - private final Map localServices; - private final Map backupManagers; - private int status = IDLE_STATUS; - private final Logger myLogger; - /** * Constructs a new Service Manager implementation complying with * a given JADE profile. This constructor is package-scoped, so diff --git a/src/jade/core/SliceProxy.java b/src/jade/core/SliceProxy.java index ae88e64..bef0e0b 100644 --- a/src/jade/core/SliceProxy.java +++ b/src/jade/core/SliceProxy.java @@ -29,6 +29,10 @@ */ public class SliceProxy implements Service.Slice { + private final transient Service myService; + private Node myNode; + private transient NodeDescriptor localNodeDescriptor; + public SliceProxy() { this(null, null); } @@ -70,8 +74,4 @@ void setLocalNodeDescriptor(NodeDescriptor dsc) { localNodeDescriptor = dsc; } - private Node myNode; - private transient NodeDescriptor localNodeDescriptor; - private final transient Service myService; - } diff --git a/src/jade/core/Specifier.java b/src/jade/core/Specifier.java index 9a05d4f..9d7e8a5 100644 --- a/src/jade/core/Specifier.java +++ b/src/jade/core/Specifier.java @@ -45,100 +45,6 @@ public class Specifier { private String className = null; private Object[] args = null; - /** - * Set the name for this specifier object. - * - * @param n The name to give to this specifier. - */ - public void setName(String n) { - name = n; - } - - /** - * Retrieve the name for this specifier object. - * - * @return The name of the specifier, if one was set, or - * null otherwise. - */ - public String getName() { - return name; - } - - /** - * Set the name of the class of this specifier. - * - * @param cn The class name to assign to the specifier object. - */ - public void setClassName(String cn) { - className = cn; - } - - /** - * Retrieve the class name of this specifier. - * - * @return The class name of the specifier, if one was set, or - * null otherwise. - */ - public String getClassName() { - return className; - } - - /** - * Set the argument list for this specifier object. - * - * @param a An object array containing the argument list for this - * specifier. - */ - public void setArgs(Object[] a) { - args = a; - } - - /** - * Retrieve the argument list for this specifier. - * - * @return An object array containing the argument list, if one - * was set, or null otherwise. - */ - public Object[] getArgs() { - return args; - } - - /** - * This method is used by Boot, ProfileImpl, and RMA in order - * to have a String representation of this Specifier according to the - * format name:className(arg1 arg2 argn) - * - * @return A string representation of this specifier, according to - * the format above. - **/ - public String toString() { - // TAKE CARE: do not change this method otherwise Boot might fail - StringBuilder tmp = new StringBuilder(); - if (name != null) { - tmp.append(name); - tmp.append(":"); - } - if (className != null) { - tmp.append(className); - } - if (args != null) { - tmp.append("("); - for (int i = 0; i < args.length; i++) { - tmp.append(args[i]); - if (i < args.length - 1) { - //#ALL_EXCLUDE_BEGIN - tmp.append(" "); - //#ALL_EXCLUDE_END - /*#ALL_INCLUDE_BEGIN - tmp.append(","); - //#ALL_INCLUDE_END*/ - } - } - tmp.append(")"); - } - return tmp.toString(); - } - /** * This static utility method can parse the string representation of * a list of specifiers. The general format of a specifier is used, @@ -309,6 +215,100 @@ private static String[] parseArguments(String args, char argsDelimiter) { return arguments; } + /** + * Retrieve the name for this specifier object. + * + * @return The name of the specifier, if one was set, or + * null otherwise. + */ + public String getName() { + return name; + } + + /** + * Set the name for this specifier object. + * + * @param n The name to give to this specifier. + */ + public void setName(String n) { + name = n; + } + + /** + * Retrieve the class name of this specifier. + * + * @return The class name of the specifier, if one was set, or + * null otherwise. + */ + public String getClassName() { + return className; + } + + /** + * Set the name of the class of this specifier. + * + * @param cn The class name to assign to the specifier object. + */ + public void setClassName(String cn) { + className = cn; + } + + /** + * Retrieve the argument list for this specifier. + * + * @return An object array containing the argument list, if one + * was set, or null otherwise. + */ + public Object[] getArgs() { + return args; + } + + /** + * Set the argument list for this specifier object. + * + * @param a An object array containing the argument list for this + * specifier. + */ + public void setArgs(Object[] a) { + args = a; + } + + /** + * This method is used by Boot, ProfileImpl, and RMA in order + * to have a String representation of this Specifier according to the + * format name:className(arg1 arg2 argn) + * + * @return A string representation of this specifier, according to + * the format above. + **/ + public String toString() { + // TAKE CARE: do not change this method otherwise Boot might fail + StringBuilder tmp = new StringBuilder(); + if (name != null) { + tmp.append(name); + tmp.append(":"); + } + if (className != null) { + tmp.append(className); + } + if (args != null) { + tmp.append("("); + for (int i = 0; i < args.length; i++) { + tmp.append(args[i]); + if (i < args.length - 1) { + //#ALL_EXCLUDE_BEGIN + tmp.append(" "); + //#ALL_EXCLUDE_END + /*#ALL_INCLUDE_BEGIN + tmp.append(","); + //#ALL_INCLUDE_END*/ + } + } + tmp.append(")"); + } + return tmp.toString(); + } + } diff --git a/src/jade/core/Timer.java b/src/jade/core/Timer.java index a0805ac..c935145 100644 --- a/src/jade/core/Timer.java +++ b/src/jade/core/Timer.java @@ -36,9 +36,9 @@ */ public class Timer { + private final TimerListener owner; private long expireTimeMillis; private boolean fired; - private final TimerListener owner; public Timer(long when, TimerListener tl) { expireTimeMillis = when; diff --git a/src/jade/core/TimerDispatcher.java b/src/jade/core/TimerDispatcher.java index b2d6d3e..1fe4aac 100644 --- a/src/jade/core/TimerDispatcher.java +++ b/src/jade/core/TimerDispatcher.java @@ -41,21 +41,29 @@ public class TimerDispatcher implements Runnable { // The singleton TimerDispatcher private static TimerDispatcher theDispatcher; - - private Thread myThread = null; - // In J2ME we use a Vector to keep timers to minimize the number of classes. // In J2SE, where we can have thousands of timers, using a Vector can be highly inefficient --> // We use a TreeSet wrapped into a class that mimic the methods of a Vector. //#J2ME_EXCLUDE_BEGIN private final TimersList timers = new TimersList(); + protected Logger myLogger = Logger.getJADELogger(getClass().getName()); + private Thread myThread = null; //#J2ME_EXCLUDE_END /*#J2ME_INCLUDE_BEGIN private Vector timers = new Vector(); #J2ME_INCLUDE_END*/ private boolean active; - protected Logger myLogger = Logger.getJADELogger(getClass().getName()); + public static TimerDispatcher getTimerDispatcher() { + if (theDispatcher == null) { + theDispatcher = new TimerDispatcher(); + } + return theDispatcher; + } + + public static void setTimerDispatcher(TimerDispatcher td) { + theDispatcher = td; + } void setThread(Thread t) { if (myThread == null) { @@ -154,17 +162,6 @@ void stop() { } } - public static TimerDispatcher getTimerDispatcher() { - if (theDispatcher == null) { - theDispatcher = new TimerDispatcher(); - } - return theDispatcher; - } - - public static void setTimerDispatcher(TimerDispatcher td) { - theDispatcher = td; - } - private boolean addTimer(Timer t) { //#J2ME_EXCLUDE_BEGIN return timers.add(t); diff --git a/src/jade/core/behaviours/BaseInitiator.java b/src/jade/core/behaviours/BaseInitiator.java index 1a7ceb1..09811d3 100644 --- a/src/jade/core/behaviours/BaseInitiator.java +++ b/src/jade/core/behaviours/BaseInitiator.java @@ -47,16 +47,13 @@ */ public abstract class BaseInitiator extends AchieveREInitiator { private static final long serialVersionUID = -6505544004754497428L; - - private AID target; - private String defaultTargetDescription; - + private static int conversationCnt = 0; protected OutcomeManager outcome; protected ConversationList conversations; - private String convId; - private static int conversationCnt = 0; - protected Logger myLogger = Logger.getJADELogger(getClass().getName()); + private AID target; + private String defaultTargetDescription; + private String convId; public BaseInitiator() { this(null); diff --git a/src/jade/core/behaviours/Behaviour.java b/src/jade/core/behaviours/Behaviour.java index 8dd2306..42447f6 100644 --- a/src/jade/core/behaviours/Behaviour.java +++ b/src/jade/core/behaviours/Behaviour.java @@ -42,25 +42,6 @@ * @version $Date: 2013-03-11 09:55:05 +0100 (lun, 11 mar 2013) $ $Revision: 6645 $ */ public abstract class Behaviour implements Serializable { - @Serial - private static final long serialVersionUID = 3487495895819001L; - - //#APIDOC_EXCLUDE_BEGIN - - /** - * A constant for child-to-parent notifications. - * - * @serial - */ - protected static final int NOTIFY_UP = -1; - - /** - * A constant for parent-to-child notifications. - * - * @serial - */ - protected static final int NOTIFY_DOWN = 1; - /** * A constant identifying the runnable state. * @@ -68,103 +49,33 @@ public abstract class Behaviour implements Serializable { */ public static final String STATE_READY = "READY"; + //#APIDOC_EXCLUDE_BEGIN /** * A constant identifying the blocked state. * * @serial */ public static final String STATE_BLOCKED = "BLOCKED"; - /** * A constant identifying the running state. * * @serial */ public static final String STATE_RUNNING = "RUNNING"; - - /** - * Event class for notifying blocked and restarted behaviours. - * This class is used to notify interested behaviours when a - * Behaviour changes its runnable state. It may be sent to - * behaviour's parent (upward notification or to behaviour's - * children (downward notification). + * A constant for child-to-parent notifications. + * + * @serial */ - protected class RunnableChangedEvent implements Serializable { - @Serial - private static final long serialVersionUID = 3487495895819002L; - /** - * @serial - */ - private boolean runnable; - - /** - * @serial - */ - private int direction; - - /** - * Re-init event content. This method can be used to rewrite an - * existing event with new data (much cheaper than making a new - * object). - * - * @param b A boolean flag; when false - * it means that a behaviour passed from Ready to - * Blocked state. When true it means that a - * behaviour passed from Blocked to Ready (this - * flag is the truth value of the predicate 'The behaviour - * has now become runnable'. - * @param d A notification direction: when direction is - * NOTIFY_UP, the event travels upwards the behaviour - * containment hierarchy; when it is NOTIFY_DOWN, the - * event travels downwards. - */ - public void init(boolean b, int d) { - runnable = b; - direction = d; - } - - - /** - * Read event source. - * - * @return The Behaviour object which generated this event. - */ - public Behaviour getSource() { - return Behaviour.this; - } - - /** - * Check whether the event is runnable. - * - * @return true when the behaviour generating this - * event has become Ready, false when it has - * become Blocked. - */ - public boolean isRunnable() { - return runnable; - } - - /** - * Check which direction this event is travelling. - * - * @return true when the event is a notification - * going from a child behaviour to its parent; false - * otherwise. - */ - public boolean isUpwards() { - return direction == NOTIFY_UP; - } - - } // End of RunnableChangedEvent class - - - //#APIDOC_EXCLUDE_END - - - private String myName; - private boolean startFlag = true; - + protected static final int NOTIFY_UP = -1; + /** + * A constant for parent-to-child notifications. + * + * @serial + */ + protected static final int NOTIFY_DOWN = 1; + @Serial + private static final long serialVersionUID = 3487495895819001L; /** * The agent this behaviour belongs to. *

@@ -178,20 +89,25 @@ public boolean isUpwards() { */ protected Agent myAgent; + + //#APIDOC_EXCLUDE_END + /** + * This event object will be re-used for every state change + * notification. + */ + protected RunnableChangedEvent myEvent = new RunnableChangedEvent(); + //#APIDOC_EXCLUDE_BEGIN + protected CompositeBehaviour parent; + private String myName; + private boolean startFlag = true; /** * Flag indicating whether this Behaviour is runnable or not */ private volatile boolean runnableState = true; private volatile long restartCounter = 0; - private volatile String executionState = STATE_READY; //#APIDOC_EXCLUDE_BEGIN - - /** - * This event object will be re-used for every state change - * notification. - */ - protected RunnableChangedEvent myEvent = new RunnableChangedEvent(); + private volatile String executionState = STATE_READY; //#APIDOC_EXCLUDE_END @@ -204,41 +120,7 @@ public boolean isUpwards() { * map key - message */ private HashMap mapMessages; - - void setParent(CompositeBehaviour cb) { - parent = cb; - if (parent != null) { - myAgent = parent.myAgent; - } - wrappedParent = null; - } - - void setWrappedParent(CompositeBehaviour cb) { - wrappedParent = cb; - } - private CompositeBehaviour wrappedParent; - //#APIDOC_EXCLUDE_BEGIN - protected CompositeBehaviour parent; - //#APIDOC_EXCLUDE_END - - /** - * Retrieve the enclosing CompositeBehaviour (if present). In order to access the parent behaviour - * it is strongly suggested to use this method rather than the parent member variable - * directly. In case of threaded or wrapped behaviour in facts the latter may have unexpected values. - * - * @return The enclosing CompositeBehaviour (if present). - * see CompositeBehaviour - */ - protected CompositeBehaviour getParent() { - if (wrappedParent != null) { - return wrappedParent; - } else { - return parent; - } - } - //#CUSTOM_EXCLUDE_END - /** * Default constructor. It does not set the agent owning this @@ -268,13 +150,34 @@ public Behaviour(Agent a) { myAgent = a; } + void setWrappedParent(CompositeBehaviour cb) { + wrappedParent = cb; + } + //#APIDOC_EXCLUDE_END + /** - * Give a name to this behaviour object. + * Retrieve the enclosing CompositeBehaviour (if present). In order to access the parent behaviour + * it is strongly suggested to use this method rather than the parent member variable + * directly. In case of threaded or wrapped behaviour in facts the latter may have unexpected values. * - * @param name The name to give to this behaviour. + * @return The enclosing CompositeBehaviour (if present). + * see CompositeBehaviour */ - public final void setBehaviourName(String name) { - myName = name; + protected CompositeBehaviour getParent() { + if (wrappedParent != null) { + return wrappedParent; + } else { + return parent; + } + } + //#CUSTOM_EXCLUDE_END + + void setParent(CompositeBehaviour cb) { + parent = cb; + if (parent != null) { + myAgent = parent.myAgent; + } + wrappedParent = null; } /** @@ -288,6 +191,15 @@ public final String getBehaviourName() { return myName; } + /** + * Give a name to this behaviour object. + * + * @param name The name to give to this behaviour. + */ + public final void setBehaviourName(String name) { + myName = name; + } + /** * Runs the behaviour. This abstract method must be implemented by * Behavioursubclasses to perform ordinary behaviour @@ -346,8 +258,6 @@ public int onEnd() { public void onStart() { } - //#APIDOC_EXCLUDE_BEGIN - /** * This method is called internally by the JADE framework * and should not be called by the user. @@ -372,15 +282,15 @@ public final void actionWrapper() { //#MIDP_EXCLUDE_END } - public final void setExecutionState(String s) { - executionState = s; - } + //#APIDOC_EXCLUDE_BEGIN public final String getExecutionState() { return executionState; } - //#APIDOC_EXCLUDE_END + public final void setExecutionState(String s) { + executionState = s; + } /** * Restores behaviour initial state. This method must be implemented @@ -396,8 +306,7 @@ public void reset() { startFlag = true; restart(); } - - //#APIDOC_EXCLUDE_BEGIN + //#APIDOC_EXCLUDE_END /** * Handler for block/restart events. This method handles @@ -419,7 +328,8 @@ protected void handle(RunnableChangedEvent rce) { } //#CUSTOM_EXCLUDE_END } - //#APIDOC_EXCLUDE_END + + //#APIDOC_EXCLUDE_BEGIN /** * Returns the root for this Behaviour object. That is, @@ -441,14 +351,7 @@ public Behaviour root() { //#CUSTOM_EXCLUDE_END return this; } - - // Sets the runnable/not-runnable state - void setRunnable(boolean runnable) { - runnableState = runnable; - if (runnableState) { - restartCounter++; - } - } + //#APIDOC_EXCLUDE_END /** * Returns whether this Behaviour object is blocked or @@ -461,7 +364,13 @@ public boolean isRunnable() { return runnableState; } - //#APIDOC_EXCLUDE_BEGIN + // Sets the runnable/not-runnable state + void setRunnable(boolean runnable) { + runnableState = runnable; + if (runnableState) { + restartCounter++; + } + } /** * This method is used internally by the framework. Developer should not call or redefine it. @@ -469,7 +378,8 @@ public boolean isRunnable() { public final long getRestartCounter() { return restartCounter; } - //#APIDOC_EXCLUDE_END + + //#APIDOC_EXCLUDE_BEGIN /** * Blocks this behaviour. It should be noticed that this method is NOT a @@ -488,8 +398,7 @@ public final long getRestartCounter() { public void block() { handleBlockEvent(); } - - //#APIDOC_EXCLUDE_BEGIN + //#APIDOC_EXCLUDE_END /** * This method is used internally by the framework. Developer should not call or redefine it. @@ -498,8 +407,8 @@ protected void handleBlockEvent() { myEvent.init(false, NOTIFY_UP); handle(myEvent); } - //#APIDOC_EXCLUDE_END + //#APIDOC_EXCLUDE_BEGIN /** * Blocks this behaviour for a specified amount of time. The @@ -533,6 +442,7 @@ public void block(long millis) { myAgent.restartLater(this, millis); } } + //#APIDOC_EXCLUDE_END /** * Restarts a blocked behaviour. This method fires a suitable event @@ -555,8 +465,6 @@ public void restart() { } } - //#APIDOC_EXCLUDE_BEGIN - /** * This method is used internally by the framework. Developer should not call or redefine it. */ @@ -564,8 +472,13 @@ public void handleRestartEvent() { myEvent.init(true, NOTIFY_UP); handle(myEvent); } - //#APIDOC_EXCLUDE_END + //#APIDOC_EXCLUDE_BEGIN + + public Agent getAgent() { + return myAgent; + } + //#APIDOC_EXCLUDE_END /** * Associates this behaviour with the agent it belongs to. There is @@ -580,13 +493,6 @@ public void setAgent(Agent a) { myAgent = a; } - public Agent getAgent() { - return myAgent; - } - - - //#CUSTOM_EXCLUDE_BEGIN - /** * Return the private map of list of messages of this Behaviour. * If it was null, a new HashMap is created and returned. @@ -601,6 +507,18 @@ public HashMap> getMapMessagesList() { } + //#CUSTOM_EXCLUDE_BEGIN + + /** + * Set the private map of list of messages of this Behaviour + * + * @param map the HashMap that this Behaviour + * will use as its private map of list of messages + */ + public void setMapMessagesList(HashMap> map) { + mapMessagesList = map; + } + /** * Return the private map of messages of this Behaviour. * If it was null, a new HashMap is created and returned. @@ -614,17 +532,6 @@ public HashMap getMapMessages() { return mapMessages; } - - /** - * Set the private map of list of messages of this Behaviour - * - * @param map the HashMap that this Behaviour - * will use as its private map of list of messages - */ - public void setMapMessagesList(HashMap> map) { - mapMessagesList = map; - } - /** * Set the private map of messages of this Behaviour * @@ -635,5 +542,80 @@ public void setMapMessages(HashMap map) { mapMessages = map; } + /** + * Event class for notifying blocked and restarted behaviours. + * This class is used to notify interested behaviours when a + * Behaviour changes its runnable state. It may be sent to + * behaviour's parent (upward notification or to behaviour's + * children (downward notification). + */ + protected class RunnableChangedEvent implements Serializable { + @Serial + private static final long serialVersionUID = 3487495895819002L; + /** + * @serial + */ + private boolean runnable; + + /** + * @serial + */ + private int direction; + + /** + * Re-init event content. This method can be used to rewrite an + * existing event with new data (much cheaper than making a new + * object). + * + * @param b A boolean flag; when false + * it means that a behaviour passed from Ready to + * Blocked state. When true it means that a + * behaviour passed from Blocked to Ready (this + * flag is the truth value of the predicate 'The behaviour + * has now become runnable'. + * @param d A notification direction: when direction is + * NOTIFY_UP, the event travels upwards the behaviour + * containment hierarchy; when it is NOTIFY_DOWN, the + * event travels downwards. + */ + public void init(boolean b, int d) { + runnable = b; + direction = d; + } + + + /** + * Read event source. + * + * @return The Behaviour object which generated this event. + */ + public Behaviour getSource() { + return Behaviour.this; + } + + /** + * Check whether the event is runnable. + * + * @return true when the behaviour generating this + * event has become Ready, false when it has + * become Blocked. + */ + public boolean isRunnable() { + return runnable; + } + + /** + * Check which direction this event is travelling. + * + * @return true when the event is a notification + * going from a child behaviour to its parent; false + * otherwise. + */ + public boolean isUpwards() { + return direction == NOTIFY_UP; + } + + } // End of RunnableChangedEvent class + //#CUSTOM_EXCLUDE_END } diff --git a/src/jade/core/behaviours/CompositeBehaviour.java b/src/jade/core/behaviours/CompositeBehaviour.java index 394a082..b05be5f 100644 --- a/src/jade/core/behaviours/CompositeBehaviour.java +++ b/src/jade/core/behaviours/CompositeBehaviour.java @@ -45,6 +45,8 @@ */ public abstract class CompositeBehaviour extends Behaviour { + //#APIDOC_EXCLUDE_BEGIN + protected boolean currentExecuted = false; /** * This variable marks the state when no child-behaviour has been run yet. */ @@ -53,12 +55,8 @@ public abstract class CompositeBehaviour extends Behaviour { * This variable marks the state when all child-behaviours have been run. */ private boolean finished = false; - private boolean currentDone; private int currentResult; - - //#APIDOC_EXCLUDE_BEGIN - protected boolean currentExecuted = false; //#APIDOC_EXCLUDE_END diff --git a/src/jade/core/behaviours/FSMBehaviour.java b/src/jade/core/behaviours/FSMBehaviour.java index 638aa46..5bb501f 100644 --- a/src/jade/core/behaviours/FSMBehaviour.java +++ b/src/jade/core/behaviours/FSMBehaviour.java @@ -65,22 +65,19 @@ public class FSMBehaviour extends SerialBehaviour { private final Map mapStates = new HashMap<>(); - private Behaviour current = null; + private final TransitionTable theTransitionTable = new TransitionTable(); + //#J2ME_EXCLUDE_BEGIN + private final Logger myLogger = Logger.getMyLogger(FSMBehaviour.class.getName()); // Protected for debugging purposes only protected List lastStates = new ArrayList<>(); protected String currentName = null; + private Behaviour current = null; private String previousName = null; private String firstName = null; private int lastExitValue; - // These variables are used to force a transition on a given state at runtime private boolean transitionForced = false; private String forcedTransitionDest = null; - - private final TransitionTable theTransitionTable = new TransitionTable(); - - //#J2ME_EXCLUDE_BEGIN - private final Logger myLogger = Logger.getMyLogger(FSMBehaviour.class.getName()); //#J2ME_EXCLUDE_END /** @@ -483,98 +480,24 @@ public void resetStates(String[] states) { } } - - /** - * Inner class implementing the FSM transition table - */ - class TransitionTable implements Serializable { - private final Hashtable transitions = new Hashtable<>(); - @Serial - private static final long serialVersionUID = 3487495895819003L; - - void clear() { - transitions.clear(); - } - - void addTransition(Transition t) { - String key1 = t.getFromState(); - - TransitionsFromState tfs = transitions.get(key1); - - if (tfs == null) { - tfs = new TransitionsFromState(); - transitions.put(key1, tfs); - } - - if (t.isDefault()) { - tfs.setDefaultTransition(t); - } else { - Integer key2 = t.getTrigger(); - tfs.put(key2, t); - } - } - - void removeTransition(String s1, int event) { - TransitionsFromState tfs = transitions.get(s1); - if (tfs != null) { - Transition t = (Transition) tfs.remove(event); - if (t != null) { - - if ((tfs.isEmpty() && (tfs.getDefaultTransition() == null))) { - transitions.remove(s1); - } - } - } - } - - void removeTransition(String s1) { - TransitionsFromState tfs = transitions.get(s1); - if (tfs != null) { - tfs.setDefaultTransition(null); - - if (tfs.isEmpty()) { - transitions.remove(s1); - } - } - } - - Transition getTransition(String s, int event) { - TransitionsFromState tfs = transitions.get(s); - if (tfs != null) { - return (Transition) tfs.get(event); - } else { - return null; - } - } - - Transition getTransition(String s) { - TransitionsFromState tfs = transitions.get(s); - if (tfs != null) { - return tfs.getDefaultTransition(); - } else { - return null; - } - } - - void removeTransitionsFromState(String stateName) { - transitions.remove(stateName); - } + //#MIDP_EXCLUDE_BEGIN + public String stringifyTransitionTable() { + return theTransitionTable.transitions.toString(); } - /** * Inner class Transition */ static class Transition implements Serializable { + @Serial + private static final long serialVersionUID = 3487495895819004L; private FSMBehaviour fsm; private String src; private String dest; private int trigger; private boolean def; private String[] toBeReset; - @Serial - private static final long serialVersionUID = 3487495895819004L; public Transition() { } @@ -652,23 +575,99 @@ public String toString() { //#MIDP_EXCLUDE_END } // END of inner class Transition + /** + * Inner class implementing the FSM transition table + */ + class TransitionTable implements Serializable { + @Serial + private static final long serialVersionUID = 3487495895819003L; + private final Hashtable transitions = new Hashtable<>(); + + void clear() { + transitions.clear(); + } + + void addTransition(Transition t) { + String key1 = t.getFromState(); + + TransitionsFromState tfs = transitions.get(key1); + + if (tfs == null) { + tfs = new TransitionsFromState(); + transitions.put(key1, tfs); + } + + if (t.isDefault()) { + tfs.setDefaultTransition(t); + } else { + Integer key2 = t.getTrigger(); + tfs.put(key2, t); + } + } + + void removeTransition(String s1, int event) { + TransitionsFromState tfs = transitions.get(s1); + if (tfs != null) { + Transition t = (Transition) tfs.remove(event); + if (t != null) { + + if ((tfs.isEmpty() && (tfs.getDefaultTransition() == null))) { + transitions.remove(s1); + } + } + } + } + + void removeTransition(String s1) { + TransitionsFromState tfs = transitions.get(s1); + if (tfs != null) { + tfs.setDefaultTransition(null); + + if (tfs.isEmpty()) { + transitions.remove(s1); + } + } + } + + Transition getTransition(String s, int event) { + TransitionsFromState tfs = transitions.get(s); + if (tfs != null) { + return (Transition) tfs.get(event); + } else { + return null; + } + } + + Transition getTransition(String s) { + TransitionsFromState tfs = transitions.get(s); + if (tfs != null) { + return tfs.getDefaultTransition(); + } else { + return null; + } + } + + void removeTransitionsFromState(String stateName) { + transitions.remove(stateName); + } + } /** * Inner class TransitionsFromState */ class TransitionsFromState extends Hashtable { - private Transition defaultTransition = null; @Serial private static final long serialVersionUID = 3487495895819005L; - - void setDefaultTransition(Transition dt) { - defaultTransition = dt; - } + private Transition defaultTransition = null; Transition getDefaultTransition() { return defaultTransition; } + void setDefaultTransition(Transition dt) { + defaultTransition = dt; + } + public Object get(Object key) { Transition t = (Transition) super.get(key); if (t == null) { @@ -689,10 +688,5 @@ public String toString() { } //#MIDP_EXCLUDE_END } // END of inner class TransitionsFromState - - //#MIDP_EXCLUDE_BEGIN - public String stringifyTransitionTable() { - return theTransitionTable.transitions.toString(); - } //#MIDP_EXCLUDE_END } diff --git a/src/jade/core/behaviours/LoaderBehaviour.java b/src/jade/core/behaviours/LoaderBehaviour.java index d802794..a9aa801 100644 --- a/src/jade/core/behaviours/LoaderBehaviour.java +++ b/src/jade/core/behaviours/LoaderBehaviour.java @@ -73,8 +73,6 @@ public class LoaderBehaviour extends Behaviour { private final Codec codec = new LEAPCodec(); private final Ontology onto = BehaviourLoadingOntology.getInstance(); private final ContentManager myContentManager = new ContentManager(); - private ClassLoader localLoader; - private final MessageTemplate myTemplate = MessageTemplate.and( MessageTemplate.MatchPerformative(ACLMessage.REQUEST), MessageTemplate.and( @@ -82,7 +80,7 @@ public class LoaderBehaviour extends Behaviour { MessageTemplate.MatchOntology(onto.getName()) ) ); - + private ClassLoader localLoader; private boolean finished = false; /** @@ -276,6 +274,28 @@ private Behaviour load(String className, Hashtable classes) thro return b; } + protected void setInputParameters(Behaviour b, List params) { + var ds = b.getMapMessages(); + if (params != null) { + for (Parameter param : params) { + if (param.getMode() == Parameter.IN_MODE || param.getMode() == Parameter.INOUT_MODE) { + ds.put(param.getName(), (ACLMessage)param.getValue()); + } + } + } + } + + protected void getOutputParameters(Behaviour b, List params) { + var ds = b.getMapMessages(); + if (params != null) { + for (Parameter param : params) { + if (param.getMode() == Parameter.OUT_MODE || param.getMode() == Parameter.INOUT_MODE) { + param.setValue(ds.get(param.getName())); + } + } + } + } + /** * Inner class HashClassLoader */ @@ -306,7 +326,7 @@ protected Class findClass(String name) throws ClassNotFoundException { protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException { // 1) Try to see if the class has already been loaded Class c = findLoadedClass(name); - + // 2) Try to load the class using the system class loader if(c == null) { try { @@ -315,46 +335,21 @@ protected Class loadClass(String name, boolean resolve) throws ClassNotFoundExce catch (ClassNotFoundException cnfe) { } } - + // 3) If still not found, try to load the class from the code if(c == null) { c = findClass(name); } - + if(resolve) { resolveClass(c); } - + return c; } #PJAVA_INCLUDE_END*/ } // END of inner class HashClassLoader - - protected void setInputParameters(Behaviour b, List params) { - HashMap ds = b.getMapMessages(); - if (params != null) { - for (Parameter param : params) { - if (param.getMode() == Parameter.IN_MODE || param.getMode() == Parameter.INOUT_MODE) { - ds.put(param.getName(), param.getValue()); - } - } - } - } - - protected void getOutputParameters(Behaviour b, List params) { - HashMap ds = b.getMapMessages(); - if (params != null) { - for (Object param : params) { - Parameter p = (Parameter) param; - if (p.getMode() == Parameter.OUT_MODE || p.getMode() == Parameter.INOUT_MODE) { - p.setValue(ds.get(p.getName())); - } - } - } - } - - /** * Inner class ResultCollector. * This behaviour restores the output parameters at the end of @@ -363,9 +358,9 @@ protected void getOutputParameters(Behaviour b, List params) { */ private class ResultCollector extends OneShotBehaviour { private final Behaviour myBehaviour; - private List myParams; private final Action actionExpr; private final ACLMessage request; + private List myParams; ResultCollector(Behaviour b, List l, Action a, ACLMessage m) { super(); diff --git a/src/jade/core/behaviours/OntologyServer.java b/src/jade/core/behaviours/OntologyServer.java index c16a1a4..8aa15cc 100644 --- a/src/jade/core/behaviours/OntologyServer.java +++ b/src/jade/core/behaviours/OntologyServer.java @@ -80,19 +80,16 @@ public class OntologyServer extends CyclicBehaviour { private final Object serverDelegate; private final Ontology onto; - private Codec codec; private final int[] servedPerformatives; - + private final Set performativesRequiringReply = new HashSet<>(); + protected Logger myLogger = Logger.getMyLogger(getClass().getName()); + private Codec codec; private ConversationList ignoredConversations; private boolean printFullUnexpectedMessages = true; private MessageTemplate template; - private final Set performativesRequiringReply = new HashSet<>(); - private transient Map cachedMethods = new HashMap<>(); private ContentElement receivedContentElement; - protected Logger myLogger = Logger.getMyLogger(getClass().getName()); - public OntologyServer(Agent a, Ontology onto, int performative) { this(a, onto, new int[]{performative}, null); } @@ -144,6 +141,10 @@ public void setMessageTemplate(MessageTemplate template) { this.template = template; } + public ConversationList getIgnoredConversations() { + return ignoredConversations; + } + /** * Set the ConversationList used by this OntologyServer * to determine which conversations to ignore (if any). @@ -156,10 +157,6 @@ public void setIgnoredConversations(ConversationList l) { } } - public ConversationList getIgnoredConversations() { - return ignoredConversations; - } - /** * If an unexpected error occurs in one of the serving methods or if a suitable serving method * is not found for an incoming message, the OntologyServer automatically sends back a FAILURE diff --git a/src/jade/core/behaviours/OutcomeManager.java b/src/jade/core/behaviours/OutcomeManager.java index 8c16f2c..719e72e 100644 --- a/src/jade/core/behaviours/OutcomeManager.java +++ b/src/jade/core/behaviours/OutcomeManager.java @@ -36,19 +36,15 @@ * @author Giovanni Caire */ public class OutcomeManager implements Serializable { - @Serial - private static final long serialVersionUID = -87842234567654L; - public static final int OK = 1; public static final int KO = 0; - + @Serial + private static final long serialVersionUID = -87842234567654L; private final Behaviour bh; - + private final Logger myLogger = Logger.getJADELogger(getClass().getName()); private int exitCode = OK; private String errorMsg; - private final Logger myLogger = Logger.getJADELogger(getClass().getName()); - public OutcomeManager(Behaviour bh) { this.bh = bh; } diff --git a/src/jade/core/behaviours/ReceiverBehaviour.java b/src/jade/core/behaviours/ReceiverBehaviour.java index e682835..2434b9e 100644 --- a/src/jade/core/behaviours/ReceiverBehaviour.java +++ b/src/jade/core/behaviours/ReceiverBehaviour.java @@ -43,145 +43,35 @@ */ public final class ReceiverBehaviour extends Behaviour { - /** - * Exception class for timeouts. This exception is thrown when trying - * to obtain an ACLMessage object from an - * Handle, but no message was received within a specified - * timeout. - * - * @see Handle#getMessage() - */ - public static class TimedOut extends Exception { - TimedOut() { - super("No message was received before time limit."); - } - } - - /** - * Exception class for timeouts. This exception is thrown when trying - * to obtain an ACLMessage from an Handle - * and no message was received so far, but the time limit is not yet - * reached. - * - * @see Handle#getMessage() - */ - public static class NotYetReady extends Exception { - NotYetReady() { - super("Requested message is not ready yet."); - } - } - - /** - * An interface representing ACL messages due to arrive within a time - * limit. This interface is used to create a - * ReceiverBehaviour object to receive an ACL message - * within a user specified time limit. When the user tries to read the - * message represented by the handle, either gets it or gets an - * exception. - * - * @see ReceiverBehaviour#newHandle() - * @see ReceiverBehaviour#ReceiverBehaviour(Agent - * a, Handle h, long millis) - */ - public interface Handle { - - /** - * Tries to retrieve the ACLMessage object represented - * by this handle. - * - * @return The ACL message, received by the associated - * ReceiverBehaviour, if any. - * @throws TimedOut If the associated - * ReceiverBehaviour did not receive a suitable ACL - * message within the time limit. - * @throws NotYetReady If the associated - * ReceiverBehaviour is still waiting for a suitable - * ACL message to arrive. - * @see ReceiverBehaviour#ReceiverBehaviour(Agent - * a, Handle h, long millis) - */ - ACLMessage getMessage() throws TimedOut, NotYetReady; - - } - - private static class MessageFuture implements Handle, Serializable { - - private static final int OK = 0; - private static final int NOT_YET = 1; - private static final int TIMED_OUT = 2; - - private int state = NOT_YET; - private ACLMessage message; - - public void reset() { - message = null; - state = NOT_YET; - } - - public void setMessage(ACLMessage msg) { - message = msg; - if (message != null) - state = OK; - else - state = TIMED_OUT; - } - - public ACLMessage getMessage() throws TimedOut, NotYetReady { - return switch (state) { - case NOT_YET -> throw new NotYetReady(); - case TIMED_OUT -> throw new TimedOut(); - default -> message; - }; - } - } - - /** - * Factory method for message handles. This method returns a new - * Handle object, which can be used to retrieve an ACL - * message out of a ReceiverBehaviour object. - * - * @return A new Handle object. - * @see Handle - */ - public static Handle newHandle() { - return new MessageFuture(); - } - - - // The pattern to match incoming messages against /** * @serial */ private final MessageTemplate template; - - // A future for the ACL message, used when a timeout was specified /** * @serial */ private final MessageFuture future; - - // A time out value, when present /** * @serial */ private final long timeOut; - - // A running counter for calling block(millis) until 'timeOut' milliseconds pass. /** * @serial */ private long timeToWait; - - // Timestamp holder, used when calling block(millis) many times. /** * @serial */ private long blockingTime = 0; + + + // The pattern to match incoming messages against /** * @serial */ private boolean finished; + // A future for the ACL message, used when a timeout was specified /** * This constructor creates a * ReceiverBehaviour object that ends as soon as an ACL @@ -201,7 +91,7 @@ public ReceiverBehaviour(Agent a, long millis, MessageTemplate mt) { this(a, newHandle(), millis, mt); } - + // A time out value, when present /** * Receive any ACL message, waiting at most millis * milliseconds (infinite time if millis < 1). @@ -243,6 +133,7 @@ public ReceiverBehaviour(Agent a, Handle h, long millis) { this(a, h, millis, null); } + // A running counter for calling block(millis) until 'timeOut' milliseconds pass. /** * Receive any ACL message matching the given template, witing at * most millis milliseconds (infinite time if @@ -265,6 +156,20 @@ public ReceiverBehaviour(Agent a, Handle h, long millis, MessageTemplate mt) { template = mt; } + // Timestamp holder, used when calling block(millis) many times. + + /** + * Factory method for message handles. This method returns a new + * Handle object, which can be used to retrieve an ACL + * message out of a ReceiverBehaviour object. + * + * @return A new Handle object. + * @see Handle + */ + public static Handle newHandle() { + return new MessageFuture(); + } + /** * Actual behaviour implementation. This method receives a suitable * ACL message and copies it into the message provided by the @@ -324,7 +229,6 @@ public void reset() { super.reset(); } - /** * This method allows the caller to get the received message. * @@ -338,4 +242,96 @@ public void reset() { public ACLMessage getMessage() throws TimedOut, NotYetReady { return future.getMessage(); } + + /** + * An interface representing ACL messages due to arrive within a time + * limit. This interface is used to create a + * ReceiverBehaviour object to receive an ACL message + * within a user specified time limit. When the user tries to read the + * message represented by the handle, either gets it or gets an + * exception. + * + * @see ReceiverBehaviour#newHandle() + * @see ReceiverBehaviour#ReceiverBehaviour(Agent + * a, Handle h, long millis) + */ + public interface Handle { + + /** + * Tries to retrieve the ACLMessage object represented + * by this handle. + * + * @return The ACL message, received by the associated + * ReceiverBehaviour, if any. + * @throws TimedOut If the associated + * ReceiverBehaviour did not receive a suitable ACL + * message within the time limit. + * @throws NotYetReady If the associated + * ReceiverBehaviour is still waiting for a suitable + * ACL message to arrive. + * @see ReceiverBehaviour#ReceiverBehaviour(Agent + * a, Handle h, long millis) + */ + ACLMessage getMessage() throws TimedOut, NotYetReady; + + } + + /** + * Exception class for timeouts. This exception is thrown when trying + * to obtain an ACLMessage object from an + * Handle, but no message was received within a specified + * timeout. + * + * @see Handle#getMessage() + */ + public static class TimedOut extends Exception { + TimedOut() { + super("No message was received before time limit."); + } + } + + /** + * Exception class for timeouts. This exception is thrown when trying + * to obtain an ACLMessage from an Handle + * and no message was received so far, but the time limit is not yet + * reached. + * + * @see Handle#getMessage() + */ + public static class NotYetReady extends Exception { + NotYetReady() { + super("Requested message is not ready yet."); + } + } + + private static class MessageFuture implements Handle, Serializable { + + private static final int OK = 0; + private static final int NOT_YET = 1; + private static final int TIMED_OUT = 2; + + private int state = NOT_YET; + private ACLMessage message; + + public void reset() { + message = null; + state = NOT_YET; + } + + public ACLMessage getMessage() throws TimedOut, NotYetReady { + return switch (state) { + case NOT_YET -> throw new NotYetReady(); + case TIMED_OUT -> throw new TimedOut(); + default -> message; + }; + } + + public void setMessage(ACLMessage msg) { + message = msg; + if (message != null) + state = OK; + else + state = TIMED_OUT; + } + } } diff --git a/src/jade/core/behaviours/ThreadedBehaviourFactory.java b/src/jade/core/behaviours/ThreadedBehaviourFactory.java index a25f8ac..20371c5 100644 --- a/src/jade/core/behaviours/ThreadedBehaviourFactory.java +++ b/src/jade/core/behaviours/ThreadedBehaviourFactory.java @@ -25,12 +25,14 @@ import jade.core.Agent; import jade.core.NotFoundException; +import jade.lang.acl.ACLMessage; import jade.util.Logger; import java.lang.reflect.Method; import java.util.Enumeration; import java.util.HashMap; import java.util.Vector; +import java.util.List; /** * This class provides support for executing JADE Behaviours @@ -203,13 +205,25 @@ private ThreadedBehaviourWrapper getWrapper(Behaviour b) { } } + private void invokeMethod(Object obj, String methodName) { + try { + Method m = obj.getClass().getMethod(methodName); + m.invoke(obj); + } catch (NoSuchMethodException nsme) { + // Callback method not defined. Just do nothing + } catch (Exception e) { + myLogger.log(Logger.WARNING, "Error invoking callback method " + methodName, e); + } + } + //#APIDOC_EXCLUDE_END + /** * Inner class ThreadedBehaviourWrapper * This class is declared public for debugging purpose only */ public class ThreadedBehaviourWrapper extends Behaviour implements Runnable { - private Thread myThread; private final Behaviour myBehaviour; + private Thread myThread; private volatile boolean restarted = false; private boolean finished = false; private volatile boolean suspended = false; @@ -271,12 +285,11 @@ protected void setParent(CompositeBehaviour parent) { myBehaviour.setWrappedParent(parent); } - public void setMapMessagesList(HashMap ds) { - myBehaviour.setMapMessagesList(ds); - } + public HashMap> getMapMessagesList() { + return myBehaviour.getMapMessagesList();} - public HashMap getMapMessagesList() { - return myBehaviour.getMapMessagesList(); + public void setMapMessagesList(HashMap> ds) { + myBehaviour.setMapMessagesList(ds); } public void reset() { @@ -467,18 +480,6 @@ public final String getThreadState() { return threadState; } } // END of inner class ThreadedBehaviourWrapper - //#APIDOC_EXCLUDE_END - - private void invokeMethod(Object obj, String methodName) { - try { - Method m = obj.getClass().getMethod(methodName); - m.invoke(obj); - } catch (NoSuchMethodException nsme) { - // Callback method not defined. Just do nothing - } catch (Exception e) { - myLogger.log(Logger.WARNING, "Error invoking callback method " + methodName, e); - } - } /** * Inner class DummyParentBehaviour. diff --git a/src/jade/core/behaviours/TickerBehaviour.java b/src/jade/core/behaviours/TickerBehaviour.java index 21254f9..81d1c84 100644 --- a/src/jade/core/behaviours/TickerBehaviour.java +++ b/src/jade/core/behaviours/TickerBehaviour.java @@ -152,15 +152,15 @@ public final int getTickCount() { return tickCount; } - protected long getPeriod() { - return period; - } - //#MIDP_EXCLUDE_BEGIN - // For persistence service private void setTickCount(int tc) { tickCount = tc; } + //#MIDP_EXCLUDE_BEGIN + + protected long getPeriod() { + return period; + } // For persistence service private void setPeriod(long p) { @@ -168,13 +168,13 @@ private void setPeriod(long p) { } // For persistence service - private void setWakeupTime(long wt) { - wakeupTime = wt; + private long getWakeupTime() { + return wakeupTime; } // For persistence service - private long getWakeupTime() { - return wakeupTime; + private void setWakeupTime(long wt) { + wakeupTime = wt; } diff --git a/src/jade/core/behaviours/WrapperBehaviour.java b/src/jade/core/behaviours/WrapperBehaviour.java index c2ec874..bc347fa 100644 --- a/src/jade/core/behaviours/WrapperBehaviour.java +++ b/src/jade/core/behaviours/WrapperBehaviour.java @@ -1,8 +1,10 @@ package jade.core.behaviours; import jade.core.Agent; +import jade.lang.acl.ACLMessage; import java.util.HashMap; +import java.util.List; /** * This behaviour allows modifying on the fly the way an existing behaviour object works @@ -108,12 +110,12 @@ void setParent(CompositeBehaviour parent) { wrappedBehaviour.setWrappedParent(parent); } - public void setMapMessagesList(HashMap ds) { - wrappedBehaviour.setMapMessagesList(ds); + public HashMap> getMapMessagesList() { + return wrappedBehaviour.getMapMessagesList(); } - public HashMap getMapMessagesList() { - return wrappedBehaviour.getMapMessagesList(); + public void setMapMessagesList(HashMap> ds) { + wrappedBehaviour.setMapMessagesList(ds); } public void reset() { diff --git a/src/jade/core/event/NotificationProxy.java b/src/jade/core/event/NotificationProxy.java index e385885..033aa6a 100644 --- a/src/jade/core/event/NotificationProxy.java +++ b/src/jade/core/event/NotificationProxy.java @@ -46,7 +46,7 @@ public void sniffOn(AID snifferName, AID targetName) throws IMTPException { Node n = getNode(); Object result = n.accept(cmd); - if ((result != null) && (result instanceof Throwable)) { + if ((result instanceof Throwable)) { if (result instanceof IMTPException) { throw (IMTPException) result; } else { @@ -67,7 +67,7 @@ public void sniffOff(AID snifferName, AID targetName) throws IMTPException { Node n = getNode(); Object result = n.accept(cmd); - if ((result != null) && (result instanceof Throwable)) { + if ((result instanceof Throwable)) { if (result instanceof IMTPException) { throw (IMTPException) result; } else { @@ -88,7 +88,7 @@ public void debugOn(AID introspectorName, AID targetName) throws IMTPException { Node n = getNode(); Object result = n.accept(cmd); - if ((result != null) && (result instanceof Throwable)) { + if ((result instanceof Throwable)) { if (result instanceof IMTPException) { throw (IMTPException) result; } else { @@ -109,7 +109,7 @@ public void debugOff(AID introspectorName, AID targetName) throws IMTPException Node n = getNode(); Object result = n.accept(cmd); - if ((result != null) && (result instanceof Throwable)) { + if ((result instanceof Throwable)) { if (result instanceof IMTPException) { throw (IMTPException) result; } else { diff --git a/src/jade/core/event/NotificationService.java b/src/jade/core/event/NotificationService.java index 7a82753..1e34d22 100644 --- a/src/jade/core/event/NotificationService.java +++ b/src/jade/core/event/NotificationService.java @@ -65,31 +65,24 @@ public class NotificationService extends BaseService { // The special name of an auxiliary thread used to avoid deadlock when debugging the AMS private final static String AMS_DEBUG_HELPER = "AMS-debug-helper"; - - // The concrete agent container, providing access to LADT, etc. - private AgentContainer myContainer; - - // The local slice for this service - private ServiceComponent localSlice; private final Sink sourceSink = new NotificationSourceSink(); private final Filter outgoingFilter = new NotificationOutgoingFilter(); private final Filter incomingFilter = new NotificationIncomingFilter(); private final NotificationHelper helper = new NotificationHelperImpl(); - // The list of all listeners of ACL messaging related events (uses RW-locking) private final SynchList messageListeners = new SynchList(); - // The list of all listeners of agent life cycle events (uses RW-locking) private final SynchList agentListeners = new SynchList(); - // The list of all listeners of container events (uses RW-locking) private final SynchList containerListeners = new SynchList(); - // This maps a debugged agent into the list of debuggers that are // currently debugging it. It is used to know when an agent is no longer // debugged by any debugger and behaviour event generation can be turned off. private final Map> debuggers = new HashMap<>(); - + // The concrete agent container, providing access to LADT, etc. + private AgentContainer myContainer; + // The local slice for this service + private ServiceComponent localSlice; public void init(AgentContainer ac, Profile p) throws ProfileException { super.init(ac, p); @@ -135,6 +128,259 @@ public String[] getOwnedCommands() { return OWNED_COMMANDS; } + ///////////////////////////////////// + // Event dispatching methods + ///////////////////////////////////// + private void fireSentMessage(ACLMessage msg, AID sender, AID receiver) { + // NOTE: A normal synchronized block could create deadlock problems + // as it prevents concurrent scannings of the listeners list. + List l = messageListeners.startScanning(); + if (l != null) { + MessageEvent ev = new MessageEvent(MessageEvent.SENT_MESSAGE, msg, sender, receiver, myID()); + for (Object o : l) { + MessageListener ml = (MessageListener) o; + ml.sentMessage(ev); + } + messageListeners.stopScanning(); + } + } + + private void firePostedMessage(ACLMessage msg, AID receiver) { + // Set the sender explicitly only if different than that included in the message + String realSenderName = msg.getUserDefinedParameter(ACLMessage.REAL_SENDER); + AID sender = null; + if (realSenderName != null) { + sender = new AID(realSenderName, AID.ISGUID); + } + // NOTE: A normal synchronized block could create deadlock problems + // as it prevents concurrent scannings of the listeners list. + List l = messageListeners.startScanning(); + if (l != null) { + MessageEvent ev = new MessageEvent(MessageEvent.POSTED_MESSAGE, msg, sender, receiver, myID()); + for (Object o : l) { + MessageListener ml = (MessageListener) o; + ml.postedMessage(ev); + } + messageListeners.stopScanning(); + } + } + + private void fireReceivedMessage(ACLMessage msg, AID receiver) { + // Set the sender explicitly only if different than that included in the message + String realSenderName = msg.getUserDefinedParameter(ACLMessage.REAL_SENDER); + AID sender = null; + if (realSenderName != null) { + sender = new AID(realSenderName, AID.ISGUID); + } + // NOTE: A normal synchronized block could create deadlock problems + // as it prevents concurrent scannings of the listeners list. + List l = messageListeners.startScanning(); + if (l != null) { + MessageEvent ev = new MessageEvent(MessageEvent.RECEIVED_MESSAGE, msg, sender, receiver, myID()); + for (Object o : l) { + MessageListener ml = (MessageListener) o; + ml.receivedMessage(ev); + } + messageListeners.stopScanning(); + } + } + + private void fireRoutedMessage(ACLMessage msg, Channel from, Channel to) { + // NOTE: A normal synchronized block could create deadlock problems + // as it prevents concurrent scannings of the listeners list. + List l = messageListeners.startScanning(); + if (l != null) { + MessageEvent ev = new MessageEvent(MessageEvent.ROUTED_MESSAGE, msg, from, to, myID()); + for (Object o : l) { + MessageListener ml = (MessageListener) o; + ml.routedMessage(ev); + } + messageListeners.stopScanning(); + } + } + + private void fireAddedBehaviour(AID agentID, Behaviour b) { + // NOTE: A normal synchronized block could create deadlock problems + // as it prevents concurrent scannings of the listeners list. + List l = agentListeners.startScanning(); + if (l != null) { + AgentEvent ev = null; + if (b == b.root()) { + // The behaviour has been added to the Agent + ev = new AgentEvent(AgentEvent.ADDED_BEHAVIOUR, agentID, new BehaviourID(b), myID()); + } else { + // The behaviour is actually a new child that has been added to a CompositeBehaviour + //FIXME: TO be done + //ev = new AgentEvent(AgentEvent.ADDED_SUB_BEHAVIOUR, agentID, new BehaviourID(b.getParent()), new BehaviourID(b), myID()); + } + + for (Object o : l) { + AgentListener al = (AgentListener) o; + al.addedBehaviour(ev); + } + agentListeners.stopScanning(); + } + } + + private void fireRemovedBehaviour(AID agentID, Behaviour b) { + // NOTE: A normal synchronized block could create deadlock problems + // as it prevents concurrent scannings of the listeners list. + List l = agentListeners.startScanning(); + if (l != null) { + AgentEvent ev = new AgentEvent(AgentEvent.REMOVED_BEHAVIOUR, agentID, new BehaviourID(b), myID()); + for (Object o : l) { + AgentListener al = (AgentListener) o; + al.removedBehaviour(ev); + } + agentListeners.stopScanning(); + } + } + + private void fireChangedBehaviourState(AID agentID, Behaviour b, String from, String to) { + // NOTE: A normal synchronized block could create deadlock problems + // as it prevents concurrent scannings of the listeners list. + List l = agentListeners.startScanning(); + if (l != null) { + AgentEvent ev = new AgentEvent(AgentEvent.CHANGED_BEHAVIOUR_STATE, agentID, new BehaviourID(b), from, to, myID()); + for (Object o : l) { + AgentListener al = (AgentListener) o; + al.changedBehaviourState(ev); + } + agentListeners.stopScanning(); + } + } + + private void fireChangedAgentPrincipal(AID agentID, JADEPrincipal from, JADEPrincipal to) { + // NOTE: A normal synchronized block could create deadlock problems + // as it prevents concurrent scannings of the listeners list. + List l = agentListeners.startScanning(); + if (l != null) { + AgentEvent ev = new AgentEvent(AgentEvent.CHANGED_AGENT_PRINCIPAL, agentID, from, to, myID()); + for (Object o : l) { + AgentListener al = (AgentListener) o; + al.changedAgentPrincipal(ev); + } + agentListeners.stopScanning(); + } + } + + private void fireChangedAgentState(AID agentID, AgentState from, AgentState to) { + // NOTE: A normal synchronized block could create deadlock problems + // as it prevents concurrent scannings of the listeners list. + List l = agentListeners.startScanning(); + if (l != null) { + AgentEvent ev = new AgentEvent(AgentEvent.CHANGED_AGENT_STATE, agentID, from, to, myID()); + for (Object o : l) { + AgentListener al = (AgentListener) o; + al.changedAgentState(ev); + } + agentListeners.stopScanning(); + } + } + + private void fireBornAgent(AID agentID) { + // NOTE: A normal synchronized block could create deadlock problems + // as it prevents concurrent scannings of the listeners list. + List l = containerListeners.startScanning(); + if (l != null) { + ContainerEvent ev = new ContainerEvent(ContainerEvent.BORN_AGENT, agentID, myID()); + for (Object o : l) { + ContainerListener cl = (ContainerListener) o; + cl.bornAgent(ev); + } + containerListeners.stopScanning(); + } + } + + private void fireDeadAgent(AID agentID) { + // NOTE: A normal synchronized block could create deadlock problems + // as it prevents concurrent scannings of the listeners list. + List l = containerListeners.startScanning(); + if (l != null) { + ContainerEvent ev = new ContainerEvent(ContainerEvent.DEAD_AGENT, agentID, myID()); + for (Object o : l) { + ContainerListener cl = (ContainerListener) o; + cl.deadAgent(ev); + } + containerListeners.stopScanning(); + } + } + + private void fireReattached() { + // NOTE: A normal synchronized block could create deadlock problems + // as it prevents concurrent scannings of the listeners list. + List l = containerListeners.startScanning(); + if (l != null) { + ContainerEvent ev = new ContainerEvent(ContainerEvent.REATTACHED, null, myID()); + for (Object o : l) { + ContainerListener cl = (ContainerListener) o; + cl.reattached(ev); + } + containerListeners.stopScanning(); + } + } + + private void fireReconnected() { + // NOTE: A normal synchronized block could create deadlock problems + // as it prevents concurrent scannings of the listeners list. + List l = containerListeners.startScanning(); + if (l != null) { + ContainerEvent ev = new ContainerEvent(ContainerEvent.RECONNECTED, null, myID()); + for (Object o : l) { + ContainerListener cl = (ContainerListener) o; + cl.reconnected(ev); + } + containerListeners.stopScanning(); + } + } + + private void fireLeadershipAcquired() { + // NOTE: A normal synchronized block could create deadlock problems + // as it prevents concurrent scannings of the listeners list. + List l = containerListeners.startScanning(); + if (l != null) { + ContainerEvent ev = new ContainerEvent(ContainerEvent.LEADERSHIP_ACQUIRED, null, myID()); + for (Object o : l) { + ContainerListener cl = (ContainerListener) o; + cl.leadershipAcquired(ev); + } + containerListeners.stopScanning(); + } + } + + //////////////////////////// + // Utility methods + //////////////////////////// + private ToolNotifier findNotifier(AID observerName) { + ToolNotifier tn = null; + // Note that if a ToolNotifier exists it must be among the messageListeners + // --> There is no need to search it also among the agentListeners. + List l = messageListeners.startScanning(); + if (l != null) { + for (Object obj : l) { + if (obj instanceof ToolNotifier tni) { + AID id = tni.getObserver(); + if (id.equals(observerName)) { + tn = tni; + break; + } + } + } + messageListeners.stopScanning(); + } + + // Redundant check: this condition may happen at platform shutdown + if (tn != null && tn.getState() == Agent.AP_DELETED) { // A formerly dead notifier + helper.deregisterMessageListener(tn); + helper.deregisterAgentListener(tn); + tn = null; + } + return tn; + } + + private ContainerID myID() { + return (ContainerID) myContainer.here(); + } /** * Inner class NotificationSourceSink @@ -314,7 +560,6 @@ private void handleNotifyChangedBehaviourState(VerticalCommand cmd) { } } // End of inner class NotificationSourceSink - /** * Inner class NotificationOutgoingFilter */ @@ -375,7 +620,6 @@ private void handleLeadershipAcquired(VerticalCommand cmd) { } } // END of inner class NotificationOutgoingFilter - /** * Inner class NotificationIncomingFilter */ @@ -404,7 +648,6 @@ private void handleReconnected(VerticalCommand cmd) { } } // END of inner class NotificationIncomingFilter - /** * Inner class ServiceComponent */ @@ -607,7 +850,6 @@ private void debugOff(AID introspectorName, AID targetName) { } } // End of ServiceComponent class - /** * Inner class NotificationHelperImpl */ @@ -652,259 +894,4 @@ public void deregisterContainerListener(ContainerListener cl) { containerListeners.stopModifying(); } } // END of inner class NotificationHelperImpl - - ///////////////////////////////////// - // Event dispatching methods - ///////////////////////////////////// - private void fireSentMessage(ACLMessage msg, AID sender, AID receiver) { - // NOTE: A normal synchronized block could create deadlock problems - // as it prevents concurrent scannings of the listeners list. - List l = messageListeners.startScanning(); - if (l != null) { - MessageEvent ev = new MessageEvent(MessageEvent.SENT_MESSAGE, msg, sender, receiver, myID()); - for (Object o : l) { - MessageListener ml = (MessageListener) o; - ml.sentMessage(ev); - } - messageListeners.stopScanning(); - } - } - - private void firePostedMessage(ACLMessage msg, AID receiver) { - // Set the sender explicitly only if different than that included in the message - String realSenderName = msg.getUserDefinedParameter(ACLMessage.REAL_SENDER); - AID sender = null; - if (realSenderName != null) { - sender = new AID(realSenderName, AID.ISGUID); - } - // NOTE: A normal synchronized block could create deadlock problems - // as it prevents concurrent scannings of the listeners list. - List l = messageListeners.startScanning(); - if (l != null) { - MessageEvent ev = new MessageEvent(MessageEvent.POSTED_MESSAGE, msg, sender, receiver, myID()); - for (Object o : l) { - MessageListener ml = (MessageListener) o; - ml.postedMessage(ev); - } - messageListeners.stopScanning(); - } - } - - private void fireReceivedMessage(ACLMessage msg, AID receiver) { - // Set the sender explicitly only if different than that included in the message - String realSenderName = msg.getUserDefinedParameter(ACLMessage.REAL_SENDER); - AID sender = null; - if (realSenderName != null) { - sender = new AID(realSenderName, AID.ISGUID); - } - // NOTE: A normal synchronized block could create deadlock problems - // as it prevents concurrent scannings of the listeners list. - List l = messageListeners.startScanning(); - if (l != null) { - MessageEvent ev = new MessageEvent(MessageEvent.RECEIVED_MESSAGE, msg, sender, receiver, myID()); - for (Object o : l) { - MessageListener ml = (MessageListener) o; - ml.receivedMessage(ev); - } - messageListeners.stopScanning(); - } - } - - private void fireRoutedMessage(ACLMessage msg, Channel from, Channel to) { - // NOTE: A normal synchronized block could create deadlock problems - // as it prevents concurrent scannings of the listeners list. - List l = messageListeners.startScanning(); - if (l != null) { - MessageEvent ev = new MessageEvent(MessageEvent.ROUTED_MESSAGE, msg, from, to, myID()); - for (Object o : l) { - MessageListener ml = (MessageListener) o; - ml.routedMessage(ev); - } - messageListeners.stopScanning(); - } - } - - private void fireAddedBehaviour(AID agentID, Behaviour b) { - // NOTE: A normal synchronized block could create deadlock problems - // as it prevents concurrent scannings of the listeners list. - List l = agentListeners.startScanning(); - if (l != null) { - AgentEvent ev = null; - if (b == b.root()) { - // The behaviour has been added to the Agent - ev = new AgentEvent(AgentEvent.ADDED_BEHAVIOUR, agentID, new BehaviourID(b), myID()); - } else { - // The behaviour is actually a new child that has been added to a CompositeBehaviour - //FIXME: TO be done - //ev = new AgentEvent(AgentEvent.ADDED_SUB_BEHAVIOUR, agentID, new BehaviourID(b.getParent()), new BehaviourID(b), myID()); - } - - for (Object o : l) { - AgentListener al = (AgentListener) o; - al.addedBehaviour(ev); - } - agentListeners.stopScanning(); - } - } - - private void fireRemovedBehaviour(AID agentID, Behaviour b) { - // NOTE: A normal synchronized block could create deadlock problems - // as it prevents concurrent scannings of the listeners list. - List l = agentListeners.startScanning(); - if (l != null) { - AgentEvent ev = new AgentEvent(AgentEvent.REMOVED_BEHAVIOUR, agentID, new BehaviourID(b), myID()); - for (Object o : l) { - AgentListener al = (AgentListener) o; - al.removedBehaviour(ev); - } - agentListeners.stopScanning(); - } - } - - private void fireChangedBehaviourState(AID agentID, Behaviour b, String from, String to) { - // NOTE: A normal synchronized block could create deadlock problems - // as it prevents concurrent scannings of the listeners list. - List l = agentListeners.startScanning(); - if (l != null) { - AgentEvent ev = new AgentEvent(AgentEvent.CHANGED_BEHAVIOUR_STATE, agentID, new BehaviourID(b), from, to, myID()); - for (Object o : l) { - AgentListener al = (AgentListener) o; - al.changedBehaviourState(ev); - } - agentListeners.stopScanning(); - } - } - - private void fireChangedAgentPrincipal(AID agentID, JADEPrincipal from, JADEPrincipal to) { - // NOTE: A normal synchronized block could create deadlock problems - // as it prevents concurrent scannings of the listeners list. - List l = agentListeners.startScanning(); - if (l != null) { - AgentEvent ev = new AgentEvent(AgentEvent.CHANGED_AGENT_PRINCIPAL, agentID, from, to, myID()); - for (Object o : l) { - AgentListener al = (AgentListener) o; - al.changedAgentPrincipal(ev); - } - agentListeners.stopScanning(); - } - } - - private void fireChangedAgentState(AID agentID, AgentState from, AgentState to) { - // NOTE: A normal synchronized block could create deadlock problems - // as it prevents concurrent scannings of the listeners list. - List l = agentListeners.startScanning(); - if (l != null) { - AgentEvent ev = new AgentEvent(AgentEvent.CHANGED_AGENT_STATE, agentID, from, to, myID()); - for (Object o : l) { - AgentListener al = (AgentListener) o; - al.changedAgentState(ev); - } - agentListeners.stopScanning(); - } - } - - private void fireBornAgent(AID agentID) { - // NOTE: A normal synchronized block could create deadlock problems - // as it prevents concurrent scannings of the listeners list. - List l = containerListeners.startScanning(); - if (l != null) { - ContainerEvent ev = new ContainerEvent(ContainerEvent.BORN_AGENT, agentID, myID()); - for (Object o : l) { - ContainerListener cl = (ContainerListener) o; - cl.bornAgent(ev); - } - containerListeners.stopScanning(); - } - } - - private void fireDeadAgent(AID agentID) { - // NOTE: A normal synchronized block could create deadlock problems - // as it prevents concurrent scannings of the listeners list. - List l = containerListeners.startScanning(); - if (l != null) { - ContainerEvent ev = new ContainerEvent(ContainerEvent.DEAD_AGENT, agentID, myID()); - for (Object o : l) { - ContainerListener cl = (ContainerListener) o; - cl.deadAgent(ev); - } - containerListeners.stopScanning(); - } - } - - private void fireReattached() { - // NOTE: A normal synchronized block could create deadlock problems - // as it prevents concurrent scannings of the listeners list. - List l = containerListeners.startScanning(); - if (l != null) { - ContainerEvent ev = new ContainerEvent(ContainerEvent.REATTACHED, null, myID()); - for (Object o : l) { - ContainerListener cl = (ContainerListener) o; - cl.reattached(ev); - } - containerListeners.stopScanning(); - } - } - - private void fireReconnected() { - // NOTE: A normal synchronized block could create deadlock problems - // as it prevents concurrent scannings of the listeners list. - List l = containerListeners.startScanning(); - if (l != null) { - ContainerEvent ev = new ContainerEvent(ContainerEvent.RECONNECTED, null, myID()); - for (Object o : l) { - ContainerListener cl = (ContainerListener) o; - cl.reconnected(ev); - } - containerListeners.stopScanning(); - } - } - - private void fireLeadershipAcquired() { - // NOTE: A normal synchronized block could create deadlock problems - // as it prevents concurrent scannings of the listeners list. - List l = containerListeners.startScanning(); - if (l != null) { - ContainerEvent ev = new ContainerEvent(ContainerEvent.LEADERSHIP_ACQUIRED, null, myID()); - for (Object o : l) { - ContainerListener cl = (ContainerListener) o; - cl.leadershipAcquired(ev); - } - containerListeners.stopScanning(); - } - } - - - //////////////////////////// - // Utility methods - //////////////////////////// - private ToolNotifier findNotifier(AID observerName) { - ToolNotifier tn = null; - // Note that if a ToolNotifier exists it must be among the messageListeners - // --> There is no need to search it also among the agentListeners. - List l = messageListeners.startScanning(); - if (l != null) { - for (Object obj : l) { - if (obj instanceof ToolNotifier tni) { - AID id = tni.getObserver(); - if (id.equals(observerName)) { - tn = tni; - break; - } - } - } - messageListeners.stopScanning(); - } - - // Redundant check: this condition may happen at platform shutdown - if (tn != null && tn.getState() == Agent.AP_DELETED) { // A formerly dead notifier - helper.deregisterMessageListener(tn); - helper.deregisterAgentListener(tn); - tn = null; - } - return tn; - } - - private ContainerID myID() { - return (ContainerID) myContainer.here(); - } } diff --git a/src/jade/core/event/PlatformEvent.java b/src/jade/core/event/PlatformEvent.java index 9d102b0..8c64e2d 100644 --- a/src/jade/core/event/PlatformEvent.java +++ b/src/jade/core/event/PlatformEvent.java @@ -314,7 +314,7 @@ public String getAgentGUID() { * @return A sring representation of this event. */ public String toString() { - StringBuffer buf = new StringBuffer(128); + StringBuilder buf = new StringBuilder(128); buf.append("PlatformEvent["); switch (type) { diff --git a/src/jade/core/faultRecovery/FSPersistentStorage.java b/src/jade/core/faultRecovery/FSPersistentStorage.java index e350339..5adbd54 100644 --- a/src/jade/core/faultRecovery/FSPersistentStorage.java +++ b/src/jade/core/faultRecovery/FSPersistentStorage.java @@ -45,12 +45,10 @@ class FSPersistentStorage implements PersistentStorage { private static final String UNREACHABLE_EXTENSION = ".unreachable"; private static final String PLATFORM_FILE_NAME = "platform"; private static final String NODE_POSTFIX = "-node"; - + private final Logger myLogger = Logger.getMyLogger(getClass().getName()); private String fileSeparator; private File locationDir; - private final Logger myLogger = Logger.getMyLogger(getClass().getName()); - public void init(Profile p) throws Exception { fileSeparator = System.getProperty("file.separator"); diff --git a/src/jade/core/faultRecovery/FaultRecoveryService.java b/src/jade/core/faultRecovery/FaultRecoveryService.java index 50f5c51..3bcefb2 100644 --- a/src/jade/core/faultRecovery/FaultRecoveryService.java +++ b/src/jade/core/faultRecovery/FaultRecoveryService.java @@ -285,86 +285,6 @@ private void killNode(String name, byte[] nn) { } } - - /** - * Inner class MainCommandIncomingFilter. - * This filter is installed on a Main Container and intercepts - * the NEW_NODE and DEAD_NODE V-Commands - */ - private class MainCommandIncomingFilter extends Filter { - public boolean accept(VerticalCommand cmd) { - String name = cmd.getName(); - try { - if (name.equals(Service.NEW_NODE)) { - handleNewNode((NodeDescriptor) cmd.getParams()[0]); - } - if (name.equals(Service.ADOPTED_NODE)) { - // An adopted node is treated exactly as a new node - handleNewNode((NodeDescriptor) cmd.getParams()[0]); - } else if (name.equals(Service.DEAD_NODE)) { - handleDeadNode((NodeDescriptor) cmd.getParams()[0]); - } - } catch (Exception e) { - myLogger.log(Logger.WARNING, "Error processing command " + name + ". ", e); - } - - // Never veto a command - return true; - } - } // END of inner class MainCommandIncomingFilter - - - /** - * Inner class MainCommandOutgoingFilter. - * This filter is installed on a Main Container and intercepts the - * NODE_UNREACHABLE and NODE_REACHABLE VCommands of the NodeMonitoringService - * and the ORPHAN_NODE VCommand of the UDPNodeMonitoringService. - */ - private class MainCommandOutgoingFilter extends Filter { - public boolean accept(VerticalCommand cmd) { - String name = cmd.getName(); - try { - switch (name) { - case NodeMonitoringService.NODE_UNREACHABLE -> handleNodeUnreachable((Node) cmd.getParams()[0]); - case NodeMonitoringService.NODE_REACHABLE -> handleNodeReachable((Node) cmd.getParams()[0]); - case UDPNodeMonitoringService.ORPHAN_NODE -> handleOrphanNode((String) cmd.getParams()[0]); - } - } catch (Exception e) { - myLogger.log(Logger.WARNING, "Error processing command " + name + ". ", e); - } - - // Never veto a command - return true; - } - } // END of inner class MainCommandOutgoingFilter - - - /** - * Inner class ContainerCommandIncomingFilter. - * This filter is installed on a peripheral Container and intercepts - * the REATTACHED V-Commands - */ - private class ContainerCommandIncomingFilter extends Filter { - public boolean accept(VerticalCommand cmd) { - String name = cmd.getName(); - try { - if (name.equals(Service.REATTACHED)) { - handleReattached(); - } - } catch (Exception e) { - myLogger.log(Logger.WARNING, "Error processing command " + name + ". ", e); - } - - // Never veto a command - return true; - } - } // END of inner class ContainerCommandIncomingFilter - - - //////////////////////////////////////////// - // Methods called by the filters - //////////////////////////////////////////// - /** * Add a newly born node to the persistent storage */ @@ -398,6 +318,11 @@ private void handleNodeUnreachable(Node node) throws Exception { } } + + //////////////////////////////////////////// + // Methods called by the filters + //////////////////////////////////////////// + /** * Remove the unreachable mark from a node in the persistent storage */ @@ -479,6 +404,77 @@ private void suicide() { t.start(); } + /** + * Inner class MainCommandIncomingFilter. + * This filter is installed on a Main Container and intercepts + * the NEW_NODE and DEAD_NODE V-Commands + */ + private class MainCommandIncomingFilter extends Filter { + public boolean accept(VerticalCommand cmd) { + String name = cmd.getName(); + try { + if (name.equals(Service.NEW_NODE)) { + handleNewNode((NodeDescriptor) cmd.getParams()[0]); + } + if (name.equals(Service.ADOPTED_NODE)) { + // An adopted node is treated exactly as a new node + handleNewNode((NodeDescriptor) cmd.getParams()[0]); + } else if (name.equals(Service.DEAD_NODE)) { + handleDeadNode((NodeDescriptor) cmd.getParams()[0]); + } + } catch (Exception e) { + myLogger.log(Logger.WARNING, "Error processing command " + name + ". ", e); + } + + // Never veto a command + return true; + } + } // END of inner class MainCommandIncomingFilter + + /** + * Inner class MainCommandOutgoingFilter. + * This filter is installed on a Main Container and intercepts the + * NODE_UNREACHABLE and NODE_REACHABLE VCommands of the NodeMonitoringService + * and the ORPHAN_NODE VCommand of the UDPNodeMonitoringService. + */ + private class MainCommandOutgoingFilter extends Filter { + public boolean accept(VerticalCommand cmd) { + String name = cmd.getName(); + try { + switch (name) { + case NodeMonitoringService.NODE_UNREACHABLE -> handleNodeUnreachable((Node) cmd.getParams()[0]); + case NodeMonitoringService.NODE_REACHABLE -> handleNodeReachable((Node) cmd.getParams()[0]); + case UDPNodeMonitoringService.ORPHAN_NODE -> handleOrphanNode((String) cmd.getParams()[0]); + } + } catch (Exception e) { + myLogger.log(Logger.WARNING, "Error processing command " + name + ". ", e); + } + + // Never veto a command + return true; + } + } // END of inner class MainCommandOutgoingFilter + + /** + * Inner class ContainerCommandIncomingFilter. + * This filter is installed on a peripheral Container and intercepts + * the REATTACHED V-Commands + */ + private class ContainerCommandIncomingFilter extends Filter { + public boolean accept(VerticalCommand cmd) { + String name = cmd.getName(); + try { + if (name.equals(Service.REATTACHED)) { + handleReattached(); + } + } catch (Exception e) { + myLogger.log(Logger.WARNING, "Error processing command " + name + ". ", e); + } + + // Never veto a command + return true; + } + } // END of inner class ContainerCommandIncomingFilter /** * Inner class NodeSerializer diff --git a/src/jade/core/management/AgentManagementProxy.java b/src/jade/core/management/AgentManagementProxy.java index 78918bf..1cf3345 100644 --- a/src/jade/core/management/AgentManagementProxy.java +++ b/src/jade/core/management/AgentManagementProxy.java @@ -78,7 +78,7 @@ public void killAgent(AID agentID, Command sourceCmd) throws IMTPException, NotF Node n = getNode(); Object result = n.accept(cmd); - if ((result != null) && (result instanceof Throwable)) { + if ((result instanceof Throwable)) { if (result instanceof IMTPException) { throw (IMTPException) result; } else if (result instanceof NotFoundException) { @@ -124,7 +124,7 @@ public void bornAgent(AID name, ContainerID cid, Command sourceCmd) throws IMTPE Node n = getNode(); Object result = n.accept(cmd); - if ((result != null) && (result instanceof Throwable)) { + if ((result instanceof Throwable)) { if (result instanceof IMTPException) { throw (IMTPException) result; } else if (result instanceof NotFoundException) { @@ -151,7 +151,7 @@ public void deadAgent(AID name, Command sourceCmd) throws IMTPException, NotFoun Node n = getNode(); Object result = n.accept(cmd); - if ((result != null) && (result instanceof Throwable)) { + if ((result instanceof Throwable)) { if (result instanceof IMTPException) { throw (IMTPException) result; } else if (result instanceof NotFoundException) { @@ -172,7 +172,7 @@ public void suspendedAgent(AID name) throws IMTPException, NotFoundException { Node n = getNode(); Object result = n.accept(cmd); - if ((result != null) && (result instanceof Throwable)) { + if ((result instanceof Throwable)) { if (result instanceof IMTPException) { throw (IMTPException) result; } else if (result instanceof NotFoundException) { @@ -193,7 +193,7 @@ public void resumedAgent(AID name) throws IMTPException, NotFoundException { Node n = getNode(); Object result = n.accept(cmd); - if ((result != null) && (result instanceof Throwable)) { + if ((result instanceof Throwable)) { if (result instanceof IMTPException) { throw (IMTPException) result; } else if (result instanceof NotFoundException) { @@ -213,7 +213,7 @@ public void exitContainer() throws IMTPException, NotFoundException { Node n = getNode(); Object result = n.accept(cmd); - if ((result != null) && (result instanceof Throwable)) { + if ((result instanceof Throwable)) { if (result instanceof IMTPException) { throw (IMTPException) result; } else if (result instanceof NotFoundException) { diff --git a/src/jade/core/management/AgentManagementService.java b/src/jade/core/management/AgentManagementService.java index a0a858d..e0b73f2 100644 --- a/src/jade/core/management/AgentManagementService.java +++ b/src/jade/core/management/AgentManagementService.java @@ -66,7 +66,17 @@ public class AgentManagementService extends BaseService { AgentManagementSlice.ADD_TOOL, AgentManagementSlice.REMOVE_TOOL }; - + // The local slice for this service + private final ServiceComponent localSlice = new ServiceComponent(); + // The command sink, source side + private final CommandSourceSink senderSink = new CommandSourceSink(); + // The command sink, target side + private final CommandTargetSink receiverSink = new CommandTargetSink(); + // The concrete agent container, providing access to LADT, etc. + private AgentContainer myContainer; + //#J2ME_EXCLUDE_BEGIN + private String agentsPath = null; + private CodeLocator codeLocator; public void init(AgentContainer ac, Profile p) throws ProfileException { super.init(ac, p); @@ -104,7 +114,6 @@ public Object load(String className, Properties pp) throws ClassNotFoundExceptio //#J2ME_EXCLUDE_END } - public String getName() { return AgentManagementSlice.NAME; } @@ -116,6 +125,7 @@ public Class getHorizontalInterface() { return null; } } + //#J2ME_EXCLUDE_END public Slice getLocalSlice() { return localSlice; @@ -125,7 +135,6 @@ public Filter getCommandFilter(boolean direction) { return null; } - public Sink getCommandSink(boolean side) { if (side == Sink.COMMAND_SOURCE) { return senderSink; @@ -141,12 +150,81 @@ public String[] getOwnedCommands() { public void removeLocalAgent(AID target) { myContainer.removeLocalAgent(target); } + //#J2ME_EXCLUDE_END //#J2ME_EXCLUDE_BEGIN public CodeLocator getCodeLocator() { return codeLocator; } - //#J2ME_EXCLUDE_END + + private void initAgent(AID target, Agent instance, VerticalCommand vCmd) throws IMTPException, JADESecurityException, NameClashException, NotFoundException, ServiceException { + //#J2ME_EXCLUDE_BEGIN + // If the agent was loaded from a separate space, register it to the codeLocator + if (isLoadedFromSeparateSpace(instance)) { + try { + codeLocator.registerAgent(target, instance.getClass().getClassLoader()); + } catch (Exception e) { + // Should never happen + e.printStackTrace(); + } + } + //#J2ME_EXCLUDE_END + + // Connect the new instance to the local container + Agent old = myContainer.addLocalAgent(target, instance); + if (instance == old) { + // This is a re-addition of an existing agent to a recovered main container (FaultRecoveryService) + old = null; + } + + try { + // Notify the main container through its slice + AgentManagementSlice mainSlice = (AgentManagementSlice) getSlice(MAIN_SLICE); + + // We propagate the class-name to the main, but we don't want to keep it in the actual agent AID. + AID cloned = (AID) target.clone(); + cloned.addUserDefinedSlot(AID.AGENT_CLASSNAME, instance.getClass().getName()); + try { + mainSlice.bornAgent(cloned, myContainer.getID(), vCmd); + } catch (IMTPException imtpe) { + // Try to get a newer slice and repeat... + mainSlice = (AgentManagementSlice) getFreshSlice(MAIN_SLICE); + mainSlice.bornAgent(cloned, myContainer.getID(), vCmd); + } + customize(instance); + } catch (NameClashException nce) { + removeLocalAgent(target); + if (old != null) { + myContainer.addLocalAgent(target, old); + } + throw nce; + } catch (IMTPException | JADESecurityException | NotFoundException imtpe) { + removeLocalAgent(target); + throw imtpe; + } + } + + //#J2ME_EXCLUDE_BEGIN + private boolean isLoadedFromSeparateSpace(Object obj) { + try { + Class c = obj.getClass(); + Class reloadedClass = Class.forName(c.getName(), true, getClass().getClassLoader()); + if (c == reloadedClass) { + return false; + } + } catch (Throwable t) { + // Just do nothing + } + return true; + } + + private void customize(Agent agent) { + } + + // Work-around for PJAVA compilation + protected Slice getFreshSlice(String name) throws ServiceException { + return super.getFreshSlice(name); + } // This inner class handles the messaging commands on the command // issuer side, turning them into horizontal commands and @@ -399,7 +477,6 @@ private void handleRemoveTool(VerticalCommand cmd) { } // End of CommandSourceSink class - private class CommandTargetSink implements Sink { public void consume(VerticalCommand cmd) { @@ -625,10 +702,10 @@ private void bornAgent(AID name, ContainerID cid, JADEPrincipal principal, Crede } } } - + /*#CUSTOMJ2SE_INCLUDE_BEGIN private java.util.List dyingAgents = new java.util.ArrayList(); - + private void waitUntilDead(AID id) { synchronized (dyingAgents) { while (dyingAgents.contains(id)) { @@ -639,7 +716,7 @@ private void waitUntilDead(AID id) { } } } - + private void notifyDead(AID id) { synchronized (dyingAgents) { dyingAgents.remove(id); @@ -678,7 +755,7 @@ private void exitContainer() { } // End of CommandTargetSink class - + //#J2ME_EXCLUDE_END /** * Inner mix-in class for this service: this class receives @@ -725,7 +802,6 @@ public VerticalCommand serve(HorizontalCommand cmd) { gCmd.addParam(startIt); result = gCmd; - break; } case AgentManagementSlice.H_KILLAGENT -> { GenericCommand gCmd = new GenericCommand(AgentManagementSlice.REQUEST_KILL, AgentManagementSlice.NAME, null); @@ -733,7 +809,6 @@ public VerticalCommand serve(HorizontalCommand cmd) { gCmd.addParam(agentID); result = gCmd; - break; } case AgentManagementSlice.H_CHANGEAGENTSTATE -> { GenericCommand gCmd = new GenericCommand(AgentManagementSlice.REQUEST_STATE_CHANGE, AgentManagementSlice.NAME, null); @@ -743,7 +818,6 @@ public VerticalCommand serve(HorizontalCommand cmd) { gCmd.addParam(newState); result = gCmd; - break; } case AgentManagementSlice.H_BORNAGENT -> { GenericCommand gCmd = new GenericCommand(AgentManagementSlice.INFORM_CREATED, AgentManagementSlice.NAME, null); @@ -759,7 +833,6 @@ public VerticalCommand serve(HorizontalCommand cmd) { } result = gCmd; - break; } case AgentManagementSlice.H_DEADAGENT -> { GenericCommand gCmd = new GenericCommand(AgentManagementSlice.INFORM_KILLED, AgentManagementSlice.NAME, null); @@ -767,7 +840,6 @@ public VerticalCommand serve(HorizontalCommand cmd) { gCmd.addParam(agentID); result = gCmd; - break; } case AgentManagementSlice.H_SUSPENDEDAGENT -> { GenericCommand gCmd = new GenericCommand(AgentManagementSlice.INFORM_STATE_CHANGED, AgentManagementSlice.NAME, null); @@ -777,7 +849,6 @@ public VerticalCommand serve(HorizontalCommand cmd) { gCmd.addParam("*"); result = gCmd; - break; } case AgentManagementSlice.H_RESUMEDAGENT -> { GenericCommand gCmd = new GenericCommand(AgentManagementSlice.INFORM_STATE_CHANGED, AgentManagementSlice.NAME, null); @@ -787,7 +858,6 @@ public VerticalCommand serve(HorizontalCommand cmd) { gCmd.addParam(jade.domain.FIPAAgentManagement.AMSAgentDescription.SUSPENDED); result = gCmd; - break; } case AgentManagementSlice.H_EXITCONTAINER -> result = new GenericCommand(AgentManagementSlice.KILL_CONTAINER, AgentManagementSlice.NAME, null); } @@ -799,93 +869,4 @@ public VerticalCommand serve(HorizontalCommand cmd) { } } // End of AgentManagementSlice class - - - private void initAgent(AID target, Agent instance, VerticalCommand vCmd) throws IMTPException, JADESecurityException, NameClashException, NotFoundException, ServiceException { - //#J2ME_EXCLUDE_BEGIN - // If the agent was loaded from a separate space, register it to the codeLocator - if (isLoadedFromSeparateSpace(instance)) { - try { - codeLocator.registerAgent(target, instance.getClass().getClassLoader()); - } catch (Exception e) { - // Should never happen - e.printStackTrace(); - } - } - //#J2ME_EXCLUDE_END - - // Connect the new instance to the local container - Agent old = myContainer.addLocalAgent(target, instance); - if (instance == old) { - // This is a re-addition of an existing agent to a recovered main container (FaultRecoveryService) - old = null; - } - - try { - // Notify the main container through its slice - AgentManagementSlice mainSlice = (AgentManagementSlice) getSlice(MAIN_SLICE); - - // We propagate the class-name to the main, but we don't want to keep it in the actual agent AID. - AID cloned = (AID) target.clone(); - cloned.addUserDefinedSlot(AID.AGENT_CLASSNAME, instance.getClass().getName()); - try { - mainSlice.bornAgent(cloned, myContainer.getID(), vCmd); - } catch (IMTPException imtpe) { - // Try to get a newer slice and repeat... - mainSlice = (AgentManagementSlice) getFreshSlice(MAIN_SLICE); - mainSlice.bornAgent(cloned, myContainer.getID(), vCmd); - } - customize(instance); - } catch (NameClashException nce) { - removeLocalAgent(target); - if (old != null) { - myContainer.addLocalAgent(target, old); - } - throw nce; - } catch (IMTPException | JADESecurityException | NotFoundException imtpe) { - removeLocalAgent(target); - throw imtpe; - } - } - - //#J2ME_EXCLUDE_BEGIN - private boolean isLoadedFromSeparateSpace(Object obj) { - try { - Class c = obj.getClass(); - Class reloadedClass = Class.forName(c.getName(), true, getClass().getClassLoader()); - if (c == reloadedClass) { - return false; - } - } catch (Throwable t) { - // Just do nothing - } - return true; - } - //#J2ME_EXCLUDE_END - - private void customize(Agent agent) { - } - - - // The concrete agent container, providing access to LADT, etc. - private AgentContainer myContainer; - - // The local slice for this service - private final ServiceComponent localSlice = new ServiceComponent(); - - // The command sink, source side - private final CommandSourceSink senderSink = new CommandSourceSink(); - - // The command sink, target side - private final CommandTargetSink receiverSink = new CommandTargetSink(); - - //#J2ME_EXCLUDE_BEGIN - private String agentsPath = null; - private CodeLocator codeLocator; - //#J2ME_EXCLUDE_END - - // Work-around for PJAVA compilation - protected Slice getFreshSlice(String name) throws ServiceException { - return super.getFreshSlice(name); - } } diff --git a/src/jade/core/management/BEAgentManagementService.java b/src/jade/core/management/BEAgentManagementService.java index 526f9c7..2a13933 100644 --- a/src/jade/core/management/BEAgentManagementService.java +++ b/src/jade/core/management/BEAgentManagementService.java @@ -56,7 +56,16 @@ public class BEAgentManagementService extends BaseService { AgentManagementSlice.INFORM_STATE_CHANGED, AgentManagementSlice.KILL_CONTAINER }; - + // The local slice for this service + private final ServiceComponent localSlice = new ServiceComponent(); + // The command sink, source side + private final CommandSourceSink senderSink = new CommandSourceSink(); + // The command sink, target side + private final CommandTargetSink receiverSink = new CommandTargetSink(); + // Service specific data + private final Map pendingImages = new HashMap<>(1); + // The concrete agent container, providing access to LADT, etc. + private BackEndContainer myContainer; public void init(AgentContainer ac, Profile p) throws ProfileException { super.init(ac, p); @@ -64,7 +73,6 @@ public void init(AgentContainer ac, Profile p) throws ProfileException { myContainer = (BackEndContainer) ac; } - public String getName() { return AgentManagementSlice.NAME; } @@ -85,7 +93,6 @@ public Filter getCommandFilter(boolean direction) { return null; } - public Sink getCommandSink(boolean side) { if (side == Sink.COMMAND_SOURCE) { return senderSink; @@ -98,7 +105,6 @@ public String[] getOwnedCommands() { return OWNED_COMMANDS; } - // This inner class handles the messaging commands on the command // issuer side, turning them into horizontal commands and // forwarding them to remote slices when necessary. @@ -280,7 +286,6 @@ private void handleInformStateChanged(VerticalCommand cmd) { } // End of CommandSourceSink class - private class CommandTargetSink implements Sink { public void consume(VerticalCommand cmd) { @@ -458,7 +463,6 @@ private void resumedAgent(AID name) throws NotFoundException { } // End of CommandTargetSink class - /** * Inner mix-in class for this service: this class receives * commands from the service Sink and serves them, @@ -501,7 +505,6 @@ public VerticalCommand serve(HorizontalCommand cmd) { gCmd.addParam(ownership); gCmd.addParam(certs); result = gCmd; - break; } case AgentManagementSlice.H_KILLAGENT -> { GenericCommand gCmd = new GenericCommand(AgentManagementSlice.REQUEST_KILL, AgentManagementSlice.NAME, null); @@ -509,7 +512,6 @@ public VerticalCommand serve(HorizontalCommand cmd) { gCmd.addParam(agentID); result = gCmd; - break; } case AgentManagementSlice.H_CHANGEAGENTSTATE -> { GenericCommand gCmd = new GenericCommand(AgentManagementSlice.REQUEST_STATE_CHANGE, AgentManagementSlice.NAME, null); @@ -519,7 +521,6 @@ public VerticalCommand serve(HorizontalCommand cmd) { gCmd.addParam(newState); result = gCmd; - break; } case AgentManagementSlice.H_BORNAGENT -> { GenericCommand gCmd = new GenericCommand(AgentManagementSlice.INFORM_CREATED, AgentManagementSlice.NAME, null); @@ -531,7 +532,6 @@ public VerticalCommand serve(HorizontalCommand cmd) { gCmd.addParam(ownership); result = gCmd; - break; } case AgentManagementSlice.H_DEADAGENT -> { GenericCommand gCmd = new GenericCommand(AgentManagementSlice.INFORM_KILLED, AgentManagementSlice.NAME, null); @@ -539,7 +539,6 @@ public VerticalCommand serve(HorizontalCommand cmd) { gCmd.addParam(agentID); result = gCmd; - break; } case AgentManagementSlice.H_SUSPENDEDAGENT -> { GenericCommand gCmd = new GenericCommand(AgentManagementSlice.INFORM_STATE_CHANGED, AgentManagementSlice.NAME, null); @@ -548,7 +547,6 @@ public VerticalCommand serve(HorizontalCommand cmd) { gCmd.addParam(jade.domain.FIPAAgentManagement.AMSAgentDescription.SUSPENDED); result = gCmd; - break; } case AgentManagementSlice.H_RESUMEDAGENT -> { GenericCommand gCmd = new GenericCommand(AgentManagementSlice.INFORM_STATE_CHANGED, AgentManagementSlice.NAME, null); @@ -557,7 +555,6 @@ public VerticalCommand serve(HorizontalCommand cmd) { gCmd.addParam(jade.domain.FIPAAgentManagement.AMSAgentDescription.ACTIVE); result = gCmd; - break; } case AgentManagementSlice.H_EXITCONTAINER -> result = new GenericCommand(AgentManagementSlice.KILL_CONTAINER, AgentManagementSlice.NAME, null); } @@ -570,20 +567,4 @@ public VerticalCommand serve(HorizontalCommand cmd) { } // End of AgentManagementSlice class - - // The concrete agent container, providing access to LADT, etc. - private BackEndContainer myContainer; - - // The local slice for this service - private final ServiceComponent localSlice = new ServiceComponent(); - - // The command sink, source side - private final CommandSourceSink senderSink = new CommandSourceSink(); - - // The command sink, target side - private final CommandTargetSink receiverSink = new CommandTargetSink(); - - // Service specific data - private final Map pendingImages = new HashMap<>(1); - } diff --git a/src/jade/core/management/CodeLocator.java b/src/jade/core/management/CodeLocator.java index 428a913..468eef0 100644 --- a/src/jade/core/management/CodeLocator.java +++ b/src/jade/core/management/CodeLocator.java @@ -45,6 +45,9 @@ public class CodeLocator { + private final HashMap _agents; + private final Vector _subscriptions; + public CodeLocator() { _agents = new HashMap<>(); _subscriptions = new Vector<>(); @@ -216,8 +219,5 @@ public synchronized boolean unSubscribeToEvents(CodeLocatorListener cle) { return _subscriptions.remove(cle); } - private final HashMap _agents; - private final Vector _subscriptions; - } diff --git a/src/jade/core/messaging/FileMessageStorage.java b/src/jade/core/messaging/FileMessageStorage.java index a8929ab..9e5dc4c 100644 --- a/src/jade/core/messaging/FileMessageStorage.java +++ b/src/jade/core/messaging/FileMessageStorage.java @@ -40,6 +40,7 @@ class FileMessageStorage implements MessageStorage { private static final String FOREVER = "FOREVER"; private final Logger myLogger = Logger.getMyLogger(getClass().getName()); + private File baseDir; public void init(Profile p) { // Retrieve the base directory from the profile @@ -269,7 +270,4 @@ private void createMessageFile(File toStore, GenericMessage msg, AID receiver) t } } - - private File baseDir; - } diff --git a/src/jade/core/messaging/GenericMessage.java b/src/jade/core/messaging/GenericMessage.java index 42fd841..52ef112 100644 --- a/src/jade/core/messaging/GenericMessage.java +++ b/src/jade/core/messaging/GenericMessage.java @@ -92,22 +92,22 @@ public final void update(ACLMessage msg, Envelope env, byte[] payload) { this.payload = payload; } - final void setSenderPrincipal(JADEPrincipal senderPrincipal) { - this.senderPrincipal = senderPrincipal; - } - final JADEPrincipal getSenderPrincipal() { return senderPrincipal; } - final void setSenderCredentials(Credentials senderCredentials) { - this.senderCredentials = senderCredentials; + final void setSenderPrincipal(JADEPrincipal senderPrincipal) { + this.senderPrincipal = senderPrincipal; } final Credentials getSenderCredentials() { return senderCredentials; } + final void setSenderCredentials(Credentials senderCredentials) { + this.senderCredentials = senderCredentials; + } + public final boolean isAMSFailure() { return isAMSFailure; } @@ -164,10 +164,6 @@ private void writeObject(ObjectOutputStream out) throws IOException { } //#MIDP_EXCLUDE_END - public final void setSender(AID sender) { - this.sender = sender; - } - public final AID getSender() { if (sender != null) { return sender; @@ -180,6 +176,10 @@ public final AID getSender() { } } + public final void setSender(AID sender) { + this.sender = sender; + } + // DEBUG public String toString() { return "GenericMessage\n\t" + msg + "\n\t" + env + "\n\t" + ((payload == null) ? "null payload" : Arrays.toString(payload)) + "\n"; diff --git a/src/jade/core/messaging/LightMessagingService.java b/src/jade/core/messaging/LightMessagingService.java index 416f32d..b6897e4 100644 --- a/src/jade/core/messaging/LightMessagingService.java +++ b/src/jade/core/messaging/LightMessagingService.java @@ -430,15 +430,11 @@ public boolean accept(VerticalCommand cmd) { return true; } - public void setBlocking(boolean newState) { - // Do nothing. Blocking and Skipping not supported - } - public boolean isBlocking() { return false; // Blocking and Skipping not implemented } - public void setSkipping(boolean newState) { + public void setBlocking(boolean newState) { // Do nothing. Blocking and Skipping not supported } @@ -446,6 +442,10 @@ public boolean isSkipping() { return false; // Blocking and Skipping not implemented } + public void setSkipping(boolean newState) { + // Do nothing. Blocking and Skipping not supported + } + // Implementation of the Service.Slice interface public Service getService() { return LightMessagingService.this; diff --git a/src/jade/core/messaging/MessageManager.java b/src/jade/core/messaging/MessageManager.java index 7e531d5..4869422 100644 --- a/src/jade/core/messaging/MessageManager.java +++ b/src/jade/core/messaging/MessageManager.java @@ -49,29 +49,22 @@ */ class MessageManager { - public interface Channel { - void deliverNow(GenericMessage msg, AID receiverID) throws UnreachableException, NotFoundException; - - void notifyFailureToSender(GenericMessage msg, AID receiver, InternalError ie); - } - - - // A shared instance to have a single thread pool - private static MessageManager theInstance; // FIXME: Maybe a table, indexed by a profile subset, would be better? - private static final String DUMMY_RECEIVER_NAME = "___DUMMY_"; - private static final int POOL_SIZE_DEFAULT = 5; private static final int MAX_POOL_SIZE = 100; - private static final int DELIVERY_TIME_THRESHOLD_DEFAULT = 1000; // ms private static final int DELIVERY_TIME_THRESHOLD2_DEFAULT = 5000; // ms private static final int DELIVERY_STUCK_TIME_DEFAULT = 60000; // ms - private static final int WARNING_QUEUE_SIZE_DEFAULT = 10000000; // 10MBytes private static final int MAX_QUEUE_SIZE_DEFAULT = 100000000; // 100MBytes private static final int SLEEP_TIME_FACTOR_DEFAULT = -1; // ms/MByes, -1=no sleep time - + // A shared instance to have a single thread pool + private static MessageManager theInstance; // FIXME: Maybe a table, indexed by a profile subset, would be better? + //#J2ME_EXCLUDE_BEGIN + private final AverageMeasureProviderImpl avgMsgCountPerMultipleDelivery = new AverageMeasureProviderImpl(); // Average number of messages delivered in multiple-message-delivery + private final Logger myLogger = Logger.getMyLogger(getClass().getName()); + //#MIDP_EXCLUDE_BEGIN + private final java.text.SimpleDateFormat timeFormat = new java.text.SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); private OutBox outBox; private Thread[] delivererThreads; private Deliverer[] deliverers; @@ -79,20 +72,13 @@ public interface Channel { private long deliveryTimeThreshold; private long deliveryTimeThreshold2; private long deliveryStuckTime; - private long totSubmittedCnt = 0; private long totServedCnt = 0; private long totDiscardedCnt = 0; private long totSlowDeliveryCnt = 0; private long totVerySlowDeliveryCnt = 0; - - private long totMultipleDeliveryCnt = 0; // How many times multiple-message-delivery was triggered - //#J2ME_EXCLUDE_BEGIN - private final AverageMeasureProviderImpl avgMsgCountPerMultipleDelivery = new AverageMeasureProviderImpl(); // Average number of messages delivered in multiple-message-delivery //#J2ME_EXCLUDE_END - - - private final Logger myLogger = Logger.getMyLogger(getClass().getName()); + private long totMultipleDeliveryCnt = 0; // How many times multiple-message-delivery was triggered private MessageManager() { } @@ -106,6 +92,72 @@ public static synchronized MessageManager instance(Profile p) { return theInstance; } + /** + * + */ + public static String stringify(GenericMessage m) { + //#J2ME_EXCLUDE_BEGIN + if (m instanceof MultipleGenericMessage mm) { + // MULTIPLE message + StringBuilder sb = new StringBuilder("[SET"); + List l = mm.getMessages(); + int cnt = 0; + for (GenericMessage gm : l) { + sb.append(" "); + sb.append(stringify(gm)); + // Avoid stringifying to many messages + cnt++; + if (cnt > 10 && cnt < l.size()) { + sb.append("...").append(l.size()).append(" messages in total"); + break; + } + } + sb.append("]"); + return sb.toString(); + } else { + //#J2ME_EXCLUDE_END + // SINGLE (normal) message + ACLMessage msg = m.getACLMessage(); + if (msg != null) { + StringBuilder sb = new StringBuilder("("); + sb.append(ACLMessage.getPerformative(msg.getPerformative())); + sb.append(" sender: "); + sb.append(msg.getSender().getName()); + if (msg.getOntology() != null) { + sb.append(" ontology: "); + sb.append(msg.getOntology()); + } + if (msg.getConversationId() != null) { + sb.append(" conversation-id: "); + sb.append(msg.getConversationId()); + } + sb.append(')'); + return sb.toString(); + } else { + return ("\"Unavailable\""); + } + //#J2ME_EXCLUDE_BEGIN + } + //#J2ME_EXCLUDE_END + } + + //#J2ME_EXCLUDE_BEGIN + public static void main(String[] args) { + GenericMessage gm = new GenericMessage(); + ACLMessage msg = new ACLMessage(ACLMessage.INFORM); + msg.setSender(new AID("pippo@P1", AID.ISGUID)); + msg.addReceiver(new AID("pluto@P1", AID.ISGUID)); + gm.setACLMessage(msg); + System.out.println(stringify(gm)); + + MultipleGenericMessage mgm = new MultipleGenericMessage(200); + List l = new ArrayList<>(); + l.add(gm); + l.add(gm); + mgm.setMessages(l); + System.out.println(stringify(mgm)); + } + public void initialize(Profile p) { String tmp = null; @@ -283,6 +335,153 @@ public void deliver(GenericMessage msg, AID receiverID, Channel ch) { } } + // For debugging purpose + String[] getQueueStatus() { + return outBox.getStatus(); + } + + // For debugging purpose + int getSize() { + return outBox.getSize(); + } + //#J2ME_EXCLUDE_END + + int getPendingCnt() { + return outBox.getPendingCnt(); + } + + long getSubmittedCnt() { + return totSubmittedCnt; + } + + long getServedCnt() { + return totServedCnt; + } + + long getDiscardedCnt() { + return totDiscardedCnt; + } + + long getSlowDeliveryCnt() { + return totSlowDeliveryCnt; + } + + long getVerySlowDeliveryCnt() { + return totVerySlowDeliveryCnt; + } + + long getMultipleDeliveryCnt() { + return totMultipleDeliveryCnt; + } + + //#J2ME_EXCLUDE_BEGIN + AverageMeasureProviderImpl getAvgMsgCountPerMultipleDeliveryProvider() { + return avgMsgCountPerMultipleDelivery; + } + + // For debugging purpose + String getGlobalInfo() { + return "Submitted-messages = " + totSubmittedCnt + ", Served-messages = " + totServedCnt + ", Discarded-messages = " + totDiscardedCnt + ", Queue-size (byte) = " + outBox.getSize() + ", Multiple-delivery-occurrences = " + totMultipleDeliveryCnt; + } + + // For debugging purpose + String[] getThreadPoolStatus() { + String[] status = new String[deliverers.length]; + for (int i = 0; i < deliverers.length; ++i) { + Deliverer d = deliverers[i]; + String details; + if (d.isStuck()) { + //#MIDP_EXCLUDE_BEGIN + details = "STUCK!!! last-delivery-start-time=" + timeFormat.format(new java.util.Date(d.getLastDeliveryStartTime())); + //#MIDP_EXCLUDE_END + /*#MIDP_INCLUDE_BEGIN + details = "STUCK!!! last-delivery-start-time="+formatDate(d.getLastDeliveryStartTime()); + #MIDP_INCLUDE_END*/ + } else { + //#MIDP_EXCLUDE_BEGIN + details = "last-delivery-end-time=" + timeFormat.format(new java.util.Date(d.getLastDeliveryEndTime())); + //#MIDP_EXCLUDE_END + /*#MIDP_INCLUDE_BEGIN + details = "last-delivery-end-time="+formatDate(d.getLastDeliveryEndTime()); + #MIDP_INCLUDE_END*/ + } + status[i] = "(" + d.name + ": thread-alive=" + delivererThreads[i].isAlive() + ", Served-messages=" + d.getServedCnt() + ", " + details + ")"; + } + return status; + } + //#J2ME_EXCLUDE_END + + // For debugging purpose + Thread[] getThreadPool() { + return delivererThreads; + } + + public interface Channel { + void deliverNow(GenericMessage msg, AID receiverID) throws UnreachableException, NotFoundException; + + void notifyFailureToSender(GenericMessage msg, AID receiver, InternalError ie); + } + //#MIDP_EXCLUDE_END + /*#MIDP_INCLUDE_BEGIN + private String formatDate(long date) { + java.util.Calendar calendar = java.util.Calendar.getInstance(); + calendar.setTime(new java.util.Date(date)); + java.lang.StringBuffer sb = new java.lang.StringBuffer(); + sb.append(calendar.get(java.util.Calendar.YEAR)); + sb.append("/"); + sb.append(calendar.get(java.util.Calendar.MONTH)); + sb.append("/"); + sb.append(calendar.get(java.util.Calendar.DAY_OF_MONTH)); + sb.append(" "); + sb.append(calendar.get(java.util.Calendar.HOUR)); + sb.append(":"); + sb.append(calendar.get(java.util.Calendar.MINUTE)); + sb.append(":"); + sb.append(calendar.get(java.util.Calendar.SECOND)); + return sb.toString(); + } + #MIDP_INCLUDE_END*/ + + /** + * Inner class PendingMsg + */ + public static class PendingMsg { + private final AID receiverID; + private final Channel channel; + private GenericMessage msg; + private long deadline; + + public PendingMsg(GenericMessage msg, AID receiverID, Channel channel, long deadline) { + this.msg = msg; + this.receiverID = receiverID; + this.channel = channel; + this.deadline = deadline; + } + + public GenericMessage getMessage() { + return msg; + } + + public void setMessage(GenericMessage msg) { + this.msg = msg; + } + + public AID getReceiver() { + return receiverID; + } + + public Channel getChannel() { + return channel; + } + + public long getDeadline() { + return deadline; + } + + public void setDeadline(long deadline) { + this.deadline = deadline; + } + } // END of inner class PendingMsg /** * Inner class Deliverer @@ -395,218 +594,5 @@ boolean isStuck() { } } } // END of inner class Deliverer - - - /** - * Inner class PendingMsg - */ - public static class PendingMsg { - private GenericMessage msg; - private final AID receiverID; - private final Channel channel; - private long deadline; - - public PendingMsg(GenericMessage msg, AID receiverID, Channel channel, long deadline) { - this.msg = msg; - this.receiverID = receiverID; - this.channel = channel; - this.deadline = deadline; - } - - public void setMessage(GenericMessage msg) { - this.msg = msg; - } - - public GenericMessage getMessage() { - return msg; - } - - public AID getReceiver() { - return receiverID; - } - - public Channel getChannel() { - return channel; - } - - public long getDeadline() { - return deadline; - } - - public void setDeadline(long deadline) { - this.deadline = deadline; - } - } // END of inner class PendingMsg - - - /** - * - */ - public static String stringify(GenericMessage m) { - //#J2ME_EXCLUDE_BEGIN - if (m instanceof MultipleGenericMessage mm) { - // MULTIPLE message - StringBuilder sb = new StringBuilder("[SET"); - List l = mm.getMessages(); - int cnt = 0; - for (GenericMessage gm : l) { - sb.append(" "); - sb.append(stringify(gm)); - // Avoid stringifying to many messages - cnt++; - if (cnt > 10 && cnt < l.size()) { - sb.append("...").append(l.size()).append(" messages in total"); - break; - } - } - sb.append("]"); - return sb.toString(); - } else { - //#J2ME_EXCLUDE_END - // SINGLE (normal) message - ACLMessage msg = m.getACLMessage(); - if (msg != null) { - StringBuilder sb = new StringBuilder("("); - sb.append(ACLMessage.getPerformative(msg.getPerformative())); - sb.append(" sender: "); - sb.append(msg.getSender().getName()); - if (msg.getOntology() != null) { - sb.append(" ontology: "); - sb.append(msg.getOntology()); - } - if (msg.getConversationId() != null) { - sb.append(" conversation-id: "); - sb.append(msg.getConversationId()); - } - sb.append(')'); - return sb.toString(); - } else { - return ("\"Unavailable\""); - } - //#J2ME_EXCLUDE_BEGIN - } - //#J2ME_EXCLUDE_END - } - - //#J2ME_EXCLUDE_BEGIN - public static void main(String[] args) { - GenericMessage gm = new GenericMessage(); - ACLMessage msg = new ACLMessage(ACLMessage.INFORM); - msg.setSender(new AID("pippo@P1", AID.ISGUID)); - msg.addReceiver(new AID("pluto@P1", AID.ISGUID)); - gm.setACLMessage(msg); - System.out.println(stringify(gm)); - - MultipleGenericMessage mgm = new MultipleGenericMessage(200); - List l = new ArrayList<>(); - l.add(gm); - l.add(gm); - mgm.setMessages(l); - System.out.println(stringify(mgm)); - } - //#J2ME_EXCLUDE_END - - // For debugging purpose - String[] getQueueStatus() { - return outBox.getStatus(); - } - - // For debugging purpose - int getSize() { - return outBox.getSize(); - } - - int getPendingCnt() { - return outBox.getPendingCnt(); - } - - long getSubmittedCnt() { - return totSubmittedCnt; - } - - long getServedCnt() { - return totServedCnt; - } - - long getDiscardedCnt() { - return totDiscardedCnt; - } - - long getSlowDeliveryCnt() { - return totSlowDeliveryCnt; - } - - long getVerySlowDeliveryCnt() { - return totVerySlowDeliveryCnt; - } - - long getMultipleDeliveryCnt() { - return totMultipleDeliveryCnt; - } - - //#J2ME_EXCLUDE_BEGIN - AverageMeasureProviderImpl getAvgMsgCountPerMultipleDeliveryProvider() { - return avgMsgCountPerMultipleDelivery; - } - //#J2ME_EXCLUDE_END - - // For debugging purpose - String getGlobalInfo() { - return "Submitted-messages = " + totSubmittedCnt + ", Served-messages = " + totServedCnt + ", Discarded-messages = " + totDiscardedCnt + ", Queue-size (byte) = " + outBox.getSize() + ", Multiple-delivery-occurrences = " + totMultipleDeliveryCnt; - } - - //#MIDP_EXCLUDE_BEGIN - private final java.text.SimpleDateFormat timeFormat = new java.text.SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); - //#MIDP_EXCLUDE_END - /*#MIDP_INCLUDE_BEGIN - private String formatDate(long date) { - java.util.Calendar calendar = java.util.Calendar.getInstance(); - calendar.setTime(new java.util.Date(date)); - java.lang.StringBuffer sb = new java.lang.StringBuffer(); - sb.append(calendar.get(java.util.Calendar.YEAR)); - sb.append("/"); - sb.append(calendar.get(java.util.Calendar.MONTH)); - sb.append("/"); - sb.append(calendar.get(java.util.Calendar.DAY_OF_MONTH)); - sb.append(" "); - sb.append(calendar.get(java.util.Calendar.HOUR)); - sb.append(":"); - sb.append(calendar.get(java.util.Calendar.MINUTE)); - sb.append(":"); - sb.append(calendar.get(java.util.Calendar.SECOND)); - return sb.toString(); - } - #MIDP_INCLUDE_END*/ - - // For debugging purpose - String[] getThreadPoolStatus() { - String[] status = new String[deliverers.length]; - for (int i = 0; i < deliverers.length; ++i) { - Deliverer d = deliverers[i]; - String details; - if (d.isStuck()) { - //#MIDP_EXCLUDE_BEGIN - details = "STUCK!!! last-delivery-start-time=" + timeFormat.format(new java.util.Date(d.getLastDeliveryStartTime())); - //#MIDP_EXCLUDE_END - /*#MIDP_INCLUDE_BEGIN - details = "STUCK!!! last-delivery-start-time="+formatDate(d.getLastDeliveryStartTime()); - #MIDP_INCLUDE_END*/ - } else { - //#MIDP_EXCLUDE_BEGIN - details = "last-delivery-end-time=" + timeFormat.format(new java.util.Date(d.getLastDeliveryEndTime())); - //#MIDP_EXCLUDE_END - /*#MIDP_INCLUDE_BEGIN - details = "last-delivery-end-time="+formatDate(d.getLastDeliveryEndTime()); - #MIDP_INCLUDE_END*/ - } - status[i] = "(" + d.name + ": thread-alive=" + delivererThreads[i].isAlive() + ", Served-messages=" + d.getServedCnt() + ", " + details + ")"; - } - return status; - } - - // For debugging purpose - Thread[] getThreadPool() { - return delivererThreads; - } } diff --git a/src/jade/core/messaging/MessageStorage.java b/src/jade/core/messaging/MessageStorage.java index b1b713f..2985c0f 100644 --- a/src/jade/core/messaging/MessageStorage.java +++ b/src/jade/core/messaging/MessageStorage.java @@ -33,14 +33,6 @@ public interface MessageStorage { - interface LoadListener { - void loadStarted(String storeName); - - void itemLoaded(String storeName, GenericMessage msg, AID receiver); - - void loadEnded(String storeName); - } - void init(Profile p); String store(GenericMessage msg, AID receiver) throws IOException; @@ -49,4 +41,12 @@ interface LoadListener { void loadAll(LoadListener ll) throws IOException; + interface LoadListener { + void loadStarted(String storeName); + + void itemLoaded(String storeName, GenericMessage msg, AID receiver); + + void loadEnded(String storeName); + } + } diff --git a/src/jade/core/messaging/MessagingHelper.java b/src/jade/core/messaging/MessagingHelper.java index 3b70a09..ea6b118 100644 --- a/src/jade/core/messaging/MessagingHelper.java +++ b/src/jade/core/messaging/MessagingHelper.java @@ -10,16 +10,6 @@ * available to agents */ public interface MessagingHelper extends ServiceHelper { - /** - * The interface to be implemented by classes that need to be notified about - * aliases creation/deletion - */ - interface AliasListener { - void handleNewAlias(AID alias, AID agent); - - void handleDeadAlias(AID alias, AID agent); - } - /** * Create a new alias of the agent associated to this helper * @@ -51,4 +41,14 @@ interface AliasListener { * @param l The listener to be de-registered */ void deregisterAliasListener(AliasListener l) throws ServiceException; + + /** + * The interface to be implemented by classes that need to be notified about + * aliases creation/deletion + */ + interface AliasListener { + void handleNewAlias(AID alias, AID agent); + + void handleDeadAlias(AID alias, AID agent); + } } diff --git a/src/jade/core/messaging/MessagingService.java b/src/jade/core/messaging/MessagingService.java index 493ed69..e6cb730 100644 --- a/src/jade/core/messaging/MessagingService.java +++ b/src/jade/core/messaging/MessagingService.java @@ -87,61 +87,51 @@ public class MessagingService extends BaseService implements MessageManager.Chan public static final String ENABLE_MESSAGE_MANAGER_METRICS = "jade_core_messaging_MessagingService_enablemessagemanagermetrics"; //#J2ME_EXCLUDE_END - + private final static int EXPECTED_ACLENCODINGS_SIZE = 3; + private static final String[] OWNED_COMMANDS = new String[]{ + MessagingSlice.SEND_MESSAGE, + MessagingSlice.NOTIFY_FAILURE, + MessagingSlice.INSTALL_MTP, + MessagingSlice.UNINSTALL_MTP, + MessagingSlice.NEW_MTP, + MessagingSlice.DEAD_MTP, + MessagingSlice.SET_PLATFORM_ADDRESSES + }; + // The local slice for this service + private final ServiceComponent localSlice = new ServiceComponent(); + // The command sink, source side + private final CommandSourceSink senderSink = new CommandSourceSink(); + // The command sink, target side + private final CommandTargetSink receiverSink = new CommandTargetSink(); + // The map of local and global (used in the Main Container) aliases + private final Hashtable localAliases = new Hashtable<>(); + // The table of the locally installed ACL message encodings + private final Map messageEncodings = new HashMap<>(EXPECTED_ACLENCODINGS_SIZE); + // The handle to the MainReplicationService to keep global aliases info in synch + MainReplicationHandle replicationHandle; // The profile passed to this object private Profile myProfile; - // A flag indicating whether or not we must accept foreign agents private boolean acceptForeignAgents = false; - // The ID of the Platform this service belongs to private String platformID; - // The concrete agent container, providing access to LADT, etc. private AgentContainer myContainer; - - // The local slice for this service - private final ServiceComponent localSlice = new ServiceComponent(); - - // The command sink, source side - private final CommandSourceSink senderSink = new CommandSourceSink(); - - // The command sink, target side - private final CommandTargetSink receiverSink = new CommandTargetSink(); - // The filter for incoming commands related to ACL encoding private OutgoingEncodingFilter encOutFilter; - // The filter for outgoing commands related to ACL encoding private IncomingEncodingFilter encInFilter; - // The cached AID -> MessagingSlice associations private Map cachedSlices; - // The routing table mapping MTP addresses to their hosting slice private RoutingTable routes; - private int maxDeliveryRetryAttempts; - - // The map of local and global (used in the Main Container) aliases - private final Hashtable localAliases = new Hashtable<>(); private Hashtable globalAliases; private List aliasListeners; - - // The handle to the MainReplicationService to keep global aliases info in synch - MainReplicationHandle replicationHandle; - - - private final static int EXPECTED_ACLENCODINGS_SIZE = 3; - // The table of the locally installed ACL message encodings - private final Map messageEncodings = new HashMap<>(EXPECTED_ACLENCODINGS_SIZE); - // The platform ID, to be used in inter-platform dispatching private String accID; - // The component managing asynchronous message delivery and retries private MessageManager myMessageManager; - //#J2ME_EXCLUDE_BEGIN // SAM related variables private boolean samActive; @@ -151,25 +141,10 @@ public class MessagingService extends BaseService implements MessageManager.Chan private long postedMessageCounter; private AverageMeasureProviderImpl avgQueueSizeBytesProvider; private AverageMeasureProviderImpl avgQueueSizeMessagesProvider; - private Timer samTimer; //#J2ME_EXCLUDE_END - - public static class UnknownACLEncodingException extends NotFoundException { - UnknownACLEncodingException(String msg) { - super(msg); - } - } // End of UnknownACLEncodingException class - - - private static final String[] OWNED_COMMANDS = new String[]{ - MessagingSlice.SEND_MESSAGE, - MessagingSlice.NOTIFY_FAILURE, - MessagingSlice.INSTALL_MTP, - MessagingSlice.UNINSTALL_MTP, - MessagingSlice.NEW_MTP, - MessagingSlice.DEAD_MTP, - MessagingSlice.SET_PLATFORM_ADDRESSES - }; + private Timer samTimer; + // Only for debugging: + private volatile int traceCnt = 0; public MessagingService() { } @@ -284,10 +259,9 @@ public void boot(Profile myProfile) throws ServiceException { // MTPs l = myProfile.getSpecifiers(Profile.MTPS); PrintWriter f = null; - StringBuffer sb = null; + StringBuilder sb = null; - for (Object o : l) { - Specifier spec = (Specifier) o; + for (Specifier spec : l) { String className = spec.getClassName(); String addressURL = null; Object[] args = spec.getArgs(); @@ -304,7 +278,7 @@ public void boot(Profile myProfile) throws ServiceException { if (f == null) { String fileName = myProfile.getParameter(Profile.FILE_DIR, "") + "MTPs-" + myContainer.getID().getName() + ".txt"; f = new PrintWriter(new FileWriter(fileName)); - sb = new StringBuffer("MTP addresses:"); + sb = new StringBuilder("MTP addresses:"); } f.println(mtpAddrs[0]); sb.append("\n"); @@ -776,1276 +750,1259 @@ private ContainerID getAgentLocation(AID agentID) throws IMTPException, NotFound } } - /** - * Inner class CommandSourceSink - * This inner class handles the messaging commands on the command - * issuer side, turning them into horizontal commands and - * forwarding them to remote slices when necessary. - */ - private class CommandSourceSink implements Sink { - - public void consume(VerticalCommand cmd) { - - try { - String name = cmd.getName(); - - switch (name) { - case MessagingSlice.SEND_MESSAGE -> handleSendMessage(cmd); - case MessagingSlice.NOTIFY_FAILURE -> handleNotifyFailure(cmd); - case MessagingSlice.INSTALL_MTP -> { - Object result = handleInstallMTP(cmd); - cmd.setReturnValue(result); - } - case MessagingSlice.UNINSTALL_MTP -> handleUninstallMTP(cmd); - case MessagingSlice.NEW_MTP -> handleNewMTP(cmd); - case MessagingSlice.DEAD_MTP -> handleDeadMTP(cmd); - case MessagingSlice.SET_PLATFORM_ADDRESSES -> handleSetPlatformAddresses(cmd); + void stamp(GenericMessage gmsg) { + //#J2ME_EXCLUDE_BEGIN + if (samActive) { + synchronized (this) { + msgCounter++; + if (msgCounter == deliveryTimeMeasurementRate) { + gmsg.setTimeStamp(System.currentTimeMillis()); + msgCounter = 0; } - } catch (IMTPException | NotFoundException | ServiceException | MTPException imtpe) { - cmd.setReturnValue(imtpe); - } catch (Throwable t) { - t.printStackTrace(); - cmd.setReturnValue(t); } } + //#J2ME_EXCLUDE_END + } - // Vertical command handler methods - - private void handleSendMessage(VerticalCommand cmd) { - Object[] params = cmd.getParams(); - AID sender = (AID) params[0]; - GenericMessage msg = (GenericMessage) params[1]; - AID dest = (AID) params[2]; - // Since message delivery is asynchronous we use the GenericMessage - // as a temporary holder for the sender principal and credentials - msg.setSenderPrincipal(cmd.getPrincipal()); - msg.setSenderCredentials(cmd.getCredentials()); - msg.setSender(sender); - checkTracing(msg); - if (msg.getTraceID() != null) { - myLogger.log(Logger.INFO, "MessagingService source sink handling message " + MessageManager.stringify(msg) + " for receiver " + dest.getName() + ". TraceID = " + msg.getTraceID()); + private void updateDeliveryTimeMeasurement(GenericMessage gmsg) { + //#J2ME_EXCLUDE_BEGIN + if (samActive) { + long timeStamp = gmsg.getTimeStamp(); + if (timeStamp > 0 && deliveryTimeMeasureProvider != null) { + long deliveryTime = System.currentTimeMillis() - timeStamp; + if (myLogger.isLoggable(Logger.FINER)) { + myLogger.log(Logger.FINER, "Delivery time = " + deliveryTime); + } + deliveryTimeMeasureProvider.addSample(deliveryTime); } - if (needSynchDelivery(msg)) { - // Synchronous delivery: skip the MessageManager - deliverNow(msg, dest); + } + //#J2ME_EXCLUDE_END + } + + // Entry point for the ACL message delivery + public void deliverNow(GenericMessage msg, AID receiverID) { + if (msg.getTraceID() != null) { + myLogger.log(Logger.INFO, msg.getTraceID() + " - Serving message delivery"); + } + try { + if (!msg.hasForeignReceiver()) { + deliverInLocalPlatfrom(msg, receiverID); } else { - // Normal (asynchronous) delivery - myMessageManager.deliver(msg, dest, MessagingService.this); + // Dispatch it through the ACC if (msg.getTraceID() != null) { - myLogger.log(Logger.INFO, msg.getTraceID() + " - Message enqueued to MessageManager."); + myLogger.log(Logger.INFO, msg.getTraceID() + " - Activating ACC delivery"); + } + Iterator addresses = receiverID.getAllAddresses(); + if (addresses.hasNext()) { + while (addresses.hasNext()) { + String address = addresses.next(); + try { + forwardMessage(msg, receiverID, address); + return; + } catch (MTPException mtpe) { + if (myLogger.isLoggable(Logger.WARNING) && !isPersistentDeliveryRetry(msg)) + myLogger.log(Logger.WARNING, "Cannot deliver message to address: " + address + " [" + mtpe + "]. Trying the next one..."); + } + } + notifyFailureToSender(msg, receiverID, new InternalError(ACLMessage.AMS_FAILURE_FOREIGN_AGENT_UNREACHABLE + ": " + "No valid address contained within the AID " + receiverID.getName())); + } else { + notifyFailureToSender(msg, receiverID, new InternalError(ACLMessage.AMS_FAILURE_FOREIGN_AGENT_NO_ADDRESS)); } } - } - - private void handleNotifyFailure(VerticalCommand cmd) { - Object[] params = cmd.getParams(); - GenericMessage msg = (GenericMessage) params[0]; - AID receiver = (AID) params[1]; - InternalError ie = (InternalError) params[2]; - - // The acl message contained inside the GenericMessage cannot be null; the notifyFailureToSender() method already checks that - ACLMessage aclmsg = msg.getACLMessage(); - // Sanity check to avoid infinite loops - if ((aclmsg.getSender() == null) || (aclmsg.getSender().equals(myContainer.getAMS()))) { - return; + } catch (NotFoundException nfe) { + // The receiver does not exist --> Send a FAILURE message + if (msg.getTraceID() != null) { + myLogger.log(Logger.WARNING, msg.getTraceID() + " - Receiver " + receiverID.getLocalName() + " does not exist.", nfe); } - if ("true".equals(aclmsg.getUserDefinedParameter(ACLMessage.DONT_NOTIFY_FAILURE))) { - return; + notifyFailureToSender(msg, receiverID, new InternalError(ACLMessage.AMS_FAILURE_AGENT_NOT_FOUND + ": " + nfe.getMessage())); + } catch (IMTPException imtpe) { + // Can't reach the destination container --> Send a FAILURE message + String id = (msg.getTraceID() != null ? msg.getTraceID() : MessageManager.stringify(msg)); + myLogger.log(Logger.WARNING, id + " - Receiver " + receiverID.getLocalName() + " unreachable.", imtpe); + notifyFailureToSender(msg, receiverID, new InternalError(ACLMessage.AMS_FAILURE_AGENT_UNREACHABLE + ": " + imtpe.getMessage())); + } catch (ServiceException se) { + // Service error during delivery --> Send a FAILURE message + String id = (msg.getTraceID() != null ? msg.getTraceID() : MessageManager.stringify(msg)); + myLogger.log(Logger.WARNING, id + " - Service error delivering message.", se); + notifyFailureToSender(msg, receiverID, new InternalError(ACLMessage.AMS_FAILURE_SERVICE_ERROR + ": " + se.getMessage())); + } catch (JADESecurityException jse) { + // Delivery not authorized--> Send a FAILURE message + if (msg.getTraceID() != null) { + myLogger.log(Logger.WARNING, msg.getTraceID() + " - Not authorized.", jse); } + notifyFailureToSender(msg, receiverID, new InternalError(ACLMessage.AMS_FAILURE_UNAUTHORIZED + ": " + jse.getMessage())); + } + } - // Send back a failure message - final ACLMessage failure = aclmsg.createReply(); - failure.setPerformative(ACLMessage.FAILURE); - final AID theAMS = myContainer.getAMS(); - failure.setSender(theAMS); - failure.setLanguage(FIPANames.ContentLanguage.FIPA_SL); - - // FIXME: the content is not completely correct, but that should - // also avoid creating wrong content - String content = "( (action " + msg.getSender().toString(); - content = content + " (ACLMessage) ) (MTS-error " + receiver + " " + ie.getMessage() + ") )"; - failure.setContent(content); - - try { - GenericCommand command = new GenericCommand(MessagingSlice.SEND_MESSAGE, MessagingSlice.NAME, null); - command.addParam(theAMS); - GenericMessage gm = new GenericMessage(failure); - gm.setAMSFailure(true); - command.addParam(gm); - command.addParam(failure.getAllReceiver().next()); - // FIXME: We should set the AMS principal and credentials + private boolean isPersistentDeliveryRetry(GenericMessage msg) { + boolean ret = false; + //#J2ME_EXCLUDE_BEGIN + ACLMessage acl = msg.getACLMessage(); + if (acl != null) { + ret = acl.getAllUserDefinedParameters().containsKey(PersistentDeliveryService.ACL_USERDEF_DUE_DATE); + } + //#J2ME_EXCLUDE_END + return ret; + } - submit(command); - } catch (ServiceException se) { - // It should never happen - se.printStackTrace(); - } + void deliverInLocalPlatfrom(GenericMessage msg, AID receiverID) throws IMTPException, ServiceException, NotFoundException, JADESecurityException { + if (msg.getTraceID() != null) { + myLogger.log(Logger.INFO, msg.getTraceID() + " - Activating local-platform delivery"); } - private MTPDescriptor handleInstallMTP(VerticalCommand cmd) throws IMTPException, ServiceException, NotFoundException, MTPException { - Object[] params = cmd.getParams(); - String address = (String) params[0]; - ContainerID cid = (ContainerID) params[1]; - String className = (String) params[2]; - - MessagingSlice targetSlice = (MessagingSlice) getSlice(cid.getName()); - try { - return targetSlice.installMTP(address, className); - } catch (IMTPException imtpe) { - targetSlice = (MessagingSlice) getFreshSlice(cid.getName()); - return targetSlice.installMTP(address, className); + MainContainer impl = myContainer.getMain(); + if (impl != null) { + // Directly use the GADT on the main container + int attemptsCnt = 0; + while (true) { + ContainerID cid = getAgentLocation(receiverID); + MessagingSlice targetSlice = oneShotDeliver(cid, msg, receiverID); + if (targetSlice != null) { + // Success --> Done + //#J2ME_EXCLUDE_BEGIN + DeliveryTracing.setTracingInfo("Target-node", targetSlice.getNode().getName()); + //#J2ME_EXCLUDE_END + return; + } + checkRetry(receiverID, cid, attemptsCnt); + attemptsCnt++; + } + } else { + // Try first with the cached pairs + MessagingSlice cachedSlice = (MessagingSlice) cachedSlices.get(receiverID); + if (cachedSlice != null) { // Cache hit :-) + try { + if (msg.getTraceID() != null) { + myLogger.log(Logger.INFO, msg.getTraceID() + " - Delivering message to cached slice " + cachedSlice.getNode().getName()); + } + cachedSlice.dispatchLocally(msg.getSender(), msg, receiverID); + if (msg.getTraceID() != null) { + myLogger.log(Logger.INFO, msg.getTraceID() + " - Delivery OK."); + } + //#J2ME_EXCLUDE_BEGIN + DeliveryTracing.setTracingInfo("Target-node", cachedSlice.getNode().getName()); + //#J2ME_EXCLUDE_END + return; + } catch (IMTPException imtpe) { + if (msg.getTraceID() != null) { + myLogger.log(Logger.INFO, msg.getTraceID() + " - Cached slice for receiver " + receiverID.getName() + " unreachable."); + } + } catch (NotFoundException nfe) { + if (msg.getTraceID() != null) { + myLogger.log(Logger.INFO, msg.getTraceID() + " - Receiver " + receiverID.getName() + " not found on cached slice container."); + } + } + // Eliminate stale cache entry + cachedSlices.remove(receiverID); } + + // Either the receiver was not found in cache or the cache entry was no longer valid + //#J2ME_EXCLUDE_BEGIN + DeliveryTracing.setTracingInfo("Messaging-cache-miss", true); + //#J2ME_EXCLUDE_END + deliverUntilOK(msg, receiverID); } + } - private void handleUninstallMTP(VerticalCommand cmd) throws IMTPException, ServiceException, NotFoundException, MTPException { - Object[] params = cmd.getParams(); - String address = (String) params[0]; - ContainerID cid = (ContainerID) params[1]; - MessagingSlice targetSlice = (MessagingSlice) getSlice(cid.getName()); + /////////////////////////////////////////////// + // Message delivery + /////////////////////////////////////////////// + + private void deliverUntilOK(GenericMessage msg, AID receiverID) throws IMTPException, NotFoundException, ServiceException, JADESecurityException { + int attemptsCnt = 0; + while (true) { + ContainerID cid; try { - targetSlice.uninstallMTP(address); - } catch (IMTPException imtpe) { - targetSlice = (MessagingSlice) getFreshSlice(cid.getName()); - targetSlice.uninstallMTP(address); + MessagingSlice mainSlice = (MessagingSlice) getSlice(MAIN_SLICE); + try { + cid = mainSlice.getAgentLocation(receiverID); + } catch (IMTPException imtpe) { + // Try to get a newer slice and repeat... + mainSlice = (MessagingSlice) getFreshSlice(MAIN_SLICE); + cid = mainSlice.getAgentLocation(receiverID); + } + } catch (ServiceException se) { + // This container is no longer able to access the Main --> before propagating the exception + // try to see if the receiver lives locally + if (myContainer.isLocalAgent(receiverID)) { + MessagingSlice localSlice = (MessagingSlice) getIMTPManager().createSliceProxy(getName(), getHorizontalInterface(), getLocalNode()); + localSlice.dispatchLocally(msg.getSender(), msg, receiverID); + //#J2ME_EXCLUDE_BEGIN + DeliveryTracing.setTracingInfo("Target-node", localSlice.getNode().getName()); + //#J2ME_EXCLUDE_END + return; + } else { + throw se; + } } - } - - private void handleNewMTP(VerticalCommand cmd) throws IMTPException, ServiceException { - Object[] params = cmd.getParams(); - MTPDescriptor mtp = (MTPDescriptor) params[0]; - ContainerID cid = (ContainerID) params[1]; - MessagingSlice mainSlice = (MessagingSlice) getSlice(MAIN_SLICE); - try { - mainSlice.newMTP(mtp, cid); - } catch (IMTPException imtpe) { - mainSlice = (MessagingSlice) getFreshSlice(MAIN_SLICE); - mainSlice.newMTP(mtp, cid); + MessagingSlice targetSlice = oneShotDeliver(cid, msg, receiverID); + if (targetSlice != null) { + // Success --> Done + // On successful message dispatch, put the slice into the slice cache + cachedSlices.put(receiverID, targetSlice); + //#J2ME_EXCLUDE_BEGIN + DeliveryTracing.setTracingInfo("Target-node", targetSlice.getNode().getName()); + //#J2ME_EXCLUDE_END + return; } + checkRetry(receiverID, cid, attemptsCnt); + attemptsCnt++; } + } - private void handleDeadMTP(VerticalCommand cmd) throws IMTPException, ServiceException { - Object[] params = cmd.getParams(); - MTPDescriptor mtp = (MTPDescriptor) params[0]; - ContainerID cid = (ContainerID) params[1]; + private MessagingSlice oneShotDeliver(ContainerID cid, GenericMessage msg, AID receiverID) throws IMTPException, ServiceException, JADESecurityException { + if (msg.getTraceID() != null) { + myLogger.log(Logger.FINER, msg.getTraceID() + " - Receiver " + receiverID.getLocalName() + " lives on container " + cid.getName()); + } - MessagingSlice mainSlice = (MessagingSlice) getSlice(MAIN_SLICE); + MessagingSlice targetSlice = (MessagingSlice) getSlice(cid.getName()); + try { try { - mainSlice.deadMTP(mtp, cid); + if (msg.getTraceID() != null) { + myLogger.log(Logger.INFO, msg.getTraceID() + " - Delivering message to slice " + targetSlice.getNode().getName()); + } + targetSlice.dispatchLocally(msg.getSender(), msg, receiverID); } catch (IMTPException imtpe) { - mainSlice = (MessagingSlice) getFreshSlice(MAIN_SLICE); - mainSlice.deadMTP(mtp, cid); + // Try to get a newer slice and repeat... + if (msg.getTraceID() != null) { + myLogger.log(Logger.FINER, msg.getTraceID() + " - Messaging slice on container " + cid.getName() + " unreachable. Try to get a fresh one."); + } + + targetSlice = (MessagingSlice) getFreshSlice(cid.getName()); + if (msg.getTraceID() != null && (targetSlice != null)) { + myLogger.log(Logger.FINER, msg.getTraceID() + " - Fresh slice for container " + cid.getName() + " found."); + } + + targetSlice.dispatchLocally(msg.getSender(), msg, receiverID); + } + if (msg.getTraceID() != null) { + myLogger.log(Logger.INFO, msg.getTraceID() + " - Delivery OK"); + } + return targetSlice; + } catch (NotFoundException nfe) { + // The agent was found in the GADT, but not on the container where it is supposed to + // be. Possibly it moved elsewhere in the meanwhile. ==> Try again. + if (msg.getTraceID() != null) { + myLogger.log(Logger.FINER, msg.getTraceID() + " - Receiver " + receiverID.getLocalName() + " not found on container " + cid.getName() + ". Possibly he moved elsewhere --> Retry"); + } + } catch (NullPointerException npe) { + // This is thrown if targetSlice is null: The agent was found in the GADT, + // but his container does not exist anymore. Possibly the agent moved elsewhere in + // the meanwhile ==> Try again. + if (msg.getTraceID() != null) { + myLogger.log(Logger.FINER, msg.getTraceID() + " - Container " + cid.getName() + " for receiver " + receiverID.getLocalName() + " does not exist anymore. Possibly the receiver moved elsewhere --> Retry"); } + } + + return null; + } + private void checkRetry(AID receiver, ContainerID cid, int attemptsCnt) throws NotFoundException { + if (maxDeliveryRetryAttempts >= 0 && attemptsCnt >= maxDeliveryRetryAttempts) { + throw new NotFoundException("Agent " + receiver.getLocalName() + " not found in container " + cid.getName() + " where it was supposed to be"); + } + // Wait a bit before enabling next delivery attempt + try { + Thread.sleep(200); + } catch (InterruptedException ie) { } + } - private void handleSetPlatformAddresses(VerticalCommand cmd) { - Object[] params = cmd.getParams(); - AID id = (AID) params[0]; - id.clearAllAddresses(); - addPlatformAddresses(id); + private void forwardMessage(GenericMessage msg, AID receiver, String address) throws MTPException { + // FIXME what if there is no envelope? + AID aid = msg.getEnvelope().getFrom(); + + if (aid == null) { + //System.err.println("ERROR: null message sender. Aborting message dispatch..."); + if (myLogger.isLoggable(Logger.SEVERE)) + myLogger.log(Logger.SEVERE, "ERROR: null message sender. Aborting message dispatch..."); + return; } - } // END of inner class CommandSourceSink + // FIXME The message can no longer be updated + // if has no address set, then adds the addresses of this platform + if (!aid.getAllAddresses().hasNext()) + addPlatformAddresses(aid); + + try { + if (msg.getTraceID() != null) { + myLogger.log(Logger.INFO, msg.getTraceID() + " - Routing message out to address " + address); + msg.getEnvelope().addProperties(new Property(ACLMessage.TRACE, msg.getTraceID())); + } + localSlice.routeOut(msg.getEnvelope(), msg.getPayload(), receiver, address); + } catch (IMTPException imtpe) { + throw new MTPException("Error during message routing", imtpe); + } + } /** - * Inner class CommandTargetSink + * This method is used internally by the platform in order + * to notify the sender of a message that a failure was reported by + * the Message Transport Service. */ - private class CommandTargetSink implements Sink { - - public void consume(VerticalCommand cmd) { + public void notifyFailureToSender(GenericMessage msg, AID receiver, InternalError ie) { + //#J2ME_EXCLUDE_BEGIN + // If msg represents a MultipleGenericMessage, recursive call notifyFailureToSender() for each msg + if (msg instanceof MultipleGenericMessage) { + for (GenericMessage g : ((MultipleGenericMessage) msg).getMessages()) { + notifyFailureToSender(g, receiver, ie); + } + return; + } + //#J2ME_EXCLUDE_END + ACLMessage acl = msg.getACLMessage(); + if (acl == null) { + // ACLMessage can be null in case we get a failure delivering a message coming from an external platform (received by a local MTP). + // In this case in fact the message is encoded. Try to decode it so that a suitable FAILURE response can be sent back. + // If the payload is mangled in some way (e.g. encrypted) decoding will fail and no suitable FAILURE response will be sent try { - String name = cmd.getName(); - switch (name) { - case MessagingSlice.SEND_MESSAGE -> handleSendMessage(cmd); - case MessagingSlice.INSTALL_MTP -> { - Object result = handleInstallMTP(cmd); - cmd.setReturnValue(result); - } - case MessagingSlice.UNINSTALL_MTP -> handleUninstallMTP(cmd); - case MessagingSlice.NEW_MTP -> handleNewMTP(cmd); - case MessagingSlice.DEAD_MTP -> handleDeadMTP(cmd); - case MessagingSlice.SET_PLATFORM_ADDRESSES -> handleSetPlatformAddresses(cmd); - case Service.NEW_SLICE -> handleNewSlice(cmd); - } - } catch (IMTPException | NotFoundException | ServiceException | MTPException imtpe) { - cmd.setReturnValue(imtpe); + acl = encInFilter.decodeMessage(msg.getEnvelope(), msg.getPayload()); + acl.setEnvelope(msg.getEnvelope()); + msg.setACLMessage(acl); + } catch (Exception e) { + // Just do nothing + e.printStackTrace(); } } + if (acl == null) { + myLogger.log(Logger.WARNING, "Cannot notify failure to sender: GenericMessage contains no ACLMessage"); + return; + } + if ("true".equals(acl.getUserDefinedParameter(ACLMessage.IGNORE_FAILURE))) { + // Ignore the failure + return; + } - private void handleSendMessage(VerticalCommand cmd) throws NotFoundException { - Object[] params = cmd.getParams(); - AID senderID = (AID) params[0]; - GenericMessage gMsg = (GenericMessage) params[1]; - AID receiverID = (AID) params[2]; - receiverID = resolveLocalAlias(receiverID); - - //#J2ME_EXCLUDE_BEGIN - if (gMsg instanceof MultipleGenericMessage) { - // Multiple-message delivery case. - List gmm = ((MultipleGenericMessage) gMsg).getMessages(); - ACLMessage[] mm = new ACLMessage[gmm.size()]; - int k = 0; - for (GenericMessage g : gmm) { - if (g.getTraceID() != null) { - myLogger.log(Logger.INFO, g.getTraceID() + " - MessagingService target sink posting message to receiver " + receiverID.getLocalName()); - } - ACLMessage msg = g.getACLMessage(); - if (!msg.getSender().equals(g.getSender()) && g.getSender() != null) { - myLogger.log(Logger.FINE, "Attaching real-sender user defined parameter: " + g.getSender().getName()); - // Sender indicated in the message different than the real sender --> store the latter in the REAL_SENDER user defined param - msg.addUserDefinedParameter(ACLMessage.REAL_SENDER, g.getSender().getName()); - } - mm[k] = msg; - k++; - } + GenericCommand cmd = new GenericCommand(MessagingSlice.NOTIFY_FAILURE, MessagingSlice.NAME, null); + cmd.addParam(msg); + cmd.addParam(receiver); + cmd.addParam(ie); - boolean found = myContainer.postMessagesBlockToLocalAgent(mm, receiverID); - if (!found) { - throw new NotFoundException("Messaging service slice failed to find " + receiverID); - } + try { + submit(cmd); + } catch (ServiceException se) { + // It should never happen + se.printStackTrace(); + } + } - for (GenericMessage g : gmm) { - postedMessageCounter++; - updateDeliveryTimeMeasurement(g); - if (g.getTraceID() != null) { - myLogger.log(Logger.INFO, g.getTraceID() + " - Message posted"); + /* + * This method is called before preparing the Envelope of an outgoing message. + * It checks for all the AIDs present in the message and adds the addresses, if not present + **/ + private void addPlatformAddresses(AID id) { + Iterator it = routes.getAddresses(); + while (it.hasNext()) { + String addr = it.next(); + id.addAddresses(addr); + } + } + + // Package scoped since it is accessed by the OutgoingEncoding filter + final boolean livesHere(AID id) { + if (!acceptForeignAgents) { + // All agents in the platform must have a name with the form + // @ + String hap = id.getHap(); + return CaseInsensitiveString.equalsIgnoreCase(hap, platformID); + } else { + String[] addresses = id.getAddressesArray(); + if (addresses.length == 0) { + return true; + } else { + boolean allLocalAddresses = true; + for (String address : addresses) { + if (!isPlatformAddress(address)) { + allLocalAddresses = false; + break; } } - return; - } - //#J2ME_EXCLUDE_END + if (allLocalAddresses) { + return true; + } else { + // Check in the GADT + try { + MainContainer impl = myContainer.getMain(); + if (impl != null) { + // Directly use the GADT on the main container + getAgentLocation(id); + } else { + // Use the main slice + MessagingSlice mainSlice = (MessagingSlice) getSlice(MAIN_SLICE); + try { + mainSlice.getAgentLocation(id); + } catch (IMTPException imtpe) { + // Try to get a newer slice and repeat... + mainSlice = (MessagingSlice) getFreshSlice(MAIN_SLICE); + mainSlice.getAgentLocation(id); + } + } + return true; + } catch (Exception nfe) { + // The agent does not live in the platform + return false; + }// Intra-platform delivery would fail, so try inter-platform - // Normal (single-message delivery) case - if (gMsg.getTraceID() != null) { - myLogger.log(Logger.INFO, gMsg.getTraceID() + " - MessagingService target sink posting message to receiver " + receiverID.getLocalName()); - } - postMessage(senderID, gMsg.getACLMessage(), receiverID); - //#J2ME_EXCLUDE_BEGIN - postedMessageCounter++; - updateDeliveryTimeMeasurement(gMsg); - //#J2ME_EXCLUDE_END - if (gMsg.getTraceID() != null) { - myLogger.log(Logger.INFO, gMsg.getTraceID() + " - Message posted"); + } } } + } - private void manageMessage(AID senderID, GenericMessage msg, AID receiverID) throws NotFoundException { - //#J2ME_EXCLUDE_BEGIN - // If gmsg represents a MultipleGenericMessage recursively call restore() for each message - if (msg instanceof MultipleGenericMessage) { - System.out.println("Multiple delivery: posting " + ((MultipleGenericMessage) msg).getMessages().size() + " messages to receiver " + receiverID.getLocalName()); - for (GenericMessage g : ((MultipleGenericMessage) msg).getMessages()) { - manageMessage(g.getSender(), g, receiverID); - } - return; + private boolean isPlatformAddress(String addr) { + Iterator it = routes.getAddresses(); + while (it.hasNext()) { + String ad = it.next(); + if (CaseInsensitiveString.equalsIgnoreCase(ad, addr)) { + return true; } - //#J2ME_EXCLUDE_END + } + return false; + } - if (msg.getTraceID() != null) { - myLogger.log(Logger.INFO, msg.getTraceID() + " - MessagingService target sink posting message to receiver " + receiverID.getLocalName()); - } - postMessage(senderID, msg.getACLMessage(), receiverID); - //#J2ME_EXCLUDE_BEGIN - postedMessageCounter++; - updateDeliveryTimeMeasurement(msg); - //#J2ME_EXCLUDE_END - if (msg.getTraceID() != null) { - myLogger.log(Logger.INFO, msg.getTraceID() + " - Message posted"); + // Work-around for PJAVA compilation + protected Slice getFreshSlice(String name) throws ServiceException { + return super.getFreshSlice(name); + } - } + private boolean needSynchDelivery(GenericMessage gMsg) { + ACLMessage acl = gMsg.getACLMessage(); + if (acl != null) { + return "true".equals(acl.clearUserDefinedParameter(ACLMessage.SYNCH_DELIVERY)); } + return false; + } - private MTPDescriptor handleInstallMTP(VerticalCommand cmd) throws IMTPException, ServiceException, MTPException { - Object[] params = cmd.getParams(); - String address = (String) params[0]; - String className = (String) params[1]; + private void checkTracing(GenericMessage msg) { + ACLMessage acl = msg.getACLMessage(); + if (acl != null) { + if (myLogger.isLoggable(Logger.FINE) || "true".equals(acl.getUserDefinedParameter(ACLMessage.TRACE))) { + msg.setTraceID(ACLMessage.getPerformative(acl.getPerformative()) + "-" + msg.getSender().getLocalName() + "-" + traceCnt); + traceCnt++; + } + } + } - return installMTP(address, className); + private String getTraceId(Envelope env) { + Iterator it = env.getAllProperties(); + while (it.hasNext()) { + Property p = it.next(); + if (p.getName().equals(ACLMessage.TRACE)) { + return (String) p.getValue(); + } } + return null; + } - private void handleUninstallMTP(VerticalCommand cmd) throws IMTPException, ServiceException, NotFoundException, MTPException { - Object[] params = cmd.getParams(); - String address = (String) params[0]; + // For debugging purpose + public String[] getMessageManagerQueueStatus() { + return myMessageManager.getQueueStatus(); + } - uninstallMTP(address); - } + // For debugging purpose + public String[] getMessageManagerThreadPoolStatus() { + return myMessageManager.getThreadPoolStatus(); + } - private void handleNewMTP(VerticalCommand cmd) throws IMTPException, ServiceException { - Object[] params = cmd.getParams(); - MTPDescriptor mtp = (MTPDescriptor) params[0]; - ContainerID cid = (ContainerID) params[1]; + // For debugging purpose + public String getMessageManagerGlobalInfo() { + return myMessageManager.getGlobalInfo(); + } - newMTP(mtp, cid); + // For debugging purpose + public Thread[] getMessageManagerThreadPool() { + return myMessageManager.getThreadPool(); + } + + protected void clearCachedSlice(String name) { + if (cachedSlices != null) { + cachedSlices.clear(); + myLogger.log(Logger.CONFIG, "Clearing cache"); } + super.clearCachedSlice(name); + } - private void handleDeadMTP(VerticalCommand cmd) throws IMTPException, ServiceException { - Object[] params = cmd.getParams(); - MTPDescriptor mtp = (MTPDescriptor) params[0]; - ContainerID cid = (ContainerID) params[1]; + public String dump(String key) { + StringBuilder sb = new StringBuilder("LOCAL ALIASES:\n"); + if (localAliases.size() > 0) { + sb.append(stringifyAliasesMap(localAliases)); + } else { + sb.append("---\n"); + } - deadMTP(mtp, cid); + if (globalAliases != null) { + sb.append("GLOBAL ALIASES:\n"); + if (globalAliases.size() > 0) { + sb.append(stringifyAliasesMap(globalAliases)); + } else { + sb.append("---\n"); + } } + return sb.toString(); + } - private void handleSetPlatformAddresses(VerticalCommand cmd) { + private String stringifyAliasesMap(Hashtable aliases) { + StringBuilder sb = new StringBuilder(); + for (Object o : aliases.keySet()) { + AID alias = (AID) o; + AID agent = aliases.get(alias); + sb.append("- ").append(alias.getLocalName()).append(" --> ").append(agent.getLocalName()).append("\n"); } + return sb.toString(); + } - private void handleNewSlice(VerticalCommand cmd) { - MainContainer impl = myContainer.getMain(); - if (impl != null) { - Object[] params = cmd.getParams(); - String newSliceName = (String) params[0]; - try { - // Be sure to get the new (fresh) slice --> Bypass the service cache - MessagingSlice newSlice = (MessagingSlice) getFreshSlice(newSliceName); + public static class UnknownACLEncodingException extends NotFoundException { + UnknownACLEncodingException(String msg) { + super(msg); + } + } // End of UnknownACLEncodingException class - // Send all possible routes to the new slice - ContainerID[] cids = impl.containerIDs(); - for (ContainerID cid : cids) { - try { - List mtps = impl.containerMTPs(cid); - for (MTPDescriptor o : mtps) { - newSlice.addRoute(o, cid.getName()); - } - } catch (NotFoundException nfe) { - // Should never happen - nfe.printStackTrace(); - } - } + /** + * Inner class CommandSourceSink + * This inner class handles the messaging commands on the command + * issuer side, turning them into horizontal commands and + * forwarding them to remote slices when necessary. + */ + private class CommandSourceSink implements Sink { - // If the new slice is on a replicated Main Container send it all current aliases - if (newSlice.getNode().hasPlatformManager()) { - newSlice.currentAliases(globalAliases); + public void consume(VerticalCommand cmd) { + + try { + String name = cmd.getName(); + + switch (name) { + case MessagingSlice.SEND_MESSAGE -> handleSendMessage(cmd); + case MessagingSlice.NOTIFY_FAILURE -> handleNotifyFailure(cmd); + case MessagingSlice.INSTALL_MTP -> { + Object result = handleInstallMTP(cmd); + cmd.setReturnValue(result); } - } catch (ServiceException se) { - // Should never happen since getSlice() should always work on the Main container - se.printStackTrace(); - } catch (IMTPException imtpe) { - myLogger.log(Logger.WARNING, "Error notifying current information to new Messaging-Slice " + newSliceName, imtpe); + case MessagingSlice.UNINSTALL_MTP -> handleUninstallMTP(cmd); + case MessagingSlice.NEW_MTP -> handleNewMTP(cmd); + case MessagingSlice.DEAD_MTP -> handleDeadMTP(cmd); + case MessagingSlice.SET_PLATFORM_ADDRESSES -> handleSetPlatformAddresses(cmd); } + } catch (IMTPException | NotFoundException | ServiceException | MTPException imtpe) { + cmd.setReturnValue(imtpe); + } catch (Throwable t) { + t.printStackTrace(); + cmd.setReturnValue(t); } } - private void postMessage(AID senderID, ACLMessage msg, AID receiverID) throws NotFoundException { - if (!msg.getSender().equals(senderID)) { - myLogger.log(Logger.FINE, "Attaching real-sender user defined parameter: " + senderID.getName()); - // Sender indicated in the message different than the real sender --> store the latter in the REAL_SENDER user defined param - msg.addUserDefinedParameter(ACLMessage.REAL_SENDER, senderID.getName()); + // Vertical command handler methods + + private void handleSendMessage(VerticalCommand cmd) { + Object[] params = cmd.getParams(); + AID sender = (AID) params[0]; + GenericMessage msg = (GenericMessage) params[1]; + AID dest = (AID) params[2]; + // Since message delivery is asynchronous we use the GenericMessage + // as a temporary holder for the sender principal and credentials + msg.setSenderPrincipal(cmd.getPrincipal()); + msg.setSenderCredentials(cmd.getCredentials()); + msg.setSender(sender); + checkTracing(msg); + if (msg.getTraceID() != null) { + myLogger.log(Logger.INFO, "MessagingService source sink handling message " + MessageManager.stringify(msg) + " for receiver " + dest.getName() + ". TraceID = " + msg.getTraceID()); } - boolean found = myContainer.postMessageToLocalAgent(msg, receiverID); - if (!found) { - throw new NotFoundException("Messaging service slice failed to find " + receiverID); + if (needSynchDelivery(msg)) { + // Synchronous delivery: skip the MessageManager + deliverNow(msg, dest); + } else { + // Normal (asynchronous) delivery + myMessageManager.deliver(msg, dest, MessagingService.this); + if (msg.getTraceID() != null) { + myLogger.log(Logger.INFO, msg.getTraceID() + " - Message enqueued to MessageManager."); + } } } - private MTPDescriptor installMTP(String address, String className) throws ServiceException, MTPException { - - try { - // Create the MTP - Class c = Class.forName(className); - MTP proto = null; - try { - proto = (MTP) c.getDeclaredConstructor().newInstance(); - } catch (IllegalArgumentException | InvocationTargetException | NoSuchMethodException - | SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - InChannel.Dispatcher dispatcher = (env, payload) -> { - //log("Message from remote platform received", 2); + private void handleNotifyFailure(VerticalCommand cmd) { + Object[] params = cmd.getParams(); + GenericMessage msg = (GenericMessage) params[0]; + AID receiver = (AID) params[1]; + InternalError ie = (InternalError) params[2]; - if (myLogger.isLoggable(Logger.FINE)) - myLogger.log(Logger.FINE, "Message from remote platform received"); + // The acl message contained inside the GenericMessage cannot be null; the notifyFailureToSender() method already checks that + ACLMessage aclmsg = msg.getACLMessage(); + // Sanity check to avoid infinite loops + if ((aclmsg.getSender() == null) || (aclmsg.getSender().equals(myContainer.getAMS()))) { + return; + } + if ("true".equals(aclmsg.getUserDefinedParameter(ACLMessage.DONT_NOTIFY_FAILURE))) { + return; + } - // To avoid message loops, make sure that the ID of this ACC does - // not appear in a previous 'received' stamp + // Send back a failure message + final ACLMessage failure = aclmsg.createReply(); + failure.setPerformative(ACLMessage.FAILURE); + final AID theAMS = myContainer.getAMS(); + failure.setSender(theAMS); + failure.setLanguage(FIPANames.ContentLanguage.FIPA_SL); - ReceivedObject[] stamps = env.getStamps(); - for (ReceivedObject stamp : stamps) { - String id = stamp.getBy(); - if (CaseInsensitiveString.equalsIgnoreCase(id, accID)) { - System.err.println("ERROR: Message loop detected !!!"); - System.err.println("Route is: "); - for (int j = 0; j < stamps.length; j++) - System.err.println("[" + j + "]" + stamps[j].getBy()); - System.err.println("Message dispatch aborted."); - return; - } - } + // FIXME: the content is not completely correct, but that should + // also avoid creating wrong content + String content = "( (action " + msg.getSender().toString(); + content = content + " (ACLMessage) ) (MTS-error " + receiver + " " + ie.getMessage() + ") )"; + failure.setContent(content); - // Put a 'received-object' stamp in the envelope - ReceivedObject ro = new ReceivedObject(); - ro.setBy(accID); - ro.setDate(new Date()); - env.setReceived(ro); + try { + GenericCommand command = new GenericCommand(MessagingSlice.SEND_MESSAGE, MessagingSlice.NAME, null); + command.addParam(theAMS); + GenericMessage gm = new GenericMessage(failure); + gm.setAMSFailure(true); + command.addParam(gm); + command.addParam(failure.getAllReceiver().next()); + // FIXME: We should set the AMS principal and credentials - Iterator it = env.getAllIntendedReceiver(); - // FIXME: There is a problem if no 'intended-receiver' is present, - // but this should not happen - while (it.hasNext()) { - AID rcv = it.next(); - GenericMessage msg = new GenericMessage(env, payload); - String traceId = getTraceId(env); - if (traceId != null) { - myLogger.log(Logger.INFO, "MTP In-Channel handling message from the outside for receiver " + rcv.getName() + ". TraceID = " + traceId); - msg.setTraceID(traceId); - } - myMessageManager.deliver(msg, rcv, MessagingService.this); - } - }; + submit(command); + } catch (ServiceException se) { + // It should never happen + se.printStackTrace(); + } + } - if (address == null) { - // Let the MTP choose the address - TransportAddress ta = proto.activate(dispatcher, myProfile); - address = proto.addrToStr(ta); - } else { - // Convert the given string into a TransportAddress object and use it - TransportAddress ta = proto.strToAddr(address); - proto.activate(dispatcher, ta, myProfile); - } - MTPDescriptor result = new MTPDescriptor(proto.getName(), className, new String[]{address}, proto.getSupportedProtocols()); - routes.addLocalMTP(address, proto, result); + private MTPDescriptor handleInstallMTP(VerticalCommand cmd) throws IMTPException, ServiceException, NotFoundException, MTPException { + Object[] params = cmd.getParams(); + String address = (String) params[0]; + ContainerID cid = (ContainerID) params[1]; + String className = (String) params[2]; - String[] pp = result.getSupportedProtocols(); - for (String value : pp) { - //log("Added Route-Via-MTP for protocol "+pp[i], 1); - if (myLogger.isLoggable(Logger.CONFIG)) - myLogger.log(Logger.CONFIG, "Added Route-Via-MTP for protocol " + value); + MessagingSlice targetSlice = (MessagingSlice) getSlice(cid.getName()); + try { + return targetSlice.installMTP(address, className); + } catch (IMTPException imtpe) { + targetSlice = (MessagingSlice) getFreshSlice(cid.getName()); + return targetSlice.installMTP(address, className); + } + } - } + private void handleUninstallMTP(VerticalCommand cmd) throws IMTPException, ServiceException, NotFoundException, MTPException { + Object[] params = cmd.getParams(); + String address = (String) params[0]; + ContainerID cid = (ContainerID) params[1]; - String[] addresses = result.getAddresses(); - for (String s : addresses) { - myContainer.addAddressToLocalAgents(s); - } + MessagingSlice targetSlice = (MessagingSlice) getSlice(cid.getName()); + try { + targetSlice.uninstallMTP(address); + } catch (IMTPException imtpe) { + targetSlice = (MessagingSlice) getFreshSlice(cid.getName()); + targetSlice.uninstallMTP(address); + } + } - GenericCommand gCmd = new GenericCommand(MessagingSlice.NEW_MTP, MessagingSlice.NAME, null); - gCmd.addParam(result); - gCmd.addParam(myContainer.getID()); - submit(gCmd); + private void handleNewMTP(VerticalCommand cmd) throws IMTPException, ServiceException { + Object[] params = cmd.getParams(); + MTPDescriptor mtp = (MTPDescriptor) params[0]; + ContainerID cid = (ContainerID) params[1]; - return result; - } - /*#DOTNET_INCLUDE_BEGIN - catch(System.TypeLoadException tle) - { - ClassNotFoundException cnfe = new ClassNotFoundException(tle.get_Message()); - throw new MTPException("The class " + className + " raised IllegalAccessException (see nested exception)", cnfe); - } - catch(System.TypeInitializationException tie) - { - InstantiationException ie = new InstantiationException(tie.get_Message()); - throw new MTPException("The class " + className + " raised InstantiationException (see nested exception)", ie); - } - #DOTNET_INCLUDE_END*/ catch (ClassNotFoundException cnfe) { - throw new MTPException("ERROR: The class " + className + " for the " + address + " MTP was not found"); - } catch (InstantiationException ie) { - throw new MTPException("The class " + className + " raised InstantiationException (see nested exception)", ie); - } catch (IllegalAccessException iae) { - throw new MTPException("The class " + className + " raised IllegalAccessException (see nested exception)", iae); + MessagingSlice mainSlice = (MessagingSlice) getSlice(MAIN_SLICE); + try { + mainSlice.newMTP(mtp, cid); + } catch (IMTPException imtpe) { + mainSlice = (MessagingSlice) getFreshSlice(MAIN_SLICE); + mainSlice.newMTP(mtp, cid); } } - private void uninstallMTP(String address) throws ServiceException, MTPException { + private void handleDeadMTP(VerticalCommand cmd) throws IMTPException, ServiceException { + Object[] params = cmd.getParams(); + MTPDescriptor mtp = (MTPDescriptor) params[0]; + ContainerID cid = (ContainerID) params[1]; - MTPInfo info = routes.removeLocalMTP(address); - if (info != null) { - MTP proto = info.getMTP(); - TransportAddress ta = proto.strToAddr(address); - proto.deactivate(ta); - MTPDescriptor desc = info.getDescriptor(); - //MTPDescriptor desc = new MTPDescriptor(proto.getName(), proto.getClass().getName(), new String[] {address}, proto.getSupportedProtocols()); + MessagingSlice mainSlice = (MessagingSlice) getSlice(MAIN_SLICE); + try { + mainSlice.deadMTP(mtp, cid); + } catch (IMTPException imtpe) { + mainSlice = (MessagingSlice) getFreshSlice(MAIN_SLICE); + mainSlice.deadMTP(mtp, cid); + } - String[] addresses = desc.getAddresses(); - for (String s : addresses) { - myContainer.removeAddressFromLocalAgents(s); - } + } - GenericCommand gCmd = new GenericCommand(MessagingSlice.DEAD_MTP, MessagingSlice.NAME, null); - gCmd.addParam(desc); - gCmd.addParam(myContainer.getID()); - submit(gCmd); - } else { - throw new MTPException("No such address was found on this container: " + address); - } + private void handleSetPlatformAddresses(VerticalCommand cmd) { + Object[] params = cmd.getParams(); + AID id = (AID) params[0]; + id.clearAllAddresses(); + addPlatformAddresses(id); } - private void newMTP(MTPDescriptor mtp, ContainerID cid) throws IMTPException, ServiceException { - MainContainer impl = myContainer.getMain(); + } // END of inner class CommandSourceSink - if (impl != null) { + /** + * Inner class CommandTargetSink + */ + private class CommandTargetSink implements Sink { - // Update the routing tables of all the other slices - Slice[] slices = getAllSlices(); - for (Slice value : slices) { - try { - MessagingSlice slice = (MessagingSlice) value; - String sliceName = slice.getNode().getName(); - if (!sliceName.equals(cid.getName())) { - slice.addRoute(mtp, cid.getName()); - } - } catch (Throwable t) { - // Re-throw allowed exceptions - if (t instanceof IMTPException) { - throw (IMTPException) t; - } - if (t instanceof ServiceException) { - throw (ServiceException) t; - } - //System.err.println("### addRoute() threw " + t.getClass().getName() + " ###"); - myLogger.log(Logger.WARNING, "### addRoute() threw " + t + " ###"); + public void consume(VerticalCommand cmd) { + + try { + String name = cmd.getName(); + switch (name) { + case MessagingSlice.SEND_MESSAGE -> handleSendMessage(cmd); + case MessagingSlice.INSTALL_MTP -> { + Object result = handleInstallMTP(cmd); + cmd.setReturnValue(result); } + case MessagingSlice.UNINSTALL_MTP -> handleUninstallMTP(cmd); + case MessagingSlice.NEW_MTP -> handleNewMTP(cmd); + case MessagingSlice.DEAD_MTP -> handleDeadMTP(cmd); + case MessagingSlice.SET_PLATFORM_ADDRESSES -> handleSetPlatformAddresses(cmd); + case Service.NEW_SLICE -> handleNewSlice(cmd); } - impl.newMTP(mtp, cid); - } else { - // Do nothing for now, but could also route the command to the main slice, thus enabling e.g. AMS replication + } catch (IMTPException | NotFoundException | ServiceException | MTPException imtpe) { + cmd.setReturnValue(imtpe); } } - private void deadMTP(MTPDescriptor mtp, ContainerID cid) throws IMTPException, ServiceException { - MainContainer impl = myContainer.getMain(); + private void handleSendMessage(VerticalCommand cmd) throws NotFoundException { + Object[] params = cmd.getParams(); + AID senderID = (AID) params[0]; + GenericMessage gMsg = (GenericMessage) params[1]; + AID receiverID = (AID) params[2]; + receiverID = resolveLocalAlias(receiverID); - if (impl != null) { + //#J2ME_EXCLUDE_BEGIN + if (gMsg instanceof MultipleGenericMessage) { + // Multiple-message delivery case. + List gmm = ((MultipleGenericMessage) gMsg).getMessages(); + ACLMessage[] mm = new ACLMessage[gmm.size()]; + int k = 0; + for (GenericMessage g : gmm) { + if (g.getTraceID() != null) { + myLogger.log(Logger.INFO, g.getTraceID() + " - MessagingService target sink posting message to receiver " + receiverID.getLocalName()); + } + ACLMessage msg = g.getACLMessage(); + if (!msg.getSender().equals(g.getSender()) && g.getSender() != null) { + myLogger.log(Logger.FINE, "Attaching real-sender user defined parameter: " + g.getSender().getName()); + // Sender indicated in the message different than the real sender --> store the latter in the REAL_SENDER user defined param + msg.addUserDefinedParameter(ACLMessage.REAL_SENDER, g.getSender().getName()); + } + mm[k] = msg; + k++; + } - // Update the routing tables of all the other slices - Slice[] slices = getAllSlices(); - for (Slice value : slices) { - try { - MessagingSlice slice = (MessagingSlice) value; - String sliceName = slice.getNode().getName(); - if (!sliceName.equals(cid.getName())) { - slice.removeRoute(mtp, cid.getName()); - } - } catch (Throwable t) { - // Re-throw allowed exceptions - if (t instanceof IMTPException) { - throw (IMTPException) t; - } - if (t instanceof ServiceException) { - throw (ServiceException) t; - } + boolean found = myContainer.postMessagesBlockToLocalAgent(mm, receiverID); + if (!found) { + throw new NotFoundException("Messaging service slice failed to find " + receiverID); + } - myLogger.log(Logger.WARNING, "### removeRoute() threw " + t + " ###"); + for (GenericMessage g : gmm) { + postedMessageCounter++; + updateDeliveryTimeMeasurement(g); + if (g.getTraceID() != null) { + myLogger.log(Logger.INFO, g.getTraceID() + " - Message posted"); } } - impl.deadMTP(mtp, cid); - } else { - // Do nothing for now, but could also route the command to the main slice, thus enabling e.g. AMS replication + return; + } + //#J2ME_EXCLUDE_END + + // Normal (single-message delivery) case + if (gMsg.getTraceID() != null) { + myLogger.log(Logger.INFO, gMsg.getTraceID() + " - MessagingService target sink posting message to receiver " + receiverID.getLocalName()); + } + postMessage(senderID, gMsg.getACLMessage(), receiverID); + //#J2ME_EXCLUDE_BEGIN + postedMessageCounter++; + updateDeliveryTimeMeasurement(gMsg); + //#J2ME_EXCLUDE_END + if (gMsg.getTraceID() != null) { + myLogger.log(Logger.INFO, gMsg.getTraceID() + " - Message posted"); } } - } // END of inner class CommandTargetSink + private void manageMessage(AID senderID, GenericMessage msg, AID receiverID) throws NotFoundException { + //#J2ME_EXCLUDE_BEGIN + // If gmsg represents a MultipleGenericMessage recursively call restore() for each message + if (msg instanceof MultipleGenericMessage) { + System.out.println("Multiple delivery: posting " + ((MultipleGenericMessage) msg).getMessages().size() + " messages to receiver " + receiverID.getLocalName()); + for (GenericMessage g : ((MultipleGenericMessage) msg).getMessages()) { + manageMessage(g.getSender(), g, receiverID); + } + return; + } + //#J2ME_EXCLUDE_END - /** - * Inner class for this service: this class receives commands from - * service Sink and serves them, coordinating with - * remote parts of this service through the Slice - * interface (that extends the Service.Slice - * interface). - */ - private class ServiceComponent implements Slice { - // Implementation of the Service.Slice interface - public Service getService() { - return MessagingService.this; - } + if (msg.getTraceID() != null) { + myLogger.log(Logger.INFO, msg.getTraceID() + " - MessagingService target sink posting message to receiver " + receiverID.getLocalName()); + } + postMessage(senderID, msg.getACLMessage(), receiverID); + //#J2ME_EXCLUDE_BEGIN + postedMessageCounter++; + updateDeliveryTimeMeasurement(msg); + //#J2ME_EXCLUDE_END + if (msg.getTraceID() != null) { + myLogger.log(Logger.INFO, msg.getTraceID() + " - Message posted"); - public Node getNode() throws ServiceException { - try { - return MessagingService.this.getLocalNode(); - } catch (IMTPException imtpe) { - throw new ServiceException("Problem in contacting the IMTP Manager", imtpe); } } - public VerticalCommand serve(HorizontalCommand cmd) { - VerticalCommand result = null; - try { - String cmdName = cmd.getName(); - Object[] params = cmd.getParams(); + private MTPDescriptor handleInstallMTP(VerticalCommand cmd) throws IMTPException, ServiceException, MTPException { + Object[] params = cmd.getParams(); + String address = (String) params[0]; + String className = (String) params[1]; - switch (cmdName) { - case MessagingSlice.H_DISPATCHLOCALLY -> { - GenericCommand gCmd = new GenericCommand(MessagingSlice.SEND_MESSAGE, MessagingSlice.NAME, null); - AID senderAID = (AID) params[0]; - GenericMessage msg = (GenericMessage) params[1]; - AID receiverID = (AID) params[2]; - if (params.length == 4) { - msg.setTimeStamp((Long) params[3]); - } - if (msg.getTraceID() != null) { - myLogger.log(Logger.INFO, "MessagingService-slice: received message " + MessageManager.stringify(msg) + " for receiver " + receiverID.getLocalName() + ". Trace ID = " + msg.getTraceID()); - } - gCmd.addParam(senderAID); - gCmd.addParam(msg); - gCmd.addParam(receiverID); - result = gCmd; - break; - } - case MessagingSlice.H_GETAGENTLOCATION -> { - AID agentID = (AID) params[0]; - cmd.setReturnValue(getAgentLocation(agentID)); - } - case MessagingSlice.H_ROUTEOUT -> { - Envelope env = (Envelope) params[0]; - byte[] payload = (byte[]) params[1]; - AID receiverID = (AID) params[2]; - String address = (String) params[3]; + return installMTP(address, className); + } - routeOut(env, payload, receiverID, address); - break; - } - case MessagingSlice.H_INSTALLMTP -> { - GenericCommand gCmd = new GenericCommand(MessagingSlice.INSTALL_MTP, MessagingSlice.NAME, null); - String address = (String) params[0]; - String className = (String) params[1]; - gCmd.addParam(address); - gCmd.addParam(className); + private void handleUninstallMTP(VerticalCommand cmd) throws IMTPException, ServiceException, NotFoundException, MTPException { + Object[] params = cmd.getParams(); + String address = (String) params[0]; - result = gCmd; - break; - } - case MessagingSlice.H_UNINSTALLMTP -> { - GenericCommand gCmd = new GenericCommand(MessagingSlice.UNINSTALL_MTP, MessagingSlice.NAME, null); - String address = (String) params[0]; - gCmd.addParam(address); + uninstallMTP(address); + } - result = gCmd; - break; - } - case MessagingSlice.H_NEWMTP -> { - MTPDescriptor mtp = (MTPDescriptor) params[0]; - ContainerID cid = (ContainerID) params[1]; + private void handleNewMTP(VerticalCommand cmd) throws IMTPException, ServiceException { + Object[] params = cmd.getParams(); + MTPDescriptor mtp = (MTPDescriptor) params[0]; + ContainerID cid = (ContainerID) params[1]; - GenericCommand gCmd = new GenericCommand(MessagingSlice.NEW_MTP, MessagingSlice.NAME, null); - gCmd.addParam(mtp); - gCmd.addParam(cid); - - result = gCmd; - break; - } - case MessagingSlice.H_DEADMTP -> { - MTPDescriptor mtp = (MTPDescriptor) params[0]; - ContainerID cid = (ContainerID) params[1]; + newMTP(mtp, cid); + } - GenericCommand gCmd = new GenericCommand(MessagingSlice.DEAD_MTP, MessagingSlice.NAME, null); - gCmd.addParam(mtp); - gCmd.addParam(cid); + private void handleDeadMTP(VerticalCommand cmd) throws IMTPException, ServiceException { + Object[] params = cmd.getParams(); + MTPDescriptor mtp = (MTPDescriptor) params[0]; + ContainerID cid = (ContainerID) params[1]; - result = gCmd; - break; - } - case MessagingSlice.H_ADDROUTE -> { - MTPDescriptor mtp = (MTPDescriptor) params[0]; - String sliceName = (String) params[1]; + deadMTP(mtp, cid); + } - addRoute(mtp, sliceName); - break; - } - case MessagingSlice.H_REMOVEROUTE -> { - MTPDescriptor mtp = (MTPDescriptor) params[0]; - String sliceName = (String) params[1]; + private void handleSetPlatformAddresses(VerticalCommand cmd) { + } - removeRoute(mtp, sliceName); - break; - } - case MessagingSlice.H_NEWALIAS -> { - AID alias = (AID) params[0]; - AID name = (AID) params[1]; + private void handleNewSlice(VerticalCommand cmd) { + MainContainer impl = myContainer.getMain(); + if (impl != null) { + Object[] params = cmd.getParams(); + String newSliceName = (String) params[0]; + try { + // Be sure to get the new (fresh) slice --> Bypass the service cache + MessagingSlice newSlice = (MessagingSlice) getFreshSlice(newSliceName); - newAlias(alias, name); - replicationHandle.invokeReplicatedMethod("newAlias", params); - break; + // Send all possible routes to the new slice + ContainerID[] cids = impl.containerIDs(); + for (ContainerID cid : cids) { + try { + List mtps = impl.containerMTPs(cid); + for (MTPDescriptor o : mtps) { + newSlice.addRoute(o, cid.getName()); + } + } catch (NotFoundException nfe) { + // Should never happen + nfe.printStackTrace(); + } } - case MessagingSlice.H_DEADALIAS -> { - AID alias = (AID) params[0]; - deadAlias(alias); - replicationHandle.invokeReplicatedMethod("deadAlias", params); - break; - } - case MessagingSlice.H_CURRENTALIASES -> globalAliases = (Hashtable) params[0]; - case MessagingSlice.H_TRANSFERLOCALALIASES -> { - AID agent = (AID) params[0]; - List aliases = (List) params[1]; - for (Object alias : aliases) { - localAliases.put(alias, agent); - } + // If the new slice is on a replicated Main Container send it all current aliases + if (newSlice.getNode().hasPlatformManager()) { + newSlice.currentAliases(globalAliases); } + } catch (ServiceException se) { + // Should never happen since getSlice() should always work on the Main container + se.printStackTrace(); + } catch (IMTPException imtpe) { + myLogger.log(Logger.WARNING, "Error notifying current information to new Messaging-Slice " + newSliceName, imtpe); } - } catch (Throwable t) { - cmd.setReturnValue(t); } - return result; } - // Private methods - private void routeOut(Envelope env, byte[] payload, AID receiverID, String address) throws IMTPException, MTPException { - RoutingTable.OutPort out = routes.lookup(address); - //log("Routing message to "+receiverID.getName()+" towards port "+out, 2); - if (myLogger.isLoggable(Logger.FINE)) - myLogger.log(Logger.FINE, "Routing message to " + receiverID.getName() + " towards port " + out); - - if (out != null) - out.route(env, payload, receiverID, address); - else - throw new MTPException("No suitable route found for address " + address + "."); + private void postMessage(AID senderID, ACLMessage msg, AID receiverID) throws NotFoundException { + if (!msg.getSender().equals(senderID)) { + myLogger.log(Logger.FINE, "Attaching real-sender user defined parameter: " + senderID.getName()); + // Sender indicated in the message different than the real sender --> store the latter in the REAL_SENDER user defined param + msg.addUserDefinedParameter(ACLMessage.REAL_SENDER, senderID.getName()); + } + boolean found = myContainer.postMessageToLocalAgent(msg, receiverID); + if (!found) { + throw new NotFoundException("Messaging service slice failed to find " + receiverID); + } } - private void addRoute(MTPDescriptor mtp, String sliceName) throws ServiceException { - // Be sure the slice is fresh --> bypass the service cache - MessagingSlice slice = (MessagingSlice) getFreshSlice(sliceName); - if (routes.addRemoteMTP(mtp, sliceName, slice)) { - // This is actually a new MTP --> Add the new address to all local agents. - // NOTE that a notification about a remote MTP can be received more than once in case of fault and successive recovery of the Main Container - String[] pp = mtp.getSupportedProtocols(); - for (String s : pp) { - if (myLogger.isLoggable(Logger.CONFIG)) - myLogger.log(Logger.CONFIG, "Added Route-Via-Slice(" + sliceName + ") for protocol " + s); - } + private MTPDescriptor installMTP(String address, String className) throws ServiceException, MTPException { - String[] addresses = mtp.getAddresses(); - for (String address : addresses) { - myContainer.addAddressToLocalAgents(address); + try { + // Create the MTP + Class c = Class.forName(className); + MTP proto = null; + try { + proto = (MTP) c.getDeclaredConstructor().newInstance(); + } catch (IllegalArgumentException | InvocationTargetException | NoSuchMethodException + | SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); } - } - } - private void removeRoute(MTPDescriptor mtp, String sliceName) throws ServiceException { - // Don't care about whether or not the slice is fresh. Only the name matters. - MessagingSlice slice = (MessagingSlice) getSlice(sliceName); - routes.removeRemoteMTP(mtp, sliceName, slice); + InChannel.Dispatcher dispatcher = (env, payload) -> { + //log("Message from remote platform received", 2); - String[] pp = mtp.getSupportedProtocols(); - for (String s : pp) { - if (myLogger.isLoggable(Logger.CONFIG)) - myLogger.log(Logger.CONFIG, "Removed Route-Via-Slice(" + sliceName + ") for protocol " + s); + if (myLogger.isLoggable(Logger.FINE)) + myLogger.log(Logger.FINE, "Message from remote platform received"); - } + // To avoid message loops, make sure that the ID of this ACC does + // not appear in a previous 'received' stamp - String[] addresses = mtp.getAddresses(); - for (String address : addresses) { - myContainer.removeAddressFromLocalAgents(address); - } - } + ReceivedObject[] stamps = env.getStamps(); + for (ReceivedObject stamp : stamps) { + String id = stamp.getBy(); + if (CaseInsensitiveString.equalsIgnoreCase(id, accID)) { + System.err.println("ERROR: Message loop detected !!!"); + System.err.println("Route is: "); + for (int j = 0; j < stamps.length; j++) + System.err.println("[" + j + "]" + stamps[j].getBy()); + System.err.println("Message dispatch aborted."); + return; + } + } - } // End of ServiceComponent class + // Put a 'received-object' stamp in the envelope + ReceivedObject ro = new ReceivedObject(); + ro.setBy(accID); + ro.setDate(new Date()); + env.setReceived(ro); + Iterator it = env.getAllIntendedReceiver(); + // FIXME: There is a problem if no 'intended-receiver' is present, + // but this should not happen + while (it.hasNext()) { + AID rcv = it.next(); + GenericMessage msg = new GenericMessage(env, payload); + String traceId = getTraceId(env); + if (traceId != null) { + myLogger.log(Logger.INFO, "MTP In-Channel handling message from the outside for receiver " + rcv.getName() + ". TraceID = " + traceId); + msg.setTraceID(traceId); + } + myMessageManager.deliver(msg, rcv, MessagingService.this); + } + }; - void stamp(GenericMessage gmsg) { - //#J2ME_EXCLUDE_BEGIN - if (samActive) { - synchronized (this) { - msgCounter++; - if (msgCounter == deliveryTimeMeasurementRate) { - gmsg.setTimeStamp(System.currentTimeMillis()); - msgCounter = 0; + if (address == null) { + // Let the MTP choose the address + TransportAddress ta = proto.activate(dispatcher, myProfile); + address = proto.addrToStr(ta); + } else { + // Convert the given string into a TransportAddress object and use it + TransportAddress ta = proto.strToAddr(address); + proto.activate(dispatcher, ta, myProfile); } - } - } - //#J2ME_EXCLUDE_END - } + MTPDescriptor result = new MTPDescriptor(proto.getName(), className, new String[]{address}, proto.getSupportedProtocols()); + routes.addLocalMTP(address, proto, result); + + String[] pp = result.getSupportedProtocols(); + for (String value : pp) { + //log("Added Route-Via-MTP for protocol "+pp[i], 1); + if (myLogger.isLoggable(Logger.CONFIG)) + myLogger.log(Logger.CONFIG, "Added Route-Via-MTP for protocol " + value); - private void updateDeliveryTimeMeasurement(GenericMessage gmsg) { - //#J2ME_EXCLUDE_BEGIN - if (samActive) { - long timeStamp = gmsg.getTimeStamp(); - if (timeStamp > 0 && deliveryTimeMeasureProvider != null) { - long deliveryTime = System.currentTimeMillis() - timeStamp; - if (myLogger.isLoggable(Logger.FINER)) { - myLogger.log(Logger.FINER, "Delivery time = " + deliveryTime); } - deliveryTimeMeasureProvider.addSample(deliveryTime); - } - } - //#J2ME_EXCLUDE_END - } + String[] addresses = result.getAddresses(); + for (String s : addresses) { + myContainer.addAddressToLocalAgents(s); + } - /////////////////////////////////////////////// - // Message delivery - /////////////////////////////////////////////// + GenericCommand gCmd = new GenericCommand(MessagingSlice.NEW_MTP, MessagingSlice.NAME, null); + gCmd.addParam(result); + gCmd.addParam(myContainer.getID()); + submit(gCmd); - // Entry point for the ACL message delivery - public void deliverNow(GenericMessage msg, AID receiverID) { - if (msg.getTraceID() != null) { - myLogger.log(Logger.INFO, msg.getTraceID() + " - Serving message delivery"); - } - try { - if (!msg.hasForeignReceiver()) { - deliverInLocalPlatfrom(msg, receiverID); - } else { - // Dispatch it through the ACC - if (msg.getTraceID() != null) { - myLogger.log(Logger.INFO, msg.getTraceID() + " - Activating ACC delivery"); - } - Iterator addresses = receiverID.getAllAddresses(); - if (addresses.hasNext()) { - while (addresses.hasNext()) { - String address = addresses.next(); - try { - forwardMessage(msg, receiverID, address); - return; - } catch (MTPException mtpe) { - if (myLogger.isLoggable(Logger.WARNING) && !isPersistentDeliveryRetry(msg)) - myLogger.log(Logger.WARNING, "Cannot deliver message to address: " + address + " [" + mtpe + "]. Trying the next one..."); - } - } - notifyFailureToSender(msg, receiverID, new InternalError(ACLMessage.AMS_FAILURE_FOREIGN_AGENT_UNREACHABLE + ": " + "No valid address contained within the AID " + receiverID.getName())); - } else { - notifyFailureToSender(msg, receiverID, new InternalError(ACLMessage.AMS_FAILURE_FOREIGN_AGENT_NO_ADDRESS)); - } - } - } catch (NotFoundException nfe) { - // The receiver does not exist --> Send a FAILURE message - if (msg.getTraceID() != null) { - myLogger.log(Logger.WARNING, msg.getTraceID() + " - Receiver " + receiverID.getLocalName() + " does not exist.", nfe); + return result; } - notifyFailureToSender(msg, receiverID, new InternalError(ACLMessage.AMS_FAILURE_AGENT_NOT_FOUND + ": " + nfe.getMessage())); - } catch (IMTPException imtpe) { - // Can't reach the destination container --> Send a FAILURE message - String id = (msg.getTraceID() != null ? msg.getTraceID() : MessageManager.stringify(msg)); - myLogger.log(Logger.WARNING, id + " - Receiver " + receiverID.getLocalName() + " unreachable.", imtpe); - notifyFailureToSender(msg, receiverID, new InternalError(ACLMessage.AMS_FAILURE_AGENT_UNREACHABLE + ": " + imtpe.getMessage())); - } catch (ServiceException se) { - // Service error during delivery --> Send a FAILURE message - String id = (msg.getTraceID() != null ? msg.getTraceID() : MessageManager.stringify(msg)); - myLogger.log(Logger.WARNING, id + " - Service error delivering message.", se); - notifyFailureToSender(msg, receiverID, new InternalError(ACLMessage.AMS_FAILURE_SERVICE_ERROR + ": " + se.getMessage())); - } catch (JADESecurityException jse) { - // Delivery not authorized--> Send a FAILURE message - if (msg.getTraceID() != null) { - myLogger.log(Logger.WARNING, msg.getTraceID() + " - Not authorized.", jse); + /*#DOTNET_INCLUDE_BEGIN + catch(System.TypeLoadException tle) + { + ClassNotFoundException cnfe = new ClassNotFoundException(tle.get_Message()); + throw new MTPException("The class " + className + " raised IllegalAccessException (see nested exception)", cnfe); + } + catch(System.TypeInitializationException tie) + { + InstantiationException ie = new InstantiationException(tie.get_Message()); + throw new MTPException("The class " + className + " raised InstantiationException (see nested exception)", ie); + } + #DOTNET_INCLUDE_END*/ catch (ClassNotFoundException cnfe) { + throw new MTPException("ERROR: The class " + className + " for the " + address + " MTP was not found"); + } catch (InstantiationException ie) { + throw new MTPException("The class " + className + " raised InstantiationException (see nested exception)", ie); + } catch (IllegalAccessException iae) { + throw new MTPException("The class " + className + " raised IllegalAccessException (see nested exception)", iae); } - notifyFailureToSender(msg, receiverID, new InternalError(ACLMessage.AMS_FAILURE_UNAUTHORIZED + ": " + jse.getMessage())); } - } - private boolean isPersistentDeliveryRetry(GenericMessage msg) { - boolean ret = false; - //#J2ME_EXCLUDE_BEGIN - ACLMessage acl = msg.getACLMessage(); - if (acl != null) { - ret = acl.getAllUserDefinedParameters().containsKey(PersistentDeliveryService.ACL_USERDEF_DUE_DATE); - } - //#J2ME_EXCLUDE_END - return ret; - } - - void deliverInLocalPlatfrom(GenericMessage msg, AID receiverID) throws IMTPException, ServiceException, NotFoundException, JADESecurityException { - if (msg.getTraceID() != null) { - myLogger.log(Logger.INFO, msg.getTraceID() + " - Activating local-platform delivery"); - } - - MainContainer impl = myContainer.getMain(); - if (impl != null) { - // Directly use the GADT on the main container - int attemptsCnt = 0; - while (true) { - ContainerID cid = getAgentLocation(receiverID); - MessagingSlice targetSlice = oneShotDeliver(cid, msg, receiverID); - if (targetSlice != null) { - // Success --> Done - //#J2ME_EXCLUDE_BEGIN - DeliveryTracing.setTracingInfo("Target-node", targetSlice.getNode().getName()); - //#J2ME_EXCLUDE_END - return; - } - checkRetry(receiverID, cid, attemptsCnt); - attemptsCnt++; - } - } else { - // Try first with the cached pairs - MessagingSlice cachedSlice = (MessagingSlice) cachedSlices.get(receiverID); - if (cachedSlice != null) { // Cache hit :-) - try { - if (msg.getTraceID() != null) { - myLogger.log(Logger.INFO, msg.getTraceID() + " - Delivering message to cached slice " + cachedSlice.getNode().getName()); - } - cachedSlice.dispatchLocally(msg.getSender(), msg, receiverID); - if (msg.getTraceID() != null) { - myLogger.log(Logger.INFO, msg.getTraceID() + " - Delivery OK."); - } - //#J2ME_EXCLUDE_BEGIN - DeliveryTracing.setTracingInfo("Target-node", cachedSlice.getNode().getName()); - //#J2ME_EXCLUDE_END - return; - } catch (IMTPException imtpe) { - if (msg.getTraceID() != null) { - myLogger.log(Logger.INFO, msg.getTraceID() + " - Cached slice for receiver " + receiverID.getName() + " unreachable."); - } - } catch (NotFoundException nfe) { - if (msg.getTraceID() != null) { - myLogger.log(Logger.INFO, msg.getTraceID() + " - Receiver " + receiverID.getName() + " not found on cached slice container."); - } - } - // Eliminate stale cache entry - cachedSlices.remove(receiverID); - } - - // Either the receiver was not found in cache or the cache entry was no longer valid - //#J2ME_EXCLUDE_BEGIN - DeliveryTracing.setTracingInfo("Messaging-cache-miss", true); - //#J2ME_EXCLUDE_END - deliverUntilOK(msg, receiverID); - } - } + private void uninstallMTP(String address) throws ServiceException, MTPException { + MTPInfo info = routes.removeLocalMTP(address); + if (info != null) { + MTP proto = info.getMTP(); + TransportAddress ta = proto.strToAddr(address); + proto.deactivate(ta); + MTPDescriptor desc = info.getDescriptor(); + //MTPDescriptor desc = new MTPDescriptor(proto.getName(), proto.getClass().getName(), new String[] {address}, proto.getSupportedProtocols()); - private void deliverUntilOK(GenericMessage msg, AID receiverID) throws IMTPException, NotFoundException, ServiceException, JADESecurityException { - int attemptsCnt = 0; - while (true) { - ContainerID cid; - try { - MessagingSlice mainSlice = (MessagingSlice) getSlice(MAIN_SLICE); - try { - cid = mainSlice.getAgentLocation(receiverID); - } catch (IMTPException imtpe) { - // Try to get a newer slice and repeat... - mainSlice = (MessagingSlice) getFreshSlice(MAIN_SLICE); - cid = mainSlice.getAgentLocation(receiverID); - } - } catch (ServiceException se) { - // This container is no longer able to access the Main --> before propagating the exception - // try to see if the receiver lives locally - if (myContainer.isLocalAgent(receiverID)) { - MessagingSlice localSlice = (MessagingSlice) getIMTPManager().createSliceProxy(getName(), getHorizontalInterface(), getLocalNode()); - localSlice.dispatchLocally(msg.getSender(), msg, receiverID); - //#J2ME_EXCLUDE_BEGIN - DeliveryTracing.setTracingInfo("Target-node", localSlice.getNode().getName()); - //#J2ME_EXCLUDE_END - return; - } else { - throw se; + String[] addresses = desc.getAddresses(); + for (String s : addresses) { + myContainer.removeAddressFromLocalAgents(s); } - } - MessagingSlice targetSlice = oneShotDeliver(cid, msg, receiverID); - if (targetSlice != null) { - // Success --> Done - // On successful message dispatch, put the slice into the slice cache - cachedSlices.put(receiverID, targetSlice); - //#J2ME_EXCLUDE_BEGIN - DeliveryTracing.setTracingInfo("Target-node", targetSlice.getNode().getName()); - //#J2ME_EXCLUDE_END - return; + GenericCommand gCmd = new GenericCommand(MessagingSlice.DEAD_MTP, MessagingSlice.NAME, null); + gCmd.addParam(desc); + gCmd.addParam(myContainer.getID()); + submit(gCmd); + } else { + throw new MTPException("No such address was found on this container: " + address); } - checkRetry(receiverID, cid, attemptsCnt); - attemptsCnt++; } - } - private MessagingSlice oneShotDeliver(ContainerID cid, GenericMessage msg, AID receiverID) throws IMTPException, ServiceException, JADESecurityException { - if (msg.getTraceID() != null) { - myLogger.log(Logger.FINER, msg.getTraceID() + " - Receiver " + receiverID.getLocalName() + " lives on container " + cid.getName()); - } + private void newMTP(MTPDescriptor mtp, ContainerID cid) throws IMTPException, ServiceException { + MainContainer impl = myContainer.getMain(); - MessagingSlice targetSlice = (MessagingSlice) getSlice(cid.getName()); - try { - try { - if (msg.getTraceID() != null) { - myLogger.log(Logger.INFO, msg.getTraceID() + " - Delivering message to slice " + targetSlice.getNode().getName()); - } - targetSlice.dispatchLocally(msg.getSender(), msg, receiverID); - } catch (IMTPException imtpe) { - // Try to get a newer slice and repeat... - if (msg.getTraceID() != null) { - myLogger.log(Logger.FINER, msg.getTraceID() + " - Messaging slice on container " + cid.getName() + " unreachable. Try to get a fresh one."); - } + if (impl != null) { - targetSlice = (MessagingSlice) getFreshSlice(cid.getName()); - if (msg.getTraceID() != null && (targetSlice != null)) { - myLogger.log(Logger.FINER, msg.getTraceID() + " - Fresh slice for container " + cid.getName() + " found."); + // Update the routing tables of all the other slices + Slice[] slices = getAllSlices(); + for (Slice value : slices) { + try { + MessagingSlice slice = (MessagingSlice) value; + String sliceName = slice.getNode().getName(); + if (!sliceName.equals(cid.getName())) { + slice.addRoute(mtp, cid.getName()); + } + } catch (Throwable t) { + // Re-throw allowed exceptions + if (t instanceof IMTPException) { + throw (IMTPException) t; + } + if (t instanceof ServiceException) { + throw (ServiceException) t; + } + //System.err.println("### addRoute() threw " + t.getClass().getName() + " ###"); + myLogger.log(Logger.WARNING, "### addRoute() threw " + t + " ###"); + } } - - targetSlice.dispatchLocally(msg.getSender(), msg, receiverID); - } - if (msg.getTraceID() != null) { - myLogger.log(Logger.INFO, msg.getTraceID() + " - Delivery OK"); - } - return targetSlice; - } catch (NotFoundException nfe) { - // The agent was found in the GADT, but not on the container where it is supposed to - // be. Possibly it moved elsewhere in the meanwhile. ==> Try again. - if (msg.getTraceID() != null) { - myLogger.log(Logger.FINER, msg.getTraceID() + " - Receiver " + receiverID.getLocalName() + " not found on container " + cid.getName() + ". Possibly he moved elsewhere --> Retry"); - } - } catch (NullPointerException npe) { - // This is thrown if targetSlice is null: The agent was found in the GADT, - // but his container does not exist anymore. Possibly the agent moved elsewhere in - // the meanwhile ==> Try again. - if (msg.getTraceID() != null) { - myLogger.log(Logger.FINER, msg.getTraceID() + " - Container " + cid.getName() + " for receiver " + receiverID.getLocalName() + " does not exist anymore. Possibly the receiver moved elsewhere --> Retry"); - } - } - - return null; - } - - private void checkRetry(AID receiver, ContainerID cid, int attemptsCnt) throws NotFoundException { - if (maxDeliveryRetryAttempts >= 0 && attemptsCnt >= maxDeliveryRetryAttempts) { - throw new NotFoundException("Agent " + receiver.getLocalName() + " not found in container " + cid.getName() + " where it was supposed to be"); - } - // Wait a bit before enabling next delivery attempt - try { - Thread.sleep(200); - } catch (InterruptedException ie) { - } - } - - - private void forwardMessage(GenericMessage msg, AID receiver, String address) throws MTPException { - // FIXME what if there is no envelope? - AID aid = msg.getEnvelope().getFrom(); - - if (aid == null) { - //System.err.println("ERROR: null message sender. Aborting message dispatch..."); - if (myLogger.isLoggable(Logger.SEVERE)) - myLogger.log(Logger.SEVERE, "ERROR: null message sender. Aborting message dispatch..."); - return; - } - - // FIXME The message can no longer be updated - // if has no address set, then adds the addresses of this platform - if (!aid.getAllAddresses().hasNext()) - addPlatformAddresses(aid); - - try { - if (msg.getTraceID() != null) { - myLogger.log(Logger.INFO, msg.getTraceID() + " - Routing message out to address " + address); - msg.getEnvelope().addProperties(new Property(ACLMessage.TRACE, msg.getTraceID())); - } - localSlice.routeOut(msg.getEnvelope(), msg.getPayload(), receiver, address); - } catch (IMTPException imtpe) { - throw new MTPException("Error during message routing", imtpe); - } - - } - - - /** - * This method is used internally by the platform in order - * to notify the sender of a message that a failure was reported by - * the Message Transport Service. - */ - public void notifyFailureToSender(GenericMessage msg, AID receiver, InternalError ie) { - //#J2ME_EXCLUDE_BEGIN - // If msg represents a MultipleGenericMessage, recursive call notifyFailureToSender() for each msg - if (msg instanceof MultipleGenericMessage) { - for (GenericMessage g : ((MultipleGenericMessage) msg).getMessages()) { - notifyFailureToSender(g, receiver, ie); - } - return; - } - //#J2ME_EXCLUDE_END - - ACLMessage acl = msg.getACLMessage(); - if (acl == null) { - // ACLMessage can be null in case we get a failure delivering a message coming from an external platform (received by a local MTP). - // In this case in fact the message is encoded. Try to decode it so that a suitable FAILURE response can be sent back. - // If the payload is mangled in some way (e.g. encrypted) decoding will fail and no suitable FAILURE response will be sent - try { - acl = encInFilter.decodeMessage(msg.getEnvelope(), msg.getPayload()); - acl.setEnvelope(msg.getEnvelope()); - msg.setACLMessage(acl); - } catch (Exception e) { - // Just do nothing - e.printStackTrace(); + impl.newMTP(mtp, cid); + } else { + // Do nothing for now, but could also route the command to the main slice, thus enabling e.g. AMS replication } } - if (acl == null) { - myLogger.log(Logger.WARNING, "Cannot notify failure to sender: GenericMessage contains no ACLMessage"); - return; - } - if ("true".equals(acl.getUserDefinedParameter(ACLMessage.IGNORE_FAILURE))) { - // Ignore the failure - return; - } - - GenericCommand cmd = new GenericCommand(MessagingSlice.NOTIFY_FAILURE, MessagingSlice.NAME, null); - cmd.addParam(msg); - cmd.addParam(receiver); - cmd.addParam(ie); - - try { - submit(cmd); - } catch (ServiceException se) { - // It should never happen - se.printStackTrace(); - } - } + private void deadMTP(MTPDescriptor mtp, ContainerID cid) throws IMTPException, ServiceException { + MainContainer impl = myContainer.getMain(); - /* - * This method is called before preparing the Envelope of an outgoing message. - * It checks for all the AIDs present in the message and adds the addresses, if not present - **/ - private void addPlatformAddresses(AID id) { - Iterator it = routes.getAddresses(); - while (it.hasNext()) { - String addr = it.next(); - id.addAddresses(addr); - } - } + if (impl != null) { - // Package scoped since it is accessed by the OutgoingEncoding filter - final boolean livesHere(AID id) { - if (!acceptForeignAgents) { - // All agents in the platform must have a name with the form - // @ - String hap = id.getHap(); - return CaseInsensitiveString.equalsIgnoreCase(hap, platformID); - } else { - String[] addresses = id.getAddressesArray(); - if (addresses.length == 0) { - return true; - } else { - boolean allLocalAddresses = true; - for (String address : addresses) { - if (!isPlatformAddress(address)) { - allLocalAddresses = false; - break; - } - } - if (allLocalAddresses) { - return true; - } else { - // Check in the GADT + // Update the routing tables of all the other slices + Slice[] slices = getAllSlices(); + for (Slice value : slices) { try { - MainContainer impl = myContainer.getMain(); - if (impl != null) { - // Directly use the GADT on the main container - getAgentLocation(id); - } else { - // Use the main slice - MessagingSlice mainSlice = (MessagingSlice) getSlice(MAIN_SLICE); - try { - mainSlice.getAgentLocation(id); - } catch (IMTPException imtpe) { - // Try to get a newer slice and repeat... - mainSlice = (MessagingSlice) getFreshSlice(MAIN_SLICE); - mainSlice.getAgentLocation(id); - } + MessagingSlice slice = (MessagingSlice) value; + String sliceName = slice.getNode().getName(); + if (!sliceName.equals(cid.getName())) { + slice.removeRoute(mtp, cid.getName()); + } + } catch (Throwable t) { + // Re-throw allowed exceptions + if (t instanceof IMTPException) { + throw (IMTPException) t; + } + if (t instanceof ServiceException) { + throw (ServiceException) t; } - return true; - } catch (NotFoundException nfe) { - // The agent does not live in the platform - return false; - } catch (Exception e) { - // Intra-platform delivery would fail, so try inter-platform - return false; + + myLogger.log(Logger.WARNING, "### removeRoute() threw " + t + " ###"); } } + impl.deadMTP(mtp, cid); + } else { + // Do nothing for now, but could also route the command to the main slice, thus enabling e.g. AMS replication } } - } + } // END of inner class CommandTargetSink - private boolean isPlatformAddress(String addr) { - Iterator it = routes.getAddresses(); - while (it.hasNext()) { - String ad = it.next(); - if (CaseInsensitiveString.equalsIgnoreCase(ad, addr)) { - return true; + /** + * Inner class for this service: this class receives commands from + * service Sink and serves them, coordinating with + * remote parts of this service through the Slice + * interface (that extends the Service.Slice + * interface). + */ + private class ServiceComponent implements Slice { + // Implementation of the Service.Slice interface + public Service getService() { + return MessagingService.this; + } + + public Node getNode() throws ServiceException { + try { + return MessagingService.this.getLocalNode(); + } catch (IMTPException imtpe) { + throw new ServiceException("Problem in contacting the IMTP Manager", imtpe); } } - return false; - } - // Work-around for PJAVA compilation - protected Slice getFreshSlice(String name) throws ServiceException { - return super.getFreshSlice(name); - } + public VerticalCommand serve(HorizontalCommand cmd) { + VerticalCommand result = null; + try { + String cmdName = cmd.getName(); + Object[] params = cmd.getParams(); + switch (cmdName) { + case MessagingSlice.H_DISPATCHLOCALLY -> { + GenericCommand gCmd = new GenericCommand(MessagingSlice.SEND_MESSAGE, MessagingSlice.NAME, null); + AID senderAID = (AID) params[0]; + GenericMessage msg = (GenericMessage) params[1]; + AID receiverID = (AID) params[2]; + if (params.length == 4) { + msg.setTimeStamp((Long) params[3]); + } + if (msg.getTraceID() != null) { + myLogger.log(Logger.INFO, "MessagingService-slice: received message " + MessageManager.stringify(msg) + " for receiver " + receiverID.getLocalName() + ". Trace ID = " + msg.getTraceID()); + } + gCmd.addParam(senderAID); + gCmd.addParam(msg); + gCmd.addParam(receiverID); + result = gCmd; + } + case MessagingSlice.H_GETAGENTLOCATION -> { + AID agentID = (AID) params[0]; + cmd.setReturnValue(getAgentLocation(agentID)); + } + case MessagingSlice.H_ROUTEOUT -> { + Envelope env = (Envelope) params[0]; + byte[] payload = (byte[]) params[1]; + AID receiverID = (AID) params[2]; + String address = (String) params[3]; - private boolean needSynchDelivery(GenericMessage gMsg) { - ACLMessage acl = gMsg.getACLMessage(); - if (acl != null) { - return "true".equals(acl.clearUserDefinedParameter(ACLMessage.SYNCH_DELIVERY)); - } - return false; - } + routeOut(env, payload, receiverID, address); + } + case MessagingSlice.H_INSTALLMTP -> { + GenericCommand gCmd = new GenericCommand(MessagingSlice.INSTALL_MTP, MessagingSlice.NAME, null); + String address = (String) params[0]; + String className = (String) params[1]; + gCmd.addParam(address); + gCmd.addParam(className); - // Only for debugging: - private volatile int traceCnt = 0; + result = gCmd; + } + case MessagingSlice.H_UNINSTALLMTP -> { + GenericCommand gCmd = new GenericCommand(MessagingSlice.UNINSTALL_MTP, MessagingSlice.NAME, null); + String address = (String) params[0]; + gCmd.addParam(address); - private void checkTracing(GenericMessage msg) { - ACLMessage acl = msg.getACLMessage(); - if (acl != null) { - if (myLogger.isLoggable(Logger.FINE) || "true".equals(acl.getUserDefinedParameter(ACLMessage.TRACE))) { - msg.setTraceID(ACLMessage.getPerformative(acl.getPerformative()) + "-" + msg.getSender().getLocalName() + "-" + traceCnt); - traceCnt++; - } - } - } + result = gCmd; + } + case MessagingSlice.H_NEWMTP -> { + MTPDescriptor mtp = (MTPDescriptor) params[0]; + ContainerID cid = (ContainerID) params[1]; - private String getTraceId(Envelope env) { - Iterator it = env.getAllProperties(); - while (it.hasNext()) { - Property p = it.next(); - if (p.getName().equals(ACLMessage.TRACE)) { - return (String) p.getValue(); - } - } - return null; - } + GenericCommand gCmd = new GenericCommand(MessagingSlice.NEW_MTP, MessagingSlice.NAME, null); + gCmd.addParam(mtp); + gCmd.addParam(cid); - // For debugging purpose - public String[] getMessageManagerQueueStatus() { - return myMessageManager.getQueueStatus(); - } + result = gCmd; + } + case MessagingSlice.H_DEADMTP -> { + MTPDescriptor mtp = (MTPDescriptor) params[0]; + ContainerID cid = (ContainerID) params[1]; - // For debugging purpose - public String[] getMessageManagerThreadPoolStatus() { - return myMessageManager.getThreadPoolStatus(); - } + GenericCommand gCmd = new GenericCommand(MessagingSlice.DEAD_MTP, MessagingSlice.NAME, null); + gCmd.addParam(mtp); + gCmd.addParam(cid); - // For debugging purpose - public String getMessageManagerGlobalInfo() { - return myMessageManager.getGlobalInfo(); - } + result = gCmd; + } + case MessagingSlice.H_ADDROUTE -> { + MTPDescriptor mtp = (MTPDescriptor) params[0]; + String sliceName = (String) params[1]; - // For debugging purpose - public Thread[] getMessageManagerThreadPool() { - return myMessageManager.getThreadPool(); - } + addRoute(mtp, sliceName); + } + case MessagingSlice.H_REMOVEROUTE -> { + MTPDescriptor mtp = (MTPDescriptor) params[0]; + String sliceName = (String) params[1]; - protected void clearCachedSlice(String name) { - if (cachedSlices != null) { - cachedSlices.clear(); - myLogger.log(Logger.CONFIG, "Clearing cache"); + removeRoute(mtp, sliceName); + } + case MessagingSlice.H_NEWALIAS -> { + AID alias = (AID) params[0]; + AID name = (AID) params[1]; + + newAlias(alias, name); + replicationHandle.invokeReplicatedMethod("newAlias", params); + } + case MessagingSlice.H_DEADALIAS -> { + AID alias = (AID) params[0]; + + deadAlias(alias); + replicationHandle.invokeReplicatedMethod("deadAlias", params); + } + case MessagingSlice.H_CURRENTALIASES -> globalAliases = (Hashtable) params[0]; + case MessagingSlice.H_TRANSFERLOCALALIASES -> { + AID agent = (AID) params[0]; + List aliases = (List) params[1]; + for (Object alias : aliases) { + localAliases.put(alias, agent); + } + } + } + } catch (Throwable t) { + cmd.setReturnValue(t); + } + return result; } - super.clearCachedSlice(name); - } - public String dump(String key) { - StringBuffer sb = new StringBuffer("LOCAL ALIASES:\n"); - if (localAliases.size() > 0) { - sb.append(stringifyAliasesMap(localAliases)); - } else { - sb.append("---\n"); + // Private methods + private void routeOut(Envelope env, byte[] payload, AID receiverID, String address) throws IMTPException, MTPException { + RoutingTable.OutPort out = routes.lookup(address); + //log("Routing message to "+receiverID.getName()+" towards port "+out, 2); + if (myLogger.isLoggable(Logger.FINE)) + myLogger.log(Logger.FINE, "Routing message to " + receiverID.getName() + " towards port " + out); + + if (out != null) + out.route(env, payload, receiverID, address); + else + throw new MTPException("No suitable route found for address " + address + "."); } - if (globalAliases != null) { - sb.append("GLOBAL ALIASES:\n"); - if (globalAliases.size() > 0) { - sb.append(stringifyAliasesMap(globalAliases)); - } else { - sb.append("---\n"); + private void addRoute(MTPDescriptor mtp, String sliceName) throws ServiceException { + // Be sure the slice is fresh --> bypass the service cache + MessagingSlice slice = (MessagingSlice) getFreshSlice(sliceName); + if (routes.addRemoteMTP(mtp, sliceName, slice)) { + // This is actually a new MTP --> Add the new address to all local agents. + // NOTE that a notification about a remote MTP can be received more than once in case of fault and successive recovery of the Main Container + String[] pp = mtp.getSupportedProtocols(); + for (String s : pp) { + if (myLogger.isLoggable(Logger.CONFIG)) + myLogger.log(Logger.CONFIG, "Added Route-Via-Slice(" + sliceName + ") for protocol " + s); + } + + String[] addresses = mtp.getAddresses(); + for (String address : addresses) { + myContainer.addAddressToLocalAgents(address); + } } } - return sb.toString(); - } - private String stringifyAliasesMap(Hashtable aliases) { - StringBuffer sb = new StringBuffer(); - for (Object o : aliases.keySet()) { - AID alias = (AID) o; - AID agent = aliases.get(alias); - sb.append("- ").append(alias.getLocalName()).append(" --> ").append(agent.getLocalName()).append("\n"); + private void removeRoute(MTPDescriptor mtp, String sliceName) throws ServiceException { + // Don't care about whether or not the slice is fresh. Only the name matters. + MessagingSlice slice = (MessagingSlice) getSlice(sliceName); + routes.removeRemoteMTP(mtp, sliceName, slice); + + String[] pp = mtp.getSupportedProtocols(); + for (String s : pp) { + if (myLogger.isLoggable(Logger.CONFIG)) + myLogger.log(Logger.CONFIG, "Removed Route-Via-Slice(" + sliceName + ") for protocol " + s); + + } + + String[] addresses = mtp.getAddresses(); + for (String address : addresses) { + myContainer.removeAddressFromLocalAgents(address); + } } - return sb.toString(); - } + + } // End of ServiceComponent class } diff --git a/src/jade/core/messaging/MultipleGenericMessage.java b/src/jade/core/messaging/MultipleGenericMessage.java index 9c5b0c0..7effee7 100644 --- a/src/jade/core/messaging/MultipleGenericMessage.java +++ b/src/jade/core/messaging/MultipleGenericMessage.java @@ -7,8 +7,8 @@ public class MultipleGenericMessage extends GenericMessage { - private List messages = new ArrayList<>(); private final int length; // Raw estimation of bytes taken by this MGM + private List messages = new ArrayList<>(); public MultipleGenericMessage(int length) { this.length = length; diff --git a/src/jade/core/messaging/OutBox.java b/src/jade/core/messaging/OutBox.java index 60bfb88..457ed5e 100644 --- a/src/jade/core/messaging/OutBox.java +++ b/src/jade/core/messaging/OutBox.java @@ -21,29 +21,24 @@ class OutBox { private static final int PENDING_MSG_PER_RECEIVER_THR = -1; - - private int size = 0; // Approximated size in bytes - private int pendingCnt = 0; private final int warningSize; private final int maxSize; private final int sleepTimeFactor; private final boolean enableMultipleDelivery; - private boolean overWarningSize = false; - private final MessageManager manager; - - private long lastDiscardedLogTime = -1; - private long discardedSinceLastLogCnt = 0; - private long servedCnt = 0; - // The messages to be delivered organized as an hashtable that maps // a receiver AID into the Box of messages to be delivered to that receiver private final Map messagesByReceiver = new HashMap<>(); // The messages to be delivered organized as a round list of the Boxes of // messages for the currently addressed receivers private final RoundList messagesByOrder = new RoundList(); - private final Logger myLogger; + private int size = 0; // Approximated size in bytes + private int pendingCnt = 0; + private boolean overWarningSize = false; + private long lastDiscardedLogTime = -1; + private long discardedSinceLastLogCnt = 0; + private long servedCnt = 0; OutBox(int warningSize, int maxSize, int sleepTimeFactor, boolean enableMultipleDelivery, MessageManager manager) { this.warningSize = warningSize; @@ -290,15 +285,34 @@ private void decreaseSize(int k) { } } + // For debugging purpose + synchronized String[] getStatus() { + Object[] boxes = messagesByOrder.toArray(); + String[] status = new String[boxes.length]; + for (int i = 0; i < boxes.length; ++i) { + status[i] = boxes[i].toString(); + } + return status; + } + + // For debugging purpose + int getSize() { + return size; + } + + int getPendingCnt() { + return pendingCnt; + } + /** * This class represents a Box of messages to be delivered to * a single receiver */ private class Box { private final AID receiver; + private final List messages; private boolean busy; private String owner; - private final List messages; public Box(AID r) { receiver = r; @@ -310,6 +324,10 @@ private AID getReceiver() { return receiver; } + private boolean isBusy() { + return busy; + } + private void setBusy(boolean b) { busy = b; //#J2ME_EXCLUDE_BEGIN @@ -317,10 +335,6 @@ private void setBusy(boolean b) { //#J2ME_EXCLUDE_END } - private boolean isBusy() { - return busy; - } - private String getOwner() { return owner; } @@ -346,24 +360,4 @@ public String toString() { return "(" + receiver.getName() + " :busy " + busy + (owner != null ? " :owner " + owner : "") + " :message-cnt " + messages.size() + ")"; } } // END of inner class Box - - - // For debugging purpose - synchronized String[] getStatus() { - Object[] boxes = messagesByOrder.toArray(); - String[] status = new String[boxes.length]; - for (int i = 0; i < boxes.length; ++i) { - status[i] = boxes[i].toString(); - } - return status; - } - - // For debugging purpose - int getSize() { - return size; - } - - int getPendingCnt() { - return pendingCnt; - } } diff --git a/src/jade/core/messaging/PersistentDeliveryManager.java b/src/jade/core/messaging/PersistentDeliveryManager.java index abdef1d..b1afdb4 100644 --- a/src/jade/core/messaging/PersistentDeliveryManager.java +++ b/src/jade/core/messaging/PersistentDeliveryManager.java @@ -46,122 +46,43 @@ */ class PersistentDeliveryManager { - public static synchronized PersistentDeliveryManager instance(Profile p, MessageManager.Channel ch) { - if (theInstance == null) { - theInstance = new PersistentDeliveryManager(); - theInstance.initialize(p, ch); - } - - return theInstance; - } - // How often to check for expired deliveries private static final long DEFAULT_SENDFAILUREPERIOD = 60 * 1000; // One minute - private static final String FILE_STORAGE_SHORTCUT = "file"; - // Default storage class private static final String DEFAULT_STORAGE = "jade.core.messaging.PersistentDeliveryManager$DummyStorage"; private static final String FILE_STORAGE = "jade.core.messaging.FileMessageStorage"; + // A shared instance to have a single thread pool + private static PersistentDeliveryManager theInstance; // FIXME: Maybe a table, indexed by a profile subset, would be better? + // The table of undelivered messages to send + private final Map pendingMessages = new HashMap<>(); + // The component managing asynchronous message delivery and retries + private MessageManager myMessageManager; + // The actual channel over which messages will be sent + private MessageManager.Channel deliveryChannel; + // How often pending messages due date will be checked (the + // message will be sent out if expired) + private long sendFailurePeriod; + // How many containers are sharing this active component + private long users; + // The active object that periodically checks the due date of ACL + // messages and sends them after it expired + private ExpirationChecker failureSender; + // The component performing the actual storage and retrieval from + // a persistent support + private MessageStorage storage; - private static class DeliveryItem { - - public DeliveryItem(GenericMessage msg, AID id, MessageManager.Channel ch, String sid) { - toDeliver = msg; - receiver = id; - channel = ch; - storeName = sid; - } - - public GenericMessage getMessage() { - return toDeliver; - } - - public AID getReceiver() { - return receiver; - } - - public MessageManager.Channel getChannel() { - return channel; - } - - public String getStoreName() { - return storeName; - } - - private final GenericMessage toDeliver; - private final AID receiver; - private final MessageManager.Channel channel; - private final String storeName; - - - } // End of DeliveryItem class - - - private class ExpirationChecker implements Runnable { - - public ExpirationChecker(long t) { - period = t; - myThread = new Thread(this, "Persistent Delivery Service -- Expiration Checker Thread"); - } - - public void run() { - while (active) { - try { - Thread.sleep(period); - synchronized (pendingMessages) { - // Try to send all stored messages... - // If the receiver still not exists and the due date has elapsed - // the sender will get back a FAILURE - Object[] keys = pendingMessages.keySet().toArray(); - for (Object key : keys) { - flushMessages((AID) key); - } - } - } catch (InterruptedException ie) { - // Just do nothing - } - } - } - - public void start() { - active = true; - myThread.start(); - } - - public void stop() { - active = false; - myThread.interrupt(); - } - - private boolean active = false; - private final long period; - private final Thread myThread; - - } // End of ExpirationChecker class - - - public static class DummyStorage implements MessageStorage { - - public void init(Profile p) { - // Do nothing - } - - public String store(GenericMessage msg, AID receiver) throws IOException { - // Do nothing - return null; - } - - public void delete(String storeName, AID receiver) throws IOException { - // Do nothing - } + private PersistentDeliveryManager() { + } - public void loadAll(LoadListener il) { - // Do nothing + public static synchronized PersistentDeliveryManager instance(Profile p, MessageManager.Channel ch) { + if (theInstance == null) { + theInstance = new PersistentDeliveryManager(); + theInstance.initialize(p, ch); } - } // End of DummyStorage class - + return theInstance; + } public void initialize(Profile p, MessageManager.Channel ch) { @@ -273,14 +194,6 @@ public synchronized void stop() { } } - - // A shared instance to have a single thread pool - private static PersistentDeliveryManager theInstance; // FIXME: Maybe a table, indexed by a profile subset, would be better? - - - private PersistentDeliveryManager() { - } - private void retry(DeliveryItem item) { // Remove the message from the storage try { @@ -292,28 +205,99 @@ private void retry(DeliveryItem item) { myMessageManager.deliver(item.getMessage(), item.getReceiver(), item.getChannel()); } + private static class DeliveryItem { - // The component managing asynchronous message delivery and retries - private MessageManager myMessageManager; + private final GenericMessage toDeliver; + private final AID receiver; + private final MessageManager.Channel channel; + private final String storeName; - // The actual channel over which messages will be sent - private MessageManager.Channel deliveryChannel; + public DeliveryItem(GenericMessage msg, AID id, MessageManager.Channel ch, String sid) { + toDeliver = msg; + receiver = id; + channel = ch; + storeName = sid; + } - // How often pending messages due date will be checked (the - // message will be sent out if expired) - private long sendFailurePeriod; + public GenericMessage getMessage() { + return toDeliver; + } - // How many containers are sharing this active component - private long users; + public AID getReceiver() { + return receiver; + } - // The table of undelivered messages to send - private final Map pendingMessages = new HashMap<>(); + public MessageManager.Channel getChannel() { + return channel; + } - // The active object that periodically checks the due date of ACL - // messages and sends them after it expired - private ExpirationChecker failureSender; + public String getStoreName() { + return storeName; + } - // The component performing the actual storage and retrieval from - // a persistent support - private MessageStorage storage; + + } // End of DeliveryItem class + + public static class DummyStorage implements MessageStorage { + + public void init(Profile p) { + // Do nothing + } + + public String store(GenericMessage msg, AID receiver) throws IOException { + // Do nothing + return null; + } + + public void delete(String storeName, AID receiver) throws IOException { + // Do nothing + } + + public void loadAll(LoadListener il) { + // Do nothing + } + + } // End of DummyStorage class + + private class ExpirationChecker implements Runnable { + + private final long period; + private final Thread myThread; + private boolean active = false; + + public ExpirationChecker(long t) { + period = t; + myThread = new Thread(this, "Persistent Delivery Service -- Expiration Checker Thread"); + } + + public void run() { + while (active) { + try { + Thread.sleep(period); + synchronized (pendingMessages) { + // Try to send all stored messages... + // If the receiver still not exists and the due date has elapsed + // the sender will get back a FAILURE + Object[] keys = pendingMessages.keySet().toArray(); + for (Object key : keys) { + flushMessages((AID) key); + } + } + } catch (InterruptedException ie) { + // Just do nothing + } + } + } + + public void start() { + active = true; + myThread.start(); + } + + public void stop() { + active = false; + myThread.interrupt(); + } + + } // End of ExpirationChecker class } diff --git a/src/jade/core/messaging/PersistentDeliveryProxy.java b/src/jade/core/messaging/PersistentDeliveryProxy.java index 7fab37d..4b52ac0 100644 --- a/src/jade/core/messaging/PersistentDeliveryProxy.java +++ b/src/jade/core/messaging/PersistentDeliveryProxy.java @@ -73,7 +73,7 @@ public void flushMessages(AID receiver) throws IMTPException { Node n = getNode(); Object result = n.accept(cmd); - if ((result != null) && (result instanceof Throwable)) { + if ((result instanceof Throwable)) { if (result instanceof IMTPException) { throw (IMTPException) result; } else { diff --git a/src/jade/core/messaging/PersistentDeliveryService.java b/src/jade/core/messaging/PersistentDeliveryService.java index b15e151..a55ac3c 100644 --- a/src/jade/core/messaging/PersistentDeliveryService.java +++ b/src/jade/core/messaging/PersistentDeliveryService.java @@ -94,7 +94,21 @@ public class PersistentDeliveryService extends BaseService { static final String ACL_USERDEF_DUE_DATE = "JADE-persistentdelivery-duedate"; - + // The local slice for this service + private final ServiceComponent localSlice = new ServiceComponent(); + // The command filter, outgoing direction + private final CommandOutgoingFilter outFilter = new CommandOutgoingFilter(); + // The command filter, incoming direction + private final CommandIncomingFilter inFilter = new CommandIncomingFilter(); + // The concrete agent container, providing access to LADT, etc. + private AgentContainer myContainer; + // The service finder component + private ServiceFinder myServiceFinder; + // The component managing ACL message storage and delayed delivery + private PersistentDeliveryManager myManager; + // The filter to be matched by undelivered ACL messages + private PersistentDeliveryFilter messageFilter; + private String[] storageEnabledSliceNames; public void init(AgentContainer ac, Profile p) throws ProfileException { super.init(ac, p); @@ -126,6 +140,89 @@ public Filter getCommandFilter(boolean direction) { } } + /** + * Activate the PersistentDeliveryManager and instantiate the + * PersistentDeliveryFilter. + * Note that getting the MessagingService (required to instantiate + * the PersistentDeliveryManager) cannot be done in the init() method + * since at that time the MessagingService may not be installed yet. + */ + public void boot(Profile myProfile) throws ServiceException { + // getting the delivery channel + try { + String str = myProfile.getParameter(PERSISTENT_DELIVERY_STORAGENODES, null); + if (str != null) { + storageEnabledSliceNames = str.split(";"); + myLogger.log(Logger.CONFIG, "Persistent-Delivery - Storage enabled nodes: " + str); + } + + MessageManager.Channel ch = (MessageManager.Channel) myServiceFinder.findService(MessagingSlice.NAME); + if (ch == null) + throw new ServiceException("Can't locate delivery channel"); + myManager = PersistentDeliveryManager.instance(myProfile, ch); + myManager.start(); + } catch (IMTPException imtpe) { + imtpe.printStackTrace(); + throw new ServiceException("Cannot retrieve the delivery channel", imtpe); + } + + try { + // Load the supplied class to filter messages if any + String className = myProfile.getParameter(PERSISTENT_DELIVERY_FILTER, null); + if (className != null) { + Class c = Class.forName(className); + messageFilter = (PersistentDeliveryFilter) c.getDeclaredConstructor().newInstance(); + myLogger.log(Logger.INFO, "Persistent-Delivery - Using message filter of type " + messageFilter.getClass().getName()); + } + } catch (Exception e) { + throw new ServiceException("Exception in message filter initialization", e); + } + } + + /** + * Requests all slices to flush the stored messages for a newly born target agent. + * Do it in a separated thread since this may take time. + * This happens on the main container only. + */ + private void flushMessages(final AID target) { + Thread t = new Thread(() -> { + try { + Slice[] slices = getStorageEnabledSlices(); + String sliceName = null; + for (Slice value : slices) { + PersistentDeliverySlice slice = (PersistentDeliverySlice) value; + try { + sliceName = slice.getNode().getName(); + slice.flushMessages(target); + } catch (Exception e) { + myLogger.log(Logger.WARNING, "Persistent-Delivery - Error trying to flush messages for agent " + target.getName() + " on node " + sliceName); +// Ignore it and try other slices... + } + } + } catch (ServiceException se) { + myLogger.log(Logger.WARNING, "Persistent-Delivery - Error retrieving storage-enabled slices to flush persisted messages for agent " + target.getName()); + } + }); + t.start(); + } + + private Slice[] getStorageEnabledSlices() throws ServiceException { + if (storageEnabledSliceNames != null) { + List ss = new ArrayList<>(storageEnabledSliceNames.length); + for (String storageEnabledSliceName : storageEnabledSliceNames) { + try { + Slice s = getSlice(storageEnabledSliceName); + ss.add(s); + } catch (ServiceException se) { + // Slice not present + } + } + return ss.toArray(new Slice[0]); + } else { + // No storage enabled slices explicitly specified --> Use all + return getAllSlices(); + } + } /** * Outgoing command FILTER. @@ -194,7 +291,6 @@ private boolean handleNotifyFailure(VerticalCommand cmd) throws IMTPException, S } // End of CommandOutgoingFilter class - /** * Incoming command FILTER. * Processes the INFORM_CREATED command. Note that we do this @@ -225,7 +321,6 @@ private void handleInformCreated(VerticalCommand cmd) throws IMTPException, Serv } // End of CommandIncomingFilter class - /** * The SLICE. */ @@ -335,112 +430,4 @@ private void flushMessages(AID receiver) { } } // End of ServiceComponent class - - - /** - * Activate the PersistentDeliveryManager and instantiate the - * PersistentDeliveryFilter. - * Note that getting the MessagingService (required to instantiate - * the PersistentDeliveryManager) cannot be done in the init() method - * since at that time the MessagingService may not be installed yet. - */ - public void boot(Profile myProfile) throws ServiceException { - // getting the delivery channel - try { - String str = myProfile.getParameter(PERSISTENT_DELIVERY_STORAGENODES, null); - if (str != null) { - storageEnabledSliceNames = str.split(";"); - myLogger.log(Logger.CONFIG, "Persistent-Delivery - Storage enabled nodes: " + str); - } - - MessageManager.Channel ch = (MessageManager.Channel) myServiceFinder.findService(MessagingSlice.NAME); - if (ch == null) - throw new ServiceException("Can't locate delivery channel"); - myManager = PersistentDeliveryManager.instance(myProfile, ch); - myManager.start(); - } catch (IMTPException imtpe) { - imtpe.printStackTrace(); - throw new ServiceException("Cannot retrieve the delivery channel", imtpe); - } - - try { - // Load the supplied class to filter messages if any - String className = myProfile.getParameter(PERSISTENT_DELIVERY_FILTER, null); - if (className != null) { - Class c = Class.forName(className); - messageFilter = (PersistentDeliveryFilter) c.getDeclaredConstructor().newInstance(); - myLogger.log(Logger.INFO, "Persistent-Delivery - Using message filter of type " + messageFilter.getClass().getName()); - } - } catch (Exception e) { - throw new ServiceException("Exception in message filter initialization", e); - } - } - - /** - * Requests all slices to flush the stored messages for a newly born target agent. - * Do it in a separated thread since this may take time. - * This happens on the main container only. - */ - private void flushMessages(final AID target) { - Thread t = new Thread(() -> { - try { - Slice[] slices = getStorageEnabledSlices(); - String sliceName = null; - for (Slice value : slices) { - PersistentDeliverySlice slice = (PersistentDeliverySlice) value; - try { - sliceName = slice.getNode().getName(); - slice.flushMessages(target); - } catch (Exception e) { - myLogger.log(Logger.WARNING, "Persistent-Delivery - Error trying to flush messages for agent " + target.getName() + " on node " + sliceName); -// Ignore it and try other slices... - } - } - } catch (ServiceException se) { - myLogger.log(Logger.WARNING, "Persistent-Delivery - Error retrieving storage-enabled slices to flush persisted messages for agent " + target.getName()); - } - }); - t.start(); - } - - private Slice[] getStorageEnabledSlices() throws ServiceException { - if (storageEnabledSliceNames != null) { - List ss = new ArrayList<>(storageEnabledSliceNames.length); - for (String storageEnabledSliceName : storageEnabledSliceNames) { - try { - Slice s = getSlice(storageEnabledSliceName); - ss.add(s); - } catch (ServiceException se) { - // Slice not present - } - } - return ss.toArray(new Slice[0]); - } else { - // No storage enabled slices explicitly specified --> Use all - return getAllSlices(); - } - } - - // The concrete agent container, providing access to LADT, etc. - private AgentContainer myContainer; - - // The service finder component - private ServiceFinder myServiceFinder; - - // The component managing ACL message storage and delayed delivery - private PersistentDeliveryManager myManager; - - // The local slice for this service - private final ServiceComponent localSlice = new ServiceComponent(); - - // The command filter, outgoing direction - private final CommandOutgoingFilter outFilter = new CommandOutgoingFilter(); - - // The command filter, incoming direction - private final CommandIncomingFilter inFilter = new CommandIncomingFilter(); - - // The filter to be matched by undelivered ACL messages - private PersistentDeliveryFilter messageFilter; - - private String[] storageEnabledSliceNames; } diff --git a/src/jade/core/messaging/RoutingTable.java b/src/jade/core/messaging/RoutingTable.java index 06ca267..db8c32d 100644 --- a/src/jade/core/messaging/RoutingTable.java +++ b/src/jade/core/messaging/RoutingTable.java @@ -38,144 +38,14 @@ class RoutingTable { - public interface OutPort { - void route(Envelope env, byte[] payload, AID receiver, String address) throws MTPException; - } - - - // This class wraps an MTP installed on a remote container, using - // RMI to forward the deliver() operation - private static class OutViaSlice implements OutPort { - - private final String sliceName; - private final MessagingSlice slice; - - public OutViaSlice(String sn, MessagingSlice ms) { - sliceName = sn; - slice = ms; - } - - public void route(Envelope env, byte[] payload, AID receiver, String address) throws MTPException { - try { - slice.routeOut(env, payload, receiver, address); - } catch (IMTPException imtpe) { - throw new MTPException("Container unreachable during routing", imtpe); - } - } - - public boolean equals(Object o) { - try { - OutViaSlice rhs = (OutViaSlice) o; - return sliceName.equals(rhs.sliceName); - } catch (ClassCastException cce) { - return false; - } - } - - } // End of OutViaContainer class - - - // This class wraps an MTP installed locally, using the ACC to encode - // the message into an MTP payload. - private static class OutViaMTP implements OutPort { - - private final OutChannel myChannel; - private final String platformInfo; - - public OutViaMTP(OutChannel proto, String platformInfo) { - myChannel = proto; - this.platformInfo = platformInfo; - } - - public void route(Envelope env, byte[] payload, AID receiver, String address) throws MTPException { - if (platformInfo != null) { - env.addProperties(new Property(MessagingService.PLATFORM_IDENTIFIER, platformInfo)); - env.addProperties(new Property(MessagingService.MTP_IDENTIFIER, myChannel.getClass().getName())); - } - myChannel.deliver(address, env, payload); - } - - public boolean equals(Object o) { - try { - OutViaMTP rhs = (OutViaMTP) o; - return myChannel.equals(rhs.myChannel); - } catch (ClassCastException cce) { - return false; - } - } - } - private static final boolean LOCAL = true; private static final boolean REMOTE = false; - - private static class OutPortList { - - private final List local = new ArrayList<>(1); - private final List remote = new ArrayList<>(1); - - public void add(OutPort port, boolean location) { - if (location == LOCAL) { - local.add(port); - } else { - remote.add(port); - } - } - - public void remove(OutPort port) { - local.remove(port); - remote.remove(port); - } - - public OutPort get() { - // Look first in the local list - if (!local.isEmpty()) - return local.get(0); - // Then look in the remote list - else if (!remote.isEmpty()) - return remote.get(0); - return null; - } - - public boolean isEmpty() { - return local.isEmpty() && remote.isEmpty(); - } - - public String size() { - return "[ local: " + local.size() + " remote: " + remote.size() + " ]"; - } - } // End of OutPortList class - - - /** - * Inner class MTPInfo - * This class just provides the association between a local MTP and its descriptor - */ - static class MTPInfo { - private final MTP mtp; - private final MTPDescriptor dsc; - - public MTPInfo(MTP mtp, MTPDescriptor dsc) { - this.mtp = mtp; - this.dsc = dsc; - } - - public MTP getMTP() { - return mtp; - } - - public MTPDescriptor getDescriptor() { - return dsc; - } - } // END of inner class MTPInfo - - + private static final int EXPECTED_PLATFORMADDRESSES_SIZE = 2; private final Map inPorts = new HashMap<>(2); private final Map outPorts = new HashMap<>(2); private final List remoteMTPs = new ArrayList<>(); - private static final int EXPECTED_PLATFORMADDRESSES_SIZE = 2; private final List platformAddresses = new ArrayList<>(EXPECTED_PLATFORMADDRESSES_SIZE); private String platformInfo = null; - public RoutingTable(boolean attachPlatformInfo) { if (attachPlatformInfo) { platformInfo = Runtime.getVersionInfo() + " (" + System.getProperty("java.version") + ", " + System.getProperty("os.name") + " " + System.getProperty("os.version") + ")"; @@ -223,7 +93,7 @@ public synchronized MTPInfo removeLocalMTP(String url) { // The MTP address is not a platform address anymore platformAddresses.remove(url); - + /* java.util.Iterator it = outPorts.keySet().iterator(); while(it.hasNext()) { @@ -325,5 +195,129 @@ private String extractProto(String address) { return null; return address.substring(0, colonPos); } + + public interface OutPort { + void route(Envelope env, byte[] payload, AID receiver, String address) throws MTPException; + } + + // This class wraps an MTP installed on a remote container, using + // RMI to forward the deliver() operation + private static class OutViaSlice implements OutPort { + + private final String sliceName; + private final MessagingSlice slice; + + public OutViaSlice(String sn, MessagingSlice ms) { + sliceName = sn; + slice = ms; + } + + public void route(Envelope env, byte[] payload, AID receiver, String address) throws MTPException { + try { + slice.routeOut(env, payload, receiver, address); + } catch (IMTPException imtpe) { + throw new MTPException("Container unreachable during routing", imtpe); + } + } + + public boolean equals(Object o) { + try { + OutViaSlice rhs = (OutViaSlice) o; + return sliceName.equals(rhs.sliceName); + } catch (ClassCastException cce) { + return false; + } + } + + } // End of OutViaContainer class + + // This class wraps an MTP installed locally, using the ACC to encode + // the message into an MTP payload. + private static class OutViaMTP implements OutPort { + + private final OutChannel myChannel; + private final String platformInfo; + + public OutViaMTP(OutChannel proto, String platformInfo) { + myChannel = proto; + this.platformInfo = platformInfo; + } + + public void route(Envelope env, byte[] payload, AID receiver, String address) throws MTPException { + if (platformInfo != null) { + env.addProperties(new Property(MessagingService.PLATFORM_IDENTIFIER, platformInfo)); + env.addProperties(new Property(MessagingService.MTP_IDENTIFIER, myChannel.getClass().getName())); + } + myChannel.deliver(address, env, payload); + } + + public boolean equals(Object o) { + try { + OutViaMTP rhs = (OutViaMTP) o; + return myChannel.equals(rhs.myChannel); + } catch (ClassCastException cce) { + return false; + } + } + } + + private static class OutPortList { + + private final List local = new ArrayList<>(1); + private final List remote = new ArrayList<>(1); + + public void add(OutPort port, boolean location) { + if (location == LOCAL) { + local.add(port); + } else { + remote.add(port); + } + } + + public void remove(OutPort port) { + local.remove(port); + remote.remove(port); + } + + public OutPort get() { + // Look first in the local list + if (!local.isEmpty()) + return local.get(0); + // Then look in the remote list + else if (!remote.isEmpty()) + return remote.get(0); + return null; + } + + public boolean isEmpty() { + return local.isEmpty() && remote.isEmpty(); + } + + public String size() { + return "[ local: " + local.size() + " remote: " + remote.size() + " ]"; + } + } // End of OutPortList class + + /** + * Inner class MTPInfo + * This class just provides the association between a local MTP and its descriptor + */ + static class MTPInfo { + private final MTP mtp; + private final MTPDescriptor dsc; + + public MTPInfo(MTP mtp, MTPDescriptor dsc) { + this.mtp = mtp; + this.dsc = dsc; + } + + public MTP getMTP() { + return mtp; + } + + public MTPDescriptor getDescriptor() { + return dsc; + } + } // END of inner class MTPInfo } diff --git a/src/jade/core/messaging/TopicManagementService.java b/src/jade/core/messaging/TopicManagementService.java index f239534..3172a3d 100644 --- a/src/jade/core/messaging/TopicManagementService.java +++ b/src/jade/core/messaging/TopicManagementService.java @@ -38,15 +38,12 @@ */ public class TopicManagementService extends BaseService { public static final String NAME = TopicManagementHelper.SERVICE_NAME; - + private final TopicTable topicTable = new TopicTable(); private AgentContainer myContainer; private MainContainer myMain; - private Filter incFilter; private Filter outFilter; private ServiceComponent localSlice; - - private final TopicTable topicTable = new TopicTable(); private MessagingService theMessagingService; private boolean shutdownInProgress = false; @@ -111,58 +108,6 @@ public String dump(String key) { return (topicTable + super.dump(key)); } - /** - * Inner class CommandOutgoingFilter. - * Intercepts the SEND_MESSAGE VCommand and broadcast messages directed to a topic to all - * agents interested in that topic - */ - private class CommandOutgoingFilter extends Filter { - public CommandOutgoingFilter() { - super(); - setPreferredPosition(2); // Before the Messaging (encoding) filter and the security related ones - } - - public final boolean accept(VerticalCommand cmd) { - String name = cmd.getName(); - if (name.equals(MessagingSlice.SEND_MESSAGE)) { - AID sender = (AID) cmd.getParam(0); - // NOTE that the gMsg cannot be a MultipleGenericMessage since we are in the outgoing chain - GenericMessage gMsg = (GenericMessage) cmd.getParam(1); - AID receiver = (AID) cmd.getParam(2); - - if (TopicUtility.isTopic(receiver)) { - // This message is directed to a Topic - if (myLogger.isLoggable(Logger.FINE)) { - myLogger.log(Logger.FINE, "Handling message about topic " + receiver.getLocalName()); - } - ACLMessage msg = gMsg.getACLMessage(); - Collection interestedAgents = topicTable.getInterestedAgents(receiver, msg); - if (interestedAgents.size() > 0) { - // Forward the message to all agents interested in that topic. - // Note that if no agents are currently listening to this topic, the message is simply swallowed - msg.addUserDefinedParameter(ACLMessage.IGNORE_FAILURE, "true"); - gMsg.setModifiable(false); - for (AID target : interestedAgents) { - if (myLogger.isLoggable(Logger.FINE)) { - myLogger.log(Logger.FINE, "Forwarding message to agent " + target.getName()); - } - sendMessage(sender, gMsg, target); - } - } - // Veto the original SEND_MESSAGE command - return false; - } - } else if (name.equals(AgentManagementSlice.SHUTDOWN_PLATFORM)) { - // Platform is shutting down. Avoid propagating information to remote slices - myLogger.log(Logger.INFO, "TopicManagentService: platform shutdown process initiation detected"); - shutdownInProgress = true; - } - // Never veto other commands - return true; - } - } // END of inner class CommandOutgoingFilter - - private void sendMessage(AID sender, GenericMessage gMsg, AID receiver) { GenericCommand cmd = new GenericCommand(MessagingSlice.SEND_MESSAGE, MessagingService.NAME, null); cmd.addParam(sender); @@ -177,38 +122,6 @@ private void sendMessage(AID sender, GenericMessage gMsg, AID receiver) { } } - - /** - * Inner class CommandIncomingFilter. - */ - private class CommandIncomingFilter extends Filter { - public boolean accept(VerticalCommand cmd) { - String name = cmd.getName(); - if (myMain != null) { - if (name.equals(AgentManagementSlice.INFORM_KILLED)) { - // If the dead agent was registered to some topic, deregister it - handleInformKilled(cmd); - } - if (name.equals(Service.NEW_SLICE)) { - // If the new slice is a TopicManagementSlice, notify it about the currently registered agents - handleNewSlice(cmd); - } - } else { - if (name.equals(Service.REATTACHED)) { - // The Main lost all information related to this container --> Notify it again - handleReattached(cmd); - } - } - // Never veto a Command - return true; - } - } // END of inner class CommandIncomingFilter - - - ////////////////////////////////////////////////// - // Methods called by the CommandIncomingFilter - ////////////////////////////////////////////////// - /** * If the dead agent was interested in some topic, notify all slices that its interest is no longer valid */ @@ -250,6 +163,11 @@ private void handleNewSlice(VerticalCommand cmd) { } } + + ////////////////////////////////////////////////// + // Methods called by the CommandIncomingFilter + ////////////////////////////////////////////////// + /** * The Main lost all information about the local node --> Notify the Main slice about all local registrations */ @@ -274,6 +192,125 @@ private void handleReattached(VerticalCommand cmd) { } } + /////////////////////////////////////////////////// + // Utility methods + /////////////////////////////////////////////////// + private void broadcastRegistration(AID aid, AID topic, Slice[] slices) { + if (myLogger.isLoggable(Logger.CONFIG)) { + myLogger.log(Logger.CONFIG, "Registering agent " + aid.getName() + " to topic " + topic.getLocalName()); + } + for (Slice value : slices) { + String sliceName = null; + try { + TopicManagementSlice slice = (TopicManagementSlice) value; + sliceName = slice.getNode().getName(); + if (myLogger.isLoggable(Logger.FINER)) { + myLogger.log(Logger.FINER, "Propagating registration of agent " + aid.getName() + " to slice " + sliceName); + } + slice.register(aid, topic); + } catch (Throwable t) { + // NOTE that slices are always retrieved from the main and not from the cache --> No need to retry in case of failure + myLogger.log(Logger.WARNING, "Error propagating topic registration to slice " + sliceName, t); + } + } + } + + private void broadcastDeregistration(AID aid, AID topic, Slice[] slices) { + if (myLogger.isLoggable(Logger.CONFIG)) { + myLogger.log(Logger.CONFIG, "Deregistering agent " + aid.getName() + " from topic " + topic.getLocalName()); + } + for (Slice value : slices) { + String sliceName = null; + try { + TopicManagementSlice slice = (TopicManagementSlice) value; + sliceName = slice.getNode().getName(); + if (myLogger.isLoggable(Logger.FINER)) { + myLogger.log(Logger.FINER, "Propagating deregistration of agent " + aid.getName() + " to slice " + sliceName); + } + slice.deregister(aid, topic); + } catch (Throwable t) { + // NOTE that slices are always retrieved from the main and not from the cache --> No need to retry in case of failure + myLogger.log(Logger.WARNING, "Error propagating topic de-registration to slice " + sliceName, t); + } + } + } + + /** + * Inner class CommandOutgoingFilter. + * Intercepts the SEND_MESSAGE VCommand and broadcast messages directed to a topic to all + * agents interested in that topic + */ + private class CommandOutgoingFilter extends Filter { + public CommandOutgoingFilter() { + super(); + setPreferredPosition(2); // Before the Messaging (encoding) filter and the security related ones + } + + public final boolean accept(VerticalCommand cmd) { + String name = cmd.getName(); + if (name.equals(MessagingSlice.SEND_MESSAGE)) { + AID sender = (AID) cmd.getParam(0); + // NOTE that the gMsg cannot be a MultipleGenericMessage since we are in the outgoing chain + GenericMessage gMsg = (GenericMessage) cmd.getParam(1); + AID receiver = (AID) cmd.getParam(2); + + if (TopicUtility.isTopic(receiver)) { + // This message is directed to a Topic + if (myLogger.isLoggable(Logger.FINE)) { + myLogger.log(Logger.FINE, "Handling message about topic " + receiver.getLocalName()); + } + ACLMessage msg = gMsg.getACLMessage(); + Collection interestedAgents = topicTable.getInterestedAgents(receiver, msg); + if (interestedAgents.size() > 0) { + // Forward the message to all agents interested in that topic. + // Note that if no agents are currently listening to this topic, the message is simply swallowed + msg.addUserDefinedParameter(ACLMessage.IGNORE_FAILURE, "true"); + gMsg.setModifiable(false); + for (AID target : interestedAgents) { + if (myLogger.isLoggable(Logger.FINE)) { + myLogger.log(Logger.FINE, "Forwarding message to agent " + target.getName()); + } + sendMessage(sender, gMsg, target); + } + } + // Veto the original SEND_MESSAGE command + return false; + } + } else if (name.equals(AgentManagementSlice.SHUTDOWN_PLATFORM)) { + // Platform is shutting down. Avoid propagating information to remote slices + myLogger.log(Logger.INFO, "TopicManagentService: platform shutdown process initiation detected"); + shutdownInProgress = true; + } + // Never veto other commands + return true; + } + } // END of inner class CommandOutgoingFilter + + /** + * Inner class CommandIncomingFilter. + */ + private class CommandIncomingFilter extends Filter { + public boolean accept(VerticalCommand cmd) { + String name = cmd.getName(); + if (myMain != null) { + if (name.equals(AgentManagementSlice.INFORM_KILLED)) { + // If the dead agent was registered to some topic, deregister it + handleInformKilled(cmd); + } + if (name.equals(Service.NEW_SLICE)) { + // If the new slice is a TopicManagementSlice, notify it about the currently registered agents + handleNewSlice(cmd); + } + } else { + if (name.equals(Service.REATTACHED)) { + // The Main lost all information related to this container --> Notify it again + handleReattached(cmd); + } + } + // Never veto a Command + return true; + } + } // END of inner class CommandIncomingFilter /** * Inner class ServiceComponent @@ -366,48 +403,4 @@ public void deregister(AID id, AID topic) throws ServiceException { broadcastDeregistration(id, topic, slices); } } // END of inner class TopicHelperImpl - - - /////////////////////////////////////////////////// - // Utility methods - /////////////////////////////////////////////////// - private void broadcastRegistration(AID aid, AID topic, Slice[] slices) { - if (myLogger.isLoggable(Logger.CONFIG)) { - myLogger.log(Logger.CONFIG, "Registering agent " + aid.getName() + " to topic " + topic.getLocalName()); - } - for (Slice value : slices) { - String sliceName = null; - try { - TopicManagementSlice slice = (TopicManagementSlice) value; - sliceName = slice.getNode().getName(); - if (myLogger.isLoggable(Logger.FINER)) { - myLogger.log(Logger.FINER, "Propagating registration of agent " + aid.getName() + " to slice " + sliceName); - } - slice.register(aid, topic); - } catch (Throwable t) { - // NOTE that slices are always retrieved from the main and not from the cache --> No need to retry in case of failure - myLogger.log(Logger.WARNING, "Error propagating topic registration to slice " + sliceName, t); - } - } - } - - private void broadcastDeregistration(AID aid, AID topic, Slice[] slices) { - if (myLogger.isLoggable(Logger.CONFIG)) { - myLogger.log(Logger.CONFIG, "Deregistering agent " + aid.getName() + " from topic " + topic.getLocalName()); - } - for (Slice value : slices) { - String sliceName = null; - try { - TopicManagementSlice slice = (TopicManagementSlice) value; - sliceName = slice.getNode().getName(); - if (myLogger.isLoggable(Logger.FINER)) { - myLogger.log(Logger.FINER, "Propagating deregistration of agent " + aid.getName() + " to slice " + sliceName); - } - slice.deregister(aid, topic); - } catch (Throwable t) { - // NOTE that slices are always retrieved from the main and not from the cache --> No need to retry in case of failure - myLogger.log(Logger.WARNING, "Error propagating topic de-registration to slice " + sliceName, t); - } - } - } } diff --git a/src/jade/core/messaging/TopicTable.java b/src/jade/core/messaging/TopicTable.java index 37b35d9..15ffdab 100644 --- a/src/jade/core/messaging/TopicTable.java +++ b/src/jade/core/messaging/TopicTable.java @@ -105,8 +105,8 @@ public String toString() { */ private class RegistrationInfo { private final AID aid; - private boolean template = false; private final StringTokenizer st; + private boolean template = false; private RegistrationInfo(AID aid, AID topic) { st = new StringTokenizer(topic.getLocalName(), "."); diff --git a/src/jade/core/mobility/AgentMobilityHelper.java b/src/jade/core/mobility/AgentMobilityHelper.java index a2da77c..04eba38 100644 --- a/src/jade/core/mobility/AgentMobilityHelper.java +++ b/src/jade/core/mobility/AgentMobilityHelper.java @@ -35,22 +35,10 @@ */ public interface AgentMobilityHelper extends ServiceHelper { - void registerMovable(Movable m); - - void move(Location destination); - - void clone(Location destination, String newName); - - //#J2ME_EXCLUDE_BEGIN - ClassLoader getContainerClassLoader(String containerName, ClassLoader parent) throws ServiceException; - //#J2ME_EXCLUDE_END - /** * The name of this service. */ String NAME = "jade.core.mobility.AgentMobility"; - - /** * This command name represents the move-agent * action. @@ -62,7 +50,6 @@ public interface AgentMobilityHelper extends ServiceHelper { * the agent migration has taken place. */ String REQUEST_MOVE = "Request-Move"; - /** * This command name represents the clone-agent * action. @@ -74,7 +61,6 @@ public interface AgentMobilityHelper extends ServiceHelper { * the agent clonation has taken place. */ String REQUEST_CLONE = "Request-Clone"; - /** * This command is issued by an agent that has just migrated. * The agent migration can either be an autonomous move of the @@ -84,7 +70,7 @@ public interface AgentMobilityHelper extends ServiceHelper { * agent migration process. */ String INFORM_MOVED = "Inform-Moved"; - + //#J2ME_EXCLUDE_END /** * This command is issued by an agent that has just cloned itself. * The agent clonation can either be an autonomous move of the @@ -95,6 +81,15 @@ public interface AgentMobilityHelper extends ServiceHelper { */ String INFORM_CLONED = "Inform-Cloned"; + void registerMovable(Movable m); + + void move(Location destination); + + void clone(Location destination, String newName); + + //#J2ME_EXCLUDE_BEGIN + ClassLoader getContainerClassLoader(String containerName, ClassLoader parent) throws ServiceException; + //void informCloned(AID agentID, Location where, String newName) throws ServiceException, JADESecurityException, IMTPException, NotFoundException, NameClashException; diff --git a/src/jade/core/mobility/AgentMobilityService.java b/src/jade/core/mobility/AgentMobilityService.java index 5ed27df..e63c6ac 100644 --- a/src/jade/core/mobility/AgentMobilityService.java +++ b/src/jade/core/mobility/AgentMobilityService.java @@ -56,46 +56,60 @@ public class AgentMobilityService extends BaseService { public static final int AP_TRANSIT = 7; public static final int AP_COPY = 8; public static final int AP_GONE = 9; - - + static final boolean MIGRATION = false; + static final boolean CLONING = true; + static final boolean CREATE_AND_START = true; + static final boolean CREATE_ONLY = false; + static final boolean TRANSFER_ABORT = false; + static final boolean TRANSFER_COMMIT = true; private static final String[] OWNED_COMMANDS = new String[]{ AgentMobilityHelper.REQUEST_MOVE, AgentMobilityHelper.REQUEST_CLONE, AgentMobilityHelper.INFORM_MOVED, AgentMobilityHelper.INFORM_CLONED }; - private static final int SIZE_JAR_BUFFER = 4096; + private static final HashMap> primitiveJavaClasses = new HashMap<>(8, 1.0F); - static final boolean MIGRATION = false; - static final boolean CLONING = true; - - static final boolean CREATE_AND_START = true; - static final boolean CREATE_ONLY = false; - - static final boolean TRANSFER_ABORT = false; - static final boolean TRANSFER_COMMIT = true; - + static { + primitiveJavaClasses.put("boolean", boolean.class); + primitiveJavaClasses.put("byte", byte.class); + primitiveJavaClasses.put("char", char.class); + primitiveJavaClasses.put("short", short.class); + primitiveJavaClasses.put("int", int.class); + primitiveJavaClasses.put("long", long.class); + primitiveJavaClasses.put("float", float.class); + primitiveJavaClasses.put("double", double.class); + primitiveJavaClasses.put("void", void.class); + } // The command sink, source side private final CommandSourceSink senderSink = new CommandSourceSink(); - + //#J2ME_EXCLUDE_END // The command sink, target side private final CommandTargetSink receiverSink = new CommandTargetSink(); - //#J2ME_EXCLUDE_BEGIN // Filter for outgoing commands private final Filter _outFilter = new CommandOutgoingFilter(); - //#J2ME_EXCLUDE_END - + // This Map holds the mapping between a container/agent pair and the class loader + // that can retrieve agent classes from that container. + private final Map loaders = new HashMap<>(); + // This Map holds the mapping between an agent that arrived on this + // container and the service slice where its classes can be found + private final Map sites = new HashMap<>(); + // The local slice for this service + private final ServiceComponent localSlice = new ServiceComponent(); // The handle to the MainReplicationService to keep GADT in synch when agents move private MainReplicationHandle replicationHandle; + // The concrete agent container, providing access to LADT, etc. + private AgentContainer myContainer; public void init(AgentContainer ac, Profile p) throws ProfileException { super.init(ac, p); myContainer = ac; } + //#J2ME_EXCLUDE_END public void boot(Profile myProfile) throws ServiceException { // Initialize the MainReplicationHandle @@ -145,109 +159,355 @@ public String getClassSite(Agent a) { return sites.get(a); } - // This inner class handles the messaging commands on the command - // issuer side, turning them into horizontal commands and - // forwarding them to remote slices when necessary. - private class CommandSourceSink implements Sink { + // Modify GADT to reflect an agent transfer + // Public since it is replicated by the MainReplicationService + public void movedAgent(AID agentID, ContainerID src, ContainerID dest) throws NotFoundException { + myContainer.getMain().movedAgent(agentID, src, dest); + } - public void consume(VerticalCommand cmd) { + // Modify GADT to reflect an agent clonation + // Public since it is replicated by the MainReplicationService + public void bornAgent(AID agentID, ContainerID cid, JADEPrincipal principal, String ownership, boolean forceReplacement) throws NameClashException, NotFoundException { + MainContainer impl = myContainer.getMain(); + try { + impl.bornAgent(agentID, cid, principal, ownership, forceReplacement); + } catch (NameClashException nce) { try { - String name = cmd.getName(); - switch (name) { - case AgentMobilityHelper.REQUEST_MOVE -> handleRequestMove(cmd); - case AgentMobilityHelper.REQUEST_CLONE -> handleRequestClone(cmd); - case AgentMobilityHelper.INFORM_MOVED -> handleInformMoved(cmd); - case AgentMobilityHelper.INFORM_CLONED -> handleInformCloned(cmd); - } - } catch (IMTPException | NotFoundException | NameClashException | JADESecurityException imtpe) { - cmd.setReturnValue(imtpe); + ContainerID oldCid = impl.getContainerID(agentID); + Node n = impl.getContainerNode(oldCid).getNode(); + + // Perform a non-blocking ping to check... + n.ping(false); + + // Ping succeeded: rethrow the NameClashException + throw nce; + } catch (NameClashException nce2) { + throw nce2; // Let this one through... + } catch (Exception e) { + // Ping failed: forcibly replace the dead agent... + impl.bornAgent(agentID, cid, null, ownership, true); + } + } + } + + // Work-around for PJAVA compilation + protected Slice getFreshSlice(String name) throws ServiceException { + return super.getFreshSlice(name); + } + + private void initCredentials(Command cmd, AID id) { + Agent agent = myContainer.acquireLocalAgent(id); + if (agent != null) { + try { + CredentialsHelper ch = (CredentialsHelper) agent.getHelper("jade.core.security.Security"); + cmd.setPrincipal(ch.getPrincipal()); + cmd.setCredentials(ch.getCredentials()); } catch (ServiceException se) { - cmd.setReturnValue(new IMTPException("Service error", se)); + // The security plug-in is not there. Just ignore it } } + myContainer.releaseLocalAgent(id); + } + /** + * Inner class TransitLifeCycle + */ + private static class TransitLifeCycle extends LifeCycle { + private final Movable myMovable; + private final transient AgentMobilityService myService; + private final Logger myLogger; + private Location myDestination; + private boolean firstTime = true; + private boolean messageAware = false; - // Vertical command handler methods + private TransitLifeCycle(Location l, Movable m, AgentMobilityService s) { + super(AP_TRANSIT); + myDestination = l; + myMovable = m; + myService = s; + myLogger = Logger.getMyLogger(myService.getName()); + } - private void handleRequestMove(VerticalCommand cmd) throws IMTPException, ServiceException, NotFoundException { - Object[] params = cmd.getParams(); - AID agentID = (AID) params[0]; - Location where = (Location) params[1]; + public void init() { + myAgent.restoreBufferedState(); + if (myMovable != null) { + myMovable.afterMove(); + } + } - MainContainer impl = myContainer.getMain(); - if (impl != null) { - ContainerID cid = impl.getContainerID(agentID); - AgentMobilitySlice targetSlice = (AgentMobilitySlice) getSlice(cid.getName()); - try { - targetSlice.moveAgent(agentID, where); - } catch (IMTPException imtpe) { - // Try to get a newer slice and repeat... - targetSlice = (AgentMobilitySlice) getFreshSlice(cid.getName()); - targetSlice.moveAgent(agentID, where); + public void execute() throws JADESecurityException, InterruptedException, InterruptedIOException { + try { + // Call beforeMove() and issue an INFORM_MOVED vertical command + if (firstTime) { + firstTime = false; + if (myMovable != null) { + messageAware = true; + myMovable.beforeMove(); + messageAware = false; + } + informMoved(myAgent.getAID(), myDestination); + } + } catch (Exception e) { + if (myAgent.getState() == myState) { + // Something went wrong during the transfer. Rollback + myAgent.restoreBufferedState(); + myDestination = null; + if (e instanceof JADESecurityException) { + // Will be caught together with all other JADESecurityException-s + throw (JADESecurityException) e; + } else { + e.printStackTrace(); + } + } else { + throw new Interrupted(); } - } else { - // Do nothing for now, but could also route the command to the main slice, thus enabling e.g. AMS replication } } - private void handleRequestClone(VerticalCommand cmd) throws IMTPException, ServiceException, NotFoundException { - Object[] params = cmd.getParams(); - AID agentID = (AID) params[0]; - Location where = (Location) params[1]; - String newName = (String) params[2]; + public void end() { + if (myLogger.isLoggable(Logger.SEVERE)) + myLogger.log(Logger.SEVERE, "*** Agent " + myAgent.getName() + " moved in a forbidden situation ***"); - MainContainer impl = myContainer.getMain(); - if (impl != null) { - ContainerID cid = impl.getContainerID(agentID); - AgentMobilitySlice targetSlice = (AgentMobilitySlice) getSlice(cid.getName()); - try { - targetSlice.copyAgent(agentID, where, newName); - } catch (IMTPException imtpe) { - // Try to get a newer slice and repeat... - targetSlice = (AgentMobilitySlice) getFreshSlice(cid.getName()); - targetSlice.copyAgent(agentID, where, newName); - } - } else { - // Do nothing for now, but could also route the command to the main slice, thus enabling e.g. AMS replication - } + myAgent.clean(true); } - private void handleInformMoved(VerticalCommand cmd) throws IMTPException, ServiceException, JADESecurityException, NotFoundException { - Object[] params = cmd.getParams(); - AID agentID = (AID) params[0]; - Location where = (Location) params[1]; + public boolean transitionTo(LifeCycle newLF) { + int s = newLF.getState(); + return (s == AP_GONE || s == Agent.AP_ACTIVE || s == Agent.AP_DELETED); + } - if (myLogger.isLoggable(Logger.CONFIG)) - myLogger.log(Logger.CONFIG, "Moving agent " + agentID.getName() + " on container " + where.getName()); + public boolean isMessageAware() { + return messageAware; + } - Agent a = myContainer.acquireLocalAgent(agentID); - if (a == null) { - myLogger.log(Logger.SEVERE, "Internal error: handleMove() called with a wrong name (" + agentID.getName() + ") !!!"); - return; - } + public void informMoved(AID agentID, Location where) throws ServiceException, JADESecurityException, NotFoundException, IMTPException { + GenericCommand cmd = new GenericCommand(AgentMobilityHelper.INFORM_MOVED, AgentMobilitySlice.NAME, null); + cmd.addParam(agentID); + cmd.addParam(where); + // Set the credentials of the moving agent + myService.initCredentials(cmd, agentID); - int transferState = 0; - List messages = new ArrayList<>(); - AgentMobilitySlice dest = null; - try { - // If the destination container is the same as this one, there is nothing to do - if (CaseInsensitiveString.equalsIgnoreCase(where.getName(), myContainer.here().getName())) { - return; + Object lastException = myService.submit(cmd); + if (lastException != null) { + if (lastException instanceof JADESecurityException) { + throw (JADESecurityException) lastException; } - - dest = (AgentMobilitySlice) getSlice(where.getName()); - if (dest == null) { - myLogger.log(Logger.SEVERE, "Destination " + where.getName() + " does not exist or does not support mobility"); - return; + if (lastException instanceof NotFoundException) { + throw (NotFoundException) lastException; } - if (myLogger.isLoggable(Logger.FINE)) { - myLogger.log(Logger.FINE, "Destination container for agent " + agentID + " found"); + if (lastException instanceof IMTPException) { + throw (IMTPException) lastException; } + } + } + } // END of inner class TransitLifeCycle - transferState = 1; + /** + * Inner class CopyLifeCycle + */ + private static class CopyLifeCycle extends LifeCycle { + private final Movable myMovable; + private final transient AgentMobilityService myService; + private final Logger myLogger; + private Location myDestination; + private String myNewName; + private boolean firstTime = true; + private boolean messageAware = false; - // Serialize the agent - ByteArrayOutputStream out = new ByteArrayOutputStream(); + private CopyLifeCycle(Location l, String newName, Movable m, AgentMobilityService s) { + super(AP_COPY); + myDestination = l; + myNewName = newName; + myMovable = m; + myService = s; + myLogger = Logger.getMyLogger(myService.getName()); + } + + public void init() { + myAgent.restoreBufferedState(); + if (myMovable != null) { + myMovable.afterClone(); + } + } + + public void execute() throws JADESecurityException, InterruptedException, InterruptedIOException { + try { + // Call beforeClone() and issue an INFORM_CLONED vertical command + if (firstTime) { + firstTime = false; + if (myMovable != null) { + messageAware = true; + myMovable.beforeClone(); + messageAware = false; + } + informCloned(myAgent.getAID(), myDestination, myNewName); + } + } catch (Exception e) { + if (myAgent.getState() == myState) { + // Something went wrong during the clonation. Rollback + myDestination = null; + myNewName = null; + myAgent.restoreBufferedState(); + if (e instanceof JADESecurityException) { + // Will be catched together with all other JADESecurityException-s + throw (JADESecurityException) e; + } else { + e.printStackTrace(); + return; + } + } else { + throw new Interrupted(); + } + } + // Once cloned go back to the previous state + myAgent.restoreBufferedState(); + } + + public boolean transitionTo(LifeCycle newLF) { + int s = newLF.getState(); + return (s == Agent.AP_ACTIVE || s == Agent.AP_DELETED); + } + + public boolean isMessageAware() { + return messageAware; + } + + public void end() { + //System.err.println("*** Agent " + myAgent.getName() + " cloned in a forbidden situation ***"); + if (myLogger.isLoggable(Logger.SEVERE)) + myLogger.log(Logger.SEVERE, "*** Agent " + myAgent.getName() + " cloned in a forbidden situation ***"); + myAgent.clean(true); + } + + public void informCloned(AID agentID, Location where, String newName) throws ServiceException, JADESecurityException, IMTPException, NotFoundException, NameClashException { + GenericCommand cmd = new GenericCommand(AgentMobilityHelper.INFORM_CLONED, AgentMobilitySlice.NAME, null); + cmd.addParam(agentID); + cmd.addParam(where); + cmd.addParam(newName); + // Set the credentials of the cloning agent + myService.initCredentials(cmd, agentID); + + Object lastException = myService.submit(cmd); + if (lastException != null) { + if (lastException instanceof JADESecurityException) { + throw (JADESecurityException) lastException; + } + if (lastException instanceof NotFoundException) { + throw (NotFoundException) lastException; + } + if (lastException instanceof IMTPException) { + throw (IMTPException) lastException; + } + if (lastException instanceof NameClashException) { + throw (NameClashException) lastException; + } + } + } + } // END of inner class CopyLifeCycle + + // This inner class handles the messaging commands on the command + // issuer side, turning them into horizontal commands and + // forwarding them to remote slices when necessary. + private class CommandSourceSink implements Sink { + + public void consume(VerticalCommand cmd) { + try { + String name = cmd.getName(); + switch (name) { + case AgentMobilityHelper.REQUEST_MOVE -> handleRequestMove(cmd); + case AgentMobilityHelper.REQUEST_CLONE -> handleRequestClone(cmd); + case AgentMobilityHelper.INFORM_MOVED -> handleInformMoved(cmd); + case AgentMobilityHelper.INFORM_CLONED -> handleInformCloned(cmd); + } + } catch (IMTPException | NotFoundException | NameClashException | JADESecurityException imtpe) { + cmd.setReturnValue(imtpe); + } catch (ServiceException se) { + cmd.setReturnValue(new IMTPException("Service error", se)); + } + } + + + // Vertical command handler methods + + private void handleRequestMove(VerticalCommand cmd) throws IMTPException, ServiceException, NotFoundException { + Object[] params = cmd.getParams(); + AID agentID = (AID) params[0]; + Location where = (Location) params[1]; + + MainContainer impl = myContainer.getMain(); + if (impl != null) { + ContainerID cid = impl.getContainerID(agentID); + AgentMobilitySlice targetSlice = (AgentMobilitySlice) getSlice(cid.getName()); + try { + targetSlice.moveAgent(agentID, where); + } catch (IMTPException imtpe) { + // Try to get a newer slice and repeat... + targetSlice = (AgentMobilitySlice) getFreshSlice(cid.getName()); + targetSlice.moveAgent(agentID, where); + } + } else { + // Do nothing for now, but could also route the command to the main slice, thus enabling e.g. AMS replication + } + } + + private void handleRequestClone(VerticalCommand cmd) throws IMTPException, ServiceException, NotFoundException { + Object[] params = cmd.getParams(); + AID agentID = (AID) params[0]; + Location where = (Location) params[1]; + String newName = (String) params[2]; + + MainContainer impl = myContainer.getMain(); + if (impl != null) { + ContainerID cid = impl.getContainerID(agentID); + AgentMobilitySlice targetSlice = (AgentMobilitySlice) getSlice(cid.getName()); + try { + targetSlice.copyAgent(agentID, where, newName); + } catch (IMTPException imtpe) { + // Try to get a newer slice and repeat... + targetSlice = (AgentMobilitySlice) getFreshSlice(cid.getName()); + targetSlice.copyAgent(agentID, where, newName); + } + } else { + // Do nothing for now, but could also route the command to the main slice, thus enabling e.g. AMS replication + } + } + + private void handleInformMoved(VerticalCommand cmd) throws IMTPException, ServiceException, JADESecurityException, NotFoundException { + Object[] params = cmd.getParams(); + AID agentID = (AID) params[0]; + Location where = (Location) params[1]; + + if (myLogger.isLoggable(Logger.CONFIG)) + myLogger.log(Logger.CONFIG, "Moving agent " + agentID.getName() + " on container " + where.getName()); + + Agent a = myContainer.acquireLocalAgent(agentID); + if (a == null) { + myLogger.log(Logger.SEVERE, "Internal error: handleMove() called with a wrong name (" + agentID.getName() + ") !!!"); + return; + } + + int transferState = 0; + List messages = new ArrayList<>(); + AgentMobilitySlice dest = null; + try { + // If the destination container is the same as this one, there is nothing to do + if (CaseInsensitiveString.equalsIgnoreCase(where.getName(), myContainer.here().getName())) { + return; + } + + dest = (AgentMobilitySlice) getSlice(where.getName()); + if (dest == null) { + myLogger.log(Logger.SEVERE, "Destination " + where.getName() + " does not exist or does not support mobility"); + return; + } + if (myLogger.isLoggable(Logger.FINE)) { + myLogger.log(Logger.FINE, "Destination container for agent " + agentID + " found"); + } + + transferState = 1; + + // Serialize the agent + ByteArrayOutputStream out = new ByteArrayOutputStream(); ObjectOutputStream encoder = new ObjectOutputStream(out); encoder.writeObject(a); byte[] bytes = out.toByteArray(); @@ -489,7 +749,6 @@ private void handleInformCloned(VerticalCommand cmd) throws IMTPException, NotFo } // End of CommandSourceSink class - // This inner class handles the messaging commands on the command // issuer side, turning them into horizontal commands and // forwarding them to remote slices when necessary. @@ -538,10 +797,10 @@ private void handleInformMoved(VerticalCommand cmd) throws IMTPException { try { // Nothing to do here: INFORM_MOVED has no target-side action... /* --- This code should go into the Security Service --- - + // agent is about to be created on the destination Container, // let's check for permissions before - + // does the agent come from a MOVE or a CLONE ? switch (instance.getState()) { case Agent.AP_TRANSIT: // MOVED @@ -559,9 +818,9 @@ private void handleInformMoved(VerticalCommand cmd) throws IMTPException { instance.getCertificateFolder() ); break; } // end switch - + log("Permissions for agent " + agentID + " OK", 2); - + // --- End of code that should go into the Security Service --- */ @@ -569,7 +828,7 @@ private void handleInformMoved(VerticalCommand cmd) throws IMTPException { //#MIDP_EXCLUDE_BEGIN //CertificateFolder agentCerts = instance.getCertificateFolder(); //#MIDP_EXCLUDE_END - + /*# MIDP_INCLUDE_BEGIN CertificateFolder agentCerts = new CertificateFolder(); # MIDP_INCLUDE_END*/ @@ -660,7 +919,6 @@ private void clonedAgent(AID agentID, ContainerID cid, Credentials credentials) } // End of CommandTargetSink class - //#J2ME_EXCLUDE_BEGIN private class CommandOutgoingFilter extends Filter { @@ -723,8 +981,6 @@ private void handleInformKilled(VerticalCommand cmd) throws IMTPException, NotFo } } } // End of CommandOutgoingFilter class - //#J2ME_EXCLUDE_END - /** * Inner mix-in class for this service: this class receives @@ -868,7 +1124,7 @@ private Agent deserializeAgent(AID agentID, byte[] serializedInstance, String cl ByteArrayInputStream in = new ByteArrayInputStream(serializedInstance); ObjectInputStream decoder = new ObjectInputStream(in); Object obj = decoder.readObject(); - + Agent instance = (Agent) obj; #DOTNET_INCLUDE_END*/ @@ -1010,30 +1266,6 @@ private ClassInfo getClassStreamFromJar(String classFileName, String jarName) th return null; } - - /** - * Inner class ClassInfo - * This utility bean class is used only to keep together some pieces of information related to a class - */ - private class ClassInfo { - private final InputStream classStream; - private int length = -1; - - public ClassInfo(InputStream is, int l) { - classStream = is; - length = l; - } - - public InputStream getClassStream() { - return classStream; - } - - public int getLength() { - return length; - } - } // END of inner class ClassInfo - - private void handleTransferResult(AID agentID, boolean result, List messages) throws NotFoundException { if (myLogger.isLoggable(Logger.FINER)) myLogger.log(Logger.FINER, "Activating incoming agent " + agentID); @@ -1165,40 +1397,30 @@ private void handleRemoveCodeLocatorEntry(AID agentID) throws IMTPException, Ser CodeLocator codeLocator = amSrv.getCodeLocator(); codeLocator.removeAgent(agentID); } - //#J2ME_EXCLUDE_END - } // End of ServiceComponent class + /** + * Inner class ClassInfo + * This utility bean class is used only to keep together some pieces of information related to a class + */ + private class ClassInfo { + private final InputStream classStream; + private int length = -1; - // Modify GADT to reflect an agent transfer - // Public since it is replicated by the MainReplicationService - public void movedAgent(AID agentID, ContainerID src, ContainerID dest) throws NotFoundException { - myContainer.getMain().movedAgent(agentID, src, dest); - } + public ClassInfo(InputStream is, int l) { + classStream = is; + length = l; + } - // Modify GADT to reflect an agent clonation - // Public since it is replicated by the MainReplicationService - public void bornAgent(AID agentID, ContainerID cid, JADEPrincipal principal, String ownership, boolean forceReplacement) throws NameClashException, NotFoundException { - MainContainer impl = myContainer.getMain(); - try { - impl.bornAgent(agentID, cid, principal, ownership, forceReplacement); - } catch (NameClashException nce) { - try { - ContainerID oldCid = impl.getContainerID(agentID); - Node n = impl.getContainerNode(oldCid).getNode(); - - // Perform a non-blocking ping to check... - n.ping(false); + public InputStream getClassStream() { + return classStream; + } - // Ping succeeded: rethrow the NameClashException - throw nce; - } catch (NameClashException nce2) { - throw nce2; // Let this one through... - } catch (Exception e) { - // Ping failed: forcibly replace the dead agent... - impl.bornAgent(agentID, cid, null, ownership, true); + public int getLength() { + return length; } - } - } + } // END of inner class ClassInfo + //#J2ME_EXCLUDE_END + } // End of ServiceComponent class /** * Inner class Deserializer @@ -1257,35 +1479,6 @@ private String createClassLoaderKey(String agentName, String classSiteName) { } // END of inner class Deserializer - private static final HashMap> primitiveJavaClasses = new HashMap<>(8, 1.0F); - - static { - primitiveJavaClasses.put("boolean", boolean.class); - primitiveJavaClasses.put("byte", byte.class); - primitiveJavaClasses.put("char", char.class); - primitiveJavaClasses.put("short", short.class); - primitiveJavaClasses.put("int", int.class); - primitiveJavaClasses.put("long", long.class); - primitiveJavaClasses.put("float", float.class); - primitiveJavaClasses.put("double", double.class); - primitiveJavaClasses.put("void", void.class); - } - - // This Map holds the mapping between a container/agent pair and the class loader - // that can retrieve agent classes from that container. - private final Map loaders = new HashMap<>(); - - // This Map holds the mapping between an agent that arrived on this - // container and the service slice where its classes can be found - private final Map sites = new HashMap<>(); - - // The concrete agent container, providing access to LADT, etc. - private AgentContainer myContainer; - - // The local slice for this service - private final ServiceComponent localSlice = new ServiceComponent(); - - /** * Inner class AgentMobilityHelperImpl. * The actual implementation of the AgentMobilityHelper interface. @@ -1320,223 +1513,5 @@ public ClassLoader getContainerClassLoader(String codeSourceContainer, ClassLoad } //#J2ME_EXCLUDE_END } // END of inner class AgentMobilityHelperImpl - - - /** - * Inner class TransitLifeCycle - */ - private static class TransitLifeCycle extends LifeCycle { - private Location myDestination; - private final Movable myMovable; - private final transient AgentMobilityService myService; - private final Logger myLogger; - private boolean firstTime = true; - private boolean messageAware = false; - - private TransitLifeCycle(Location l, Movable m, AgentMobilityService s) { - super(AP_TRANSIT); - myDestination = l; - myMovable = m; - myService = s; - myLogger = Logger.getMyLogger(myService.getName()); - } - - public void init() { - myAgent.restoreBufferedState(); - if (myMovable != null) { - myMovable.afterMove(); - } - } - - public void execute() throws JADESecurityException, InterruptedException, InterruptedIOException { - try { - // Call beforeMove() and issue an INFORM_MOVED vertical command - if (firstTime) { - firstTime = false; - if (myMovable != null) { - messageAware = true; - myMovable.beforeMove(); - messageAware = false; - } - informMoved(myAgent.getAID(), myDestination); - } - } catch (Exception e) { - if (myAgent.getState() == myState) { - // Something went wrong during the transfer. Rollback - myAgent.restoreBufferedState(); - myDestination = null; - if (e instanceof JADESecurityException) { - // Will be caught together with all other JADESecurityException-s - throw (JADESecurityException) e; - } else { - e.printStackTrace(); - } - } else { - throw new Interrupted(); - } - } - } - - public void end() { - if (myLogger.isLoggable(Logger.SEVERE)) - myLogger.log(Logger.SEVERE, "*** Agent " + myAgent.getName() + " moved in a forbidden situation ***"); - - myAgent.clean(true); - } - - public boolean transitionTo(LifeCycle newLF) { - int s = newLF.getState(); - return (s == AP_GONE || s == Agent.AP_ACTIVE || s == Agent.AP_DELETED); - } - - public boolean isMessageAware() { - return messageAware; - } - - public void informMoved(AID agentID, Location where) throws ServiceException, JADESecurityException, NotFoundException, IMTPException { - GenericCommand cmd = new GenericCommand(AgentMobilityHelper.INFORM_MOVED, AgentMobilitySlice.NAME, null); - cmd.addParam(agentID); - cmd.addParam(where); - // Set the credentials of the moving agent - myService.initCredentials(cmd, agentID); - - Object lastException = myService.submit(cmd); - if (lastException != null) { - if (lastException instanceof JADESecurityException) { - throw (JADESecurityException) lastException; - } - if (lastException instanceof NotFoundException) { - throw (NotFoundException) lastException; - } - if (lastException instanceof IMTPException) { - throw (IMTPException) lastException; - } - } - } - } // END of inner class TransitLifeCycle - - - /** - * Inner class CopyLifeCycle - */ - private static class CopyLifeCycle extends LifeCycle { - private Location myDestination; - private String myNewName; - private final Movable myMovable; - private final transient AgentMobilityService myService; - private final Logger myLogger; - private boolean firstTime = true; - private boolean messageAware = false; - - private CopyLifeCycle(Location l, String newName, Movable m, AgentMobilityService s) { - super(AP_COPY); - myDestination = l; - myNewName = newName; - myMovable = m; - myService = s; - myLogger = Logger.getMyLogger(myService.getName()); - } - - public void init() { - myAgent.restoreBufferedState(); - if (myMovable != null) { - myMovable.afterClone(); - } - } - - public void execute() throws JADESecurityException, InterruptedException, InterruptedIOException { - try { - // Call beforeClone() and issue an INFORM_CLONED vertical command - if (firstTime) { - firstTime = false; - if (myMovable != null) { - messageAware = true; - myMovable.beforeClone(); - messageAware = false; - } - informCloned(myAgent.getAID(), myDestination, myNewName); - } - } catch (Exception e) { - if (myAgent.getState() == myState) { - // Something went wrong during the clonation. Rollback - myDestination = null; - myNewName = null; - myAgent.restoreBufferedState(); - if (e instanceof JADESecurityException) { - // Will be catched together with all other JADESecurityException-s - throw (JADESecurityException) e; - } else { - e.printStackTrace(); - return; - } - } else { - throw new Interrupted(); - } - } - // Once cloned go back to the previous state - myAgent.restoreBufferedState(); - } - - public boolean transitionTo(LifeCycle newLF) { - int s = newLF.getState(); - return (s == Agent.AP_ACTIVE || s == Agent.AP_DELETED); - } - - public boolean isMessageAware() { - return messageAware; - } - - public void end() { - //System.err.println("*** Agent " + myAgent.getName() + " cloned in a forbidden situation ***"); - if (myLogger.isLoggable(Logger.SEVERE)) - myLogger.log(Logger.SEVERE, "*** Agent " + myAgent.getName() + " cloned in a forbidden situation ***"); - myAgent.clean(true); - } - - public void informCloned(AID agentID, Location where, String newName) throws ServiceException, JADESecurityException, IMTPException, NotFoundException, NameClashException { - GenericCommand cmd = new GenericCommand(AgentMobilityHelper.INFORM_CLONED, AgentMobilitySlice.NAME, null); - cmd.addParam(agentID); - cmd.addParam(where); - cmd.addParam(newName); - // Set the credentials of the cloning agent - myService.initCredentials(cmd, agentID); - - Object lastException = myService.submit(cmd); - if (lastException != null) { - if (lastException instanceof JADESecurityException) { - throw (JADESecurityException) lastException; - } - if (lastException instanceof NotFoundException) { - throw (NotFoundException) lastException; - } - if (lastException instanceof IMTPException) { - throw (IMTPException) lastException; - } - if (lastException instanceof NameClashException) { - throw (NameClashException) lastException; - } - } - } - } // END of inner class CopyLifeCycle - - - // Work-around for PJAVA compilation - protected Slice getFreshSlice(String name) throws ServiceException { - return super.getFreshSlice(name); - } - - private void initCredentials(Command cmd, AID id) { - Agent agent = myContainer.acquireLocalAgent(id); - if (agent != null) { - try { - CredentialsHelper ch = (CredentialsHelper) agent.getHelper("jade.core.security.Security"); - cmd.setPrincipal(ch.getPrincipal()); - cmd.setCredentials(ch.getCredentials()); - } catch (ServiceException se) { - // The security plug-in is not there. Just ignore it - } - } - myContainer.releaseLocalAgent(id); - } } diff --git a/src/jade/core/mobility/MobileAgentClassLoader.java b/src/jade/core/mobility/MobileAgentClassLoader.java index 9f35ed4..5ff1440 100644 --- a/src/jade/core/mobility/MobileAgentClassLoader.java +++ b/src/jade/core/mobility/MobileAgentClassLoader.java @@ -37,11 +37,11 @@ */ class MobileAgentClassLoader extends ClassLoader { - private AgentMobilitySlice classServer; private final String agentName; private final String sliceName; private final ServiceFinder finder; private final Logger myLogger = Logger.getMyLogger(AgentMobilityService.NAME); + private AgentMobilitySlice classServer; public MobileAgentClassLoader(String an, String sn, ServiceFinder sf, ClassLoader parent) throws IMTPException, ServiceException { //#PJAVA_EXCLUDE_BEGIN diff --git a/src/jade/core/nodeMonitoring/BlockingNodeFailureMonitor.java b/src/jade/core/nodeMonitoring/BlockingNodeFailureMonitor.java index 20f0296..0c75d72 100644 --- a/src/jade/core/nodeMonitoring/BlockingNodeFailureMonitor.java +++ b/src/jade/core/nodeMonitoring/BlockingNodeFailureMonitor.java @@ -42,11 +42,10 @@ public class BlockingNodeFailureMonitor extends NodeFailureMonitor implements Runnable { + private final Logger myLogger = Logger.getMyLogger(getClass().getName()); private boolean nodeExited = false; private boolean stopped = false; - private final Logger myLogger = Logger.getMyLogger(getClass().getName()); - public void start(Node n, NodeEventListener nel) { super.start(n, nel); diff --git a/src/jade/core/nodeMonitoring/UDPMonitorClient.java b/src/jade/core/nodeMonitoring/UDPMonitorClient.java index b48b902..1b85a08 100644 --- a/src/jade/core/nodeMonitoring/UDPMonitorClient.java +++ b/src/jade/core/nodeMonitoring/UDPMonitorClient.java @@ -47,12 +47,10 @@ */ class UDPMonitorClient { - private boolean running = false; - private boolean terminating = false; - private boolean sendTerminationFlag = false; - - //#DOTNET_EXCLUDE_BEGIN - private DatagramChannel channel; + private final String serverHost; + private final int serverPort; + private final Node node; + private final long key; //#DOTNET_EXCLUDE_END @@ -60,16 +58,81 @@ class UDPMonitorClient { private UdpClient channel; private IPEndPoint receivePoint; #DOTNET_INCLUDE_END*/ - - private final String serverHost; - private final int serverPort; + private final Logger logger; + private boolean running = false; + private boolean terminating = false; + private boolean sendTerminationFlag = false; + //#DOTNET_EXCLUDE_BEGIN + private DatagramChannel channel; private ByteBuffer ping; private int pingDelay; - private final Node node; - private final long key; private Thread sender; - private final Logger logger; + /** + * Constructor + * + * @param node Node for which to send ping messages + * @param serverHost hostname of the server + * @param serverPort port on which the server is listening for ping messages + */ + public UDPMonitorClient(Node node, String serverHost, int serverPort, int pingDelay, long key) { + logger = Logger.getMyLogger(this.getClass().getName()); + this.node = node; + this.serverHost = serverHost; + this.serverPort = serverPort; + this.pingDelay = pingDelay; + this.key = key; + } + + public String getServerHost() { + return serverHost; + } + + public long getKey() { + return key; + } + + void setPingDelay(int delay) { + pingDelay = delay; + sender.interrupt(); + } + + /** + * Start sending UDP ping messages to the node failure server + * + * @throws IOException if the + */ + public void start() throws IOException { + //#DOTNET_EXCLUDE_BEGIN + channel = DatagramChannel.open(); + //#DOTNET_EXCLUDE_END + /*#DOTNET_INCLUDE_BEGIN + channel = new UdpClient(); + #DOTNET_INCLUDE_END*/ + running = true; + sender = new Thread(new Sender()); + sender.start(); + + if (logger.isLoggable(Logger.CONFIG)) + logger.log(Logger.CONFIG, "UDP monitoring client started."); + } + + /** + * Stop sending UDP ping messages + */ + public void stop(boolean sendTerminationFlag) { + terminating = true; + this.sendTerminationFlag = sendTerminationFlag; + sender.interrupt(); + + if (logger.isLoggable(Logger.CONFIG)) + logger.log(Logger.CONFIG, "UDP monitoring client stopped."); + + } + + boolean isActive() { + return sender != null && sender.isAlive(); + } /** * Private class which sends ping messages in regular time intervals @@ -101,8 +164,8 @@ public void run() { try { channel.Send(ping.getUByte(), ping.capacity(), serverHost, serverPort); Thread.sleep(pingDelay - 5); - } - catch (Exception e) + } + catch (Exception e) { logger.log(Logger.WARNING,"Error sending UDP ping message to "+serverHost+":"+serverPort+" for node " + node.getName()); } @@ -116,8 +179,8 @@ public void run() { //#DOTNET_EXCLUDE_END /*#DOTNET_INCLUDE_BEGIN channel.Close(); - } - catch (Exception e) + } + catch (Exception e) { #DOTNET_INCLUDE_END*/ if (logger.isLoggable(Logger.FINER)) @@ -145,70 +208,4 @@ private void updatePing() { ping.position(0); } } - - /** - * Constructor - * - * @param node Node for which to send ping messages - * @param serverHost hostname of the server - * @param serverPort port on which the server is listening for ping messages - */ - public UDPMonitorClient(Node node, String serverHost, int serverPort, int pingDelay, long key) { - logger = Logger.getMyLogger(this.getClass().getName()); - this.node = node; - this.serverHost = serverHost; - this.serverPort = serverPort; - this.pingDelay = pingDelay; - this.key = key; - } - - public String getServerHost() { - return serverHost; - } - - public long getKey() { - return key; - } - - void setPingDelay(int delay) { - pingDelay = delay; - sender.interrupt(); - } - - /** - * Start sending UDP ping messages to the node failure server - * - * @throws IOException if the - */ - public void start() throws IOException { - //#DOTNET_EXCLUDE_BEGIN - channel = DatagramChannel.open(); - //#DOTNET_EXCLUDE_END - /*#DOTNET_INCLUDE_BEGIN - channel = new UdpClient(); - #DOTNET_INCLUDE_END*/ - running = true; - sender = new Thread(new Sender()); - sender.start(); - - if (logger.isLoggable(Logger.CONFIG)) - logger.log(Logger.CONFIG, "UDP monitoring client started."); - } - - /** - * Stop sending UDP ping messages - */ - public void stop(boolean sendTerminationFlag) { - terminating = true; - this.sendTerminationFlag = sendTerminationFlag; - sender.interrupt(); - - if (logger.isLoggable(Logger.CONFIG)) - logger.log(Logger.CONFIG, "UDP monitoring client stopped."); - - } - - boolean isActive() { - return sender != null && sender.isAlive(); - } } diff --git a/src/jade/core/nodeMonitoring/UDPMonitorServer.java b/src/jade/core/nodeMonitoring/UDPMonitorServer.java index f2b54f4..d7e1293 100644 --- a/src/jade/core/nodeMonitoring/UDPMonitorServer.java +++ b/src/jade/core/nodeMonitoring/UDPMonitorServer.java @@ -54,200 +54,32 @@ */ class UDPMonitorServer { + private static long currentId = 0; private final Logger logger; - private final UDPNodeMonitoringService myService; - private final String host; private final boolean acceptLocalHostOnly; - private int port; private final int pingDelay; private final int pingDelayLimit; private final int unreachLimit; private final NetworkChecker checker; - - //#DOTNET_EXCLUDE_BEGIN - private DatagramChannel server; - private Selector selector; - //#DOTNET_EXCLUDE_END - private final Hashtable targets = new Hashtable<>(); - private PingHandler pingHandler; - private Timer timer; private final Hashtable deadlines = new Hashtable<>(); - + //#DOTNET_EXCLUDE_END private final int orphanNodePingsCnt; private final int maxTracedUnknownPings; private final Hashtable unknownPingCounters = new Hashtable<>(); + private int port; + //#DOTNET_EXCLUDE_BEGIN + private DatagramChannel server; + private Selector selector; + private PingHandler pingHandler; /*#DOTNET_INCLUDE_BEGIN private Socket server; #DOTNET_INCLUDE_END*/ - - private static long currentId = 0; - - private synchronized static long getUniqueId() { - return currentId++; - } - - /** - * Class to store a deadline for the next ping - * of a targeted node - */ - private class Deadline extends TimerTask { - - private final String nodeID; - - private final long id; - - public Deadline(String nodeID) { - this.nodeID = nodeID; - this.id = getUniqueId(); - } - - public long getID() { - return id; - } - - public void run() { - try { - UDPNodeFailureMonitor mon = targets.get(nodeID); - - // node is still supervised and there are no new deadlines - if (mon != null) { - synchronized (mon) { // Mutual exclusion with pingReceived() - if (mon.getDeadlineID() == id) { - timeout(nodeID, mon); - } else { - // NB: This may happen when we receive a delayed UDP packet while the deadline expiration is being processed (the timeout() - // method is being executed). - // This is not so rare since deadline expiration processing involves checking reachability of the target node and this may - // take a while (especially if the target node is overloaded ... this also justifies the fact that the UDP packet is delayed). - // In such case in fact the UDP packet reception cancels the current Deadline (that has already expired) and then sets a new - // Deadline (overriding the one set within the timeout() method) as soon as we exit this synchronized block - logger.log(Logger.WARNING, "expired Deadline " + id + " for node " + nodeID + " is not the same as monitor Deadline " + mon.getDeadlineID()); - } - } - } - } catch (Throwable t) { - // If we get an uncaught Exception here the Timer thread dies with no log and from now on no more Deadline can be processed - logger.log(Logger.WARNING, "Unexpected error managing UDP Deadline for node " + nodeID, t); - } - } - - public String toString() { - return "Deadline{nodeID=" + nodeID + " id=" + id + "}"; - } - } - - /** - * Class to handles incomming ping messages - */ - private class PingHandler implements Runnable { - - private final byte TERMINATING_INFO = 1; // bit 1 - private boolean interrupted = false; - private final Thread thread; - - public PingHandler(String name) { - thread = new Thread(this, name); - } - - private void handlePing() throws IOException { - // allocate maximum size of one UDP packet - ByteBuffer datagramBuffer = ByteBuffer.allocate(1 << 16); - - //#DOTNET_EXCLUDE_BEGIN - SocketAddress address = server.receive(datagramBuffer); - //#DOTNET_EXCLUDE_END - - /*#DOTNET_INCLUDE_BEGIN - ubyte[] recData = new ubyte[datagramBuffer.getUByte().length]; - - if ( server != null) - { - try - { - if (server.get_Available() <= 0) - return; - } - catch (System.ObjectDisposedException ode) - { - return; - } - } - else - return; - - try - { - server.Receive(recData, 0, server.get_Available(), SocketFlags.None); - } - catch (SocketException se) - { - int socketError = se.get_ErrorCode(); - return; - } - IPEndPoint IPendPt = (IPEndPoint) server.get_LocalEndPoint(); - IPAddress address = IPendPt.get_Address(); - datagramBuffer.copyUByte(recData); - #DOTNET_INCLUDE_END*/ - - datagramBuffer.position(0); - - if (address != null) { - - int nodeIDLength = datagramBuffer.getInt(); - - // get node ID - byte[] bb = new byte[nodeIDLength]; - datagramBuffer.get(bb, 0, nodeIDLength); - String nodeID = new String(bb); - - // analyse info byte - byte info = datagramBuffer.get(); - boolean isTerminating = (info & TERMINATING_INFO) != 0; - - pingReceived(nodeID, isTerminating); - } - } - - public void run() { - while (!interrupted) { // endless loop - try { - //#DOTNET_EXCLUDE_BEGIN - selector.select(); - - Set keys = selector.selectedKeys(); - interrupted = keys.size() == 0; - Iterator i = keys.iterator(); - - while (i.hasNext()) { - SelectionKey key = i.next(); - i.remove(); - if (key.isValid() && key.isReadable()) { - //#DOTNET_EXCLUDE_END - handlePing(); - //#DOTNET_EXCLUDE_BEGIN - } - } - //#DOTNET_EXCLUDE_END - } catch (Exception e) // .net requires I catch Exception instead of IOException - { - logger.log(Logger.SEVERE, "UDP Connection error ", e); - } - } // for - } - - public void start() { - thread.start(); - } - - public void stop() { - interrupted = true; - } - } + private Timer timer; /** * Constructs a new UDPMonitorServer object @@ -279,6 +111,10 @@ public void stop() { } } + private synchronized static long getUniqueId() { + return currentId++; + } + String getHost() { return host; } @@ -474,20 +310,6 @@ private void handleUnknownPing(String nodeID) { } } - - private class Counter { - private int value = 0; - - private void increment() { - value++; - } - - private int getValue() { - return value; - } - } - - /** * This method is invoked by a TimeoutHandler at a timeout */ @@ -539,4 +361,174 @@ private void addDeadline(String nodeID, int delay) { } } } + + /** + * Class to store a deadline for the next ping + * of a targeted node + */ + private class Deadline extends TimerTask { + + private final String nodeID; + + private final long id; + + public Deadline(String nodeID) { + this.nodeID = nodeID; + this.id = getUniqueId(); + } + + public long getID() { + return id; + } + + public void run() { + try { + UDPNodeFailureMonitor mon = targets.get(nodeID); + + // node is still supervised and there are no new deadlines + if (mon != null) { + synchronized (mon) { // Mutual exclusion with pingReceived() + if (mon.getDeadlineID() == id) { + timeout(nodeID, mon); + } else { + // NB: This may happen when we receive a delayed UDP packet while the deadline expiration is being processed (the timeout() + // method is being executed). + // This is not so rare since deadline expiration processing involves checking reachability of the target node and this may + // take a while (especially if the target node is overloaded ... this also justifies the fact that the UDP packet is delayed). + // In such case in fact the UDP packet reception cancels the current Deadline (that has already expired) and then sets a new + // Deadline (overriding the one set within the timeout() method) as soon as we exit this synchronized block + logger.log(Logger.WARNING, "expired Deadline " + id + " for node " + nodeID + " is not the same as monitor Deadline " + mon.getDeadlineID()); + } + } + } + } catch (Throwable t) { + // If we get an uncaught Exception here the Timer thread dies with no log and from now on no more Deadline can be processed + logger.log(Logger.WARNING, "Unexpected error managing UDP Deadline for node " + nodeID, t); + } + } + + public String toString() { + return "Deadline{nodeID=" + nodeID + " id=" + id + "}"; + } + } + + /** + * Class to handles incomming ping messages + */ + private class PingHandler implements Runnable { + + private final byte TERMINATING_INFO = 1; // bit 1 + private final Thread thread; + private boolean interrupted = false; + + public PingHandler(String name) { + thread = new Thread(this, name); + } + + private void handlePing() throws IOException { + // allocate maximum size of one UDP packet + ByteBuffer datagramBuffer = ByteBuffer.allocate(1 << 16); + + //#DOTNET_EXCLUDE_BEGIN + SocketAddress address = server.receive(datagramBuffer); + //#DOTNET_EXCLUDE_END + + /*#DOTNET_INCLUDE_BEGIN + ubyte[] recData = new ubyte[datagramBuffer.getUByte().length]; + + if ( server != null) + { + try + { + if (server.get_Available() <= 0) + return; + } + catch (System.ObjectDisposedException ode) + { + return; + } + } + else + return; + + try + { + server.Receive(recData, 0, server.get_Available(), SocketFlags.None); + } + catch (SocketException se) + { + int socketError = se.get_ErrorCode(); + return; + } + IPEndPoint IPendPt = (IPEndPoint) server.get_LocalEndPoint(); + IPAddress address = IPendPt.get_Address(); + datagramBuffer.copyUByte(recData); + #DOTNET_INCLUDE_END*/ + + datagramBuffer.position(0); + + if (address != null) { + + int nodeIDLength = datagramBuffer.getInt(); + + // get node ID + byte[] bb = new byte[nodeIDLength]; + datagramBuffer.get(bb, 0, nodeIDLength); + String nodeID = new String(bb); + + // analyse info byte + byte info = datagramBuffer.get(); + boolean isTerminating = (info & TERMINATING_INFO) != 0; + + pingReceived(nodeID, isTerminating); + } + } + + public void run() { + while (!interrupted) { // endless loop + try { + //#DOTNET_EXCLUDE_BEGIN + selector.select(); + + Set keys = selector.selectedKeys(); + interrupted = keys.size() == 0; + Iterator i = keys.iterator(); + + while (i.hasNext()) { + SelectionKey key = i.next(); + i.remove(); + if (key.isValid() && key.isReadable()) { + //#DOTNET_EXCLUDE_END + handlePing(); + //#DOTNET_EXCLUDE_BEGIN + } + } + //#DOTNET_EXCLUDE_END + } catch (Exception e) // .net requires I catch Exception instead of IOException + { + logger.log(Logger.SEVERE, "UDP Connection error ", e); + } + } // for + } + + public void start() { + thread.start(); + } + + public void stop() { + interrupted = true; + } + } + + private class Counter { + private int value = 0; + + private void increment() { + value++; + } + + private int getValue() { + return value; + } + } } diff --git a/src/jade/core/nodeMonitoring/UDPNodeFailureMonitor.java b/src/jade/core/nodeMonitoring/UDPNodeFailureMonitor.java index 3a7c4b6..dc1b8f4 100644 --- a/src/jade/core/nodeMonitoring/UDPNodeFailureMonitor.java +++ b/src/jade/core/nodeMonitoring/UDPNodeFailureMonitor.java @@ -58,15 +58,13 @@ class UDPNodeFailureMonitor extends NodeFailureMonitor { * monitored anymore. */ public static final int STATE_FINAL = 2; - - + private final UDPMonitorServer server; + private final UDPNodeMonitoringService service; + private final Logger logger = Logger.getMyLogger(this.getClass().getName()); private long deadlineId = -1; private long lastPing = -1; private int state = -1; private long key = 0; - private final UDPMonitorServer server; - private final UDPNodeMonitoringService service; - private final Logger logger = Logger.getMyLogger(this.getClass().getName()); /** @@ -118,6 +116,17 @@ public long getLastPing() { return lastPing; } + /** + * Sets the time when the last ping message has been received + * from the targeted node + * + * @param time the difference, measured in milliseconds, + * between the current time and midnight, January 1, 1970 UTC. + */ + void setLastPing(long time) { + lastPing = time; + } + public long getDeadlineID() { return deadlineId; } @@ -164,17 +173,6 @@ void setState(int newState) { state = newState; } - /** - * Sets the time when the last ping message has been received - * from the targeted node - * - * @param time the difference, measured in milliseconds, - * between the current time and midnight, January 1, 1970 UTC. - */ - void setLastPing(long time) { - lastPing = time; - } - public String requireService() { return UDPNodeMonitoringService.NAME; } diff --git a/src/jade/core/nodeMonitoring/UDPNodeMonitoringProxy.java b/src/jade/core/nodeMonitoring/UDPNodeMonitoringProxy.java index 63ae893..37f7273 100644 --- a/src/jade/core/nodeMonitoring/UDPNodeMonitoringProxy.java +++ b/src/jade/core/nodeMonitoring/UDPNodeMonitoringProxy.java @@ -19,7 +19,7 @@ public void activateUDP(String label, String host, int port, int pingDelay, long Node n = getNode(); Object result = n.accept(cmd); - if ((result != null) && (result instanceof Throwable)) { + if ((result instanceof Throwable)) { if (result instanceof IMTPException) { throw (IMTPException) result; } else { diff --git a/src/jade/core/nodeMonitoring/UDPNodeMonitoringService.java b/src/jade/core/nodeMonitoring/UDPNodeMonitoringService.java index b95b822..63099ed 100644 --- a/src/jade/core/nodeMonitoring/UDPNodeMonitoringService.java +++ b/src/jade/core/nodeMonitoring/UDPNodeMonitoringService.java @@ -33,13 +33,32 @@ * UDP based implementation of the NodeMonitoringService. */ public class UDPNodeMonitoringService extends NodeMonitoringService { - private static final String PREFIX = "jade_core_nodeMonitoring_UDPNodeMonitoringService_"; - /** * The name of this service */ public static final String NAME = "jade.core.nodeMonitoring.UDPNodeMonitoring"; - + /** + * Default port on which the server is waiting for ping messages + */ + public static final int DEFAULT_PORT = 28000; + /** + * Default time between two outgoing pings + */ + public static final int DEFAULT_PING_DELAY = 1000; + /** + * Default maximum time the server waits for a ping + */ + public static final int DEFAULT_PING_DELAY_LIMIT = 3000; + /** + * Default maximum time a node can stay unreachable + */ + public static final int DEFAULT_UNREACHABLE_LIMIT = 10000; + /** + * Vertical command issued on the Main Container + * when a given number of ping packets are received from an unknown node + */ + public static final String ORPHAN_NODE = "Orphan-Node"; + private static final String PREFIX = "jade_core_nodeMonitoring_UDPNodeMonitoringService_"; /** * This constant is the name of the property whose value contains * the hostname where the Main Container is listening for UDP pings. @@ -47,21 +66,18 @@ public class UDPNodeMonitoringService extends NodeMonitoringService { * If this is null too the default network name is used. */ public static final String HOST = PREFIX + "host"; - /** * This constant is the name of the property whose value contains * a boolean indication that specifies whether or not UDP pings must be accepted * on the indicated local-host only (default = false). */ public static final String ACCEPT_LOCAL_HOST_ONLY = PREFIX + "acceptlocalhostonly"; - /** * This constant is the name of the property whose value contains an * integer representing the port number where the Main Container is * listening for UDP pings. */ public static final String PORT = PREFIX + "port"; - /** * This constant is the name of the property whose value contains an * integer representing the time interval (in milliseconds) in which a peripheral @@ -69,7 +85,6 @@ public class UDPNodeMonitoringService extends NodeMonitoringService { * This property is only meaningful on a peripheral container. */ public static final String PING_DELAY = PREFIX + "pingdelay"; - /** * This constant is the name of the property whose value contains an * integer representing the maximum time (in milliseconds) the main container @@ -78,7 +93,6 @@ public class UDPNodeMonitoringService extends NodeMonitoringService { * This property is only meaningful on a main container. */ public static final String PING_DELAY_LIMIT = PREFIX + "pingdelaylimit"; - /** * This constant is the name of the property whose value contains an * integer representing the maximum time a node can stay unreachable after it gets removed @@ -86,7 +100,6 @@ public class UDPNodeMonitoringService extends NodeMonitoringService { * This property is only meaningful on a main container. */ public static final String UNREACHABLE_LIMIT = PREFIX + "unreachablelimit"; - /** * This constant is the name of the property whose value contains an * integer representing the number of UDP ping packets that must be received from an un-monitored node @@ -95,7 +108,6 @@ public class UDPNodeMonitoringService extends NodeMonitoringService { * This property is only meaningful on a main container. */ public static final String ORPHAN_NODE_PINGS_CNT = PREFIX + "orphannodepingscnt"; - /** * This constant is the name of the property whose value contains an * integer representing the maximum number of UDP ping packets received from an un-monitored node that are traced. @@ -104,7 +116,6 @@ public class UDPNodeMonitoringService extends NodeMonitoringService { * This property is only meaningful on a main container. */ public static final String MAX_TRACED_UNKNOWN_PINGS = PREFIX + "maxtracedunknownpings"; - /** * This constants is the name of the property whose value contains the fully qualified * class name of a concrete implementation of the NetworkChecker interface. @@ -118,48 +129,34 @@ public class UDPNodeMonitoringService extends NodeMonitoringService { * @see NetworkChecker */ public static final String NETWORK_CHECKER = PREFIX + "networkchecker"; - - /** - * Default port on which the server is waiting for ping messages - */ - public static final int DEFAULT_PORT = 28000; - - /** - * Default time between two outgoing pings - */ - public static final int DEFAULT_PING_DELAY = 1000; - - /** - * Default maximum time the server waits for a ping - */ - public static final int DEFAULT_PING_DELAY_LIMIT = 3000; - - /** - * Default maximum time a node can stay unreachable - */ - public static final int DEFAULT_UNREACHABLE_LIMIT = 10000; - - /** - * Vertical command issued on the Main Container - * when a given number of ping packets are received from an unknown node - */ - public static final String ORPHAN_NODE = "Orphan-Node"; - private static final String[] OWNED_COMMANDS = new String[]{ NODE_UNREACHABLE, NODE_REACHABLE, ORPHAN_NODE }; - - - private UDPMonitorServer myServer; private final Hashtable myClients = new Hashtable<>(2); - + private final ServiceComponent localSlice = new ServiceComponent(); + private final Filter incFilter = new UDPMonitorIncomingFilter(); + private UDPMonitorServer myServer; private ServiceManager myServiceManager; private MainContainer mainContainer; - private final ServiceComponent localSlice = new ServiceComponent(); - private final Filter incFilter = new UDPMonitorIncomingFilter(); + /** + * Extracts an integer value from a given profile. If the value + * is less than zero it returns the specified default value + * + * @param p profile + * @param paramName name of the parameter in the profile + * @param defaultValue default value + */ + private static int getPosIntValue(Profile p, String paramName, int defaultValue) { + int value = Integer.parseInt(p.getParameter(paramName, "-1")); + if (value >= 0) { + return value; + } else { + return defaultValue; + } + } public String getName() { return NAME; @@ -267,23 +264,6 @@ protected void setClientsPingDelay(int delay) { } } - /** - * Extracts an integer value from a given profile. If the value - * is less than zero it returns the specified default value - * - * @param p profile - * @param paramName name of the parameter in the profile - * @param defaultValue default value - */ - private static int getPosIntValue(Profile p, String paramName, int defaultValue) { - int value = Integer.parseInt(p.getParameter(paramName, "-1")); - if (value >= 0) { - return value; - } else { - return defaultValue; - } - } - void activateUDP(Node n, long key) { if (myServer != null) { myLogger.log(Logger.CONFIG, "Requesting UDP activation to node " + n.getName()); diff --git a/src/jade/core/replication/AddressNotificationProxy.java b/src/jade/core/replication/AddressNotificationProxy.java index d84d53b..391ca25 100644 --- a/src/jade/core/replication/AddressNotificationProxy.java +++ b/src/jade/core/replication/AddressNotificationProxy.java @@ -41,7 +41,7 @@ public void addServiceManagerAddress(String addr) throws IMTPException { Node n = getNode(); Object result = n.accept(cmd); - if ((result != null) && (result instanceof Throwable)) { + if ((result instanceof Throwable)) { if (result instanceof IMTPException) { throw (IMTPException) result; } else { @@ -82,7 +82,7 @@ public String getServiceManagerAddress() throws IMTPException { Node n = getNode(); Object result = n.accept(cmd); - if ((result != null) && (result instanceof Throwable)) { + if ((result instanceof Throwable)) { if (result instanceof IMTPException) { throw (IMTPException) result; } else { diff --git a/src/jade/core/replication/AddressNotificationService.java b/src/jade/core/replication/AddressNotificationService.java index 870ebc6..1990b87 100644 --- a/src/jade/core/replication/AddressNotificationService.java +++ b/src/jade/core/replication/AddressNotificationService.java @@ -38,6 +38,12 @@ */ public class AddressNotificationService extends BaseService { + // The command sink, source side + private final IncomingFilter incomingFilter = new IncomingFilter(); + private AgentContainer myContainer; + private ServiceComponent localSlice; + private ServiceManager myServiceManager; + public void init(AgentContainer ac, Profile p) throws ProfileException { super.init(ac, p); @@ -98,6 +104,23 @@ public void boot(Profile p) throws ServiceException { } } + private void broadcastToSlices(HorizontalCommand cmd) throws IMTPException, ServiceException { + + Object[] slices = getAllSlices(); + for (Object o : slices) { + AddressNotificationSlice slice = (AddressNotificationSlice) o; + if (!slice.getNode().hasPlatformManager()) { + slice.serve(cmd); + } + } + + } + + private void addAddress(String addr) throws IMTPException { + if (myLogger.isLoggable(Logger.CONFIG)) + myLogger.log(Logger.CONFIG, "Adding PlatformManager address " + addr); + myServiceManager.addAddress(addr); + } private class IncomingFilter extends Filter { @@ -129,7 +152,6 @@ public void handleAddressAdded(VerticalCommand cmd) throws IMTPException, Servic } // End of IncomingFilter class - private class ServiceComponent implements Slice { public ServiceComponent(Profile p) { @@ -192,33 +214,4 @@ private String getServiceManagerAddress() throws IMTPException { } // End of ServiceComponent class - private AgentContainer myContainer; - - private ServiceComponent localSlice; - - // The command sink, source side - private final IncomingFilter incomingFilter = new IncomingFilter(); - - private ServiceManager myServiceManager; - - private void broadcastToSlices(HorizontalCommand cmd) throws IMTPException, ServiceException { - - Object[] slices = getAllSlices(); - for (Object o : slices) { - AddressNotificationSlice slice = (AddressNotificationSlice) o; - if (!slice.getNode().hasPlatformManager()) { - slice.serve(cmd); - } - } - - } - - - private void addAddress(String addr) throws IMTPException { - if (myLogger.isLoggable(Logger.CONFIG)) - myLogger.log(Logger.CONFIG, "Adding PlatformManager address " + addr); - myServiceManager.addAddress(addr); - } - - } diff --git a/src/jade/core/replication/AgentReplicationHandle.java b/src/jade/core/replication/AgentReplicationHandle.java index b17fa10..565e14a 100644 --- a/src/jade/core/replication/AgentReplicationHandle.java +++ b/src/jade/core/replication/AgentReplicationHandle.java @@ -34,9 +34,8 @@ * AgentReplicationService. */ public class AgentReplicationHandle { - static ThreadLocal replicatedCalls = new ThreadLocal<>(); - private static final Logger myLogger = Logger.getJADELogger(AgentReplicationHandle.class.getName()); + static ThreadLocal replicatedCalls = new ThreadLocal<>(); /** * Utility method to be called at the beginning of each replicated method as diff --git a/src/jade/core/replication/AgentReplicationHelper.java b/src/jade/core/replication/AgentReplicationHelper.java index 4aeadd5..b64e490 100644 --- a/src/jade/core/replication/AgentReplicationHelper.java +++ b/src/jade/core/replication/AgentReplicationHelper.java @@ -65,35 +65,6 @@ public interface AgentReplicationHelper extends ServiceHelper { */ String VIRTUAL_RECEIVER = "JADE-virtual-receiver"; - /** - * The interface to be implemented by a replicated agent for the master replica - * to be notified about replica addition/removal and master replica changes. - * If a replicated agent does not implement this interface such events will not be - * notified. - */ - interface Listener { - /** - * Notify the master replica that a new replica has just been added - */ - void replicaAdded(AID replicaAid, Location where); - - /** - * Notify the master replica that a replica has just been removed - */ - void replicaRemoved(AID replicaAid, Location where); - - /** - * Notify the master replica that a replica failed to start - */ - void replicaCreationFailed(AID replicaAid, Location where); - - /** - * Notify a replica that it became the new master replica - */ - void becomeMaster(); - } - - /** * Define a virtual agent and sets the agent that invokes this method as * its master replica. @@ -155,4 +126,32 @@ interface Listener { * directly. AgentReplicationHanlde.replicate() should be used instead. */ void invokeReplicatedMethod(String methodName, Object[] arguments); + + /** + * The interface to be implemented by a replicated agent for the master replica + * to be notified about replica addition/removal and master replica changes. + * If a replicated agent does not implement this interface such events will not be + * notified. + */ + interface Listener { + /** + * Notify the master replica that a new replica has just been added + */ + void replicaAdded(AID replicaAid, Location where); + + /** + * Notify the master replica that a replica has just been removed + */ + void replicaRemoved(AID replicaAid, Location where); + + /** + * Notify the master replica that a replica failed to start + */ + void replicaCreationFailed(AID replicaAid, Location where); + + /** + * Notify a replica that it became the new master replica + */ + void becomeMaster(); + } } diff --git a/src/jade/core/replication/AgentReplicationProxy.java b/src/jade/core/replication/AgentReplicationProxy.java index bfebfb6..3688c51 100644 --- a/src/jade/core/replication/AgentReplicationProxy.java +++ b/src/jade/core/replication/AgentReplicationProxy.java @@ -37,7 +37,7 @@ public void invokeAgentMethod(AID aid, String methodName, Object[] arguments) th Node n = getNode(); Object result = n.accept(cmd); - if ((result != null) && (result instanceof Throwable)) { + if ((result instanceof Throwable)) { if (result instanceof NotFoundException) { throw (NotFoundException) result; } else if (result instanceof ServiceException) { @@ -57,7 +57,7 @@ public ContainerID getAgentLocation(AID aid) throws IMTPException, NotFoundExcep try { Node n = getNode(); Object result = n.accept(cmd); - if ((result != null) && (result instanceof Throwable)) { + if ((result instanceof Throwable)) { if (result instanceof NotFoundException) { throw (NotFoundException) result; } else if (result instanceof IMTPException) { @@ -80,7 +80,7 @@ public void replicaCreationRequested(AID virtualAid, AID replicaAid) throws IMTP try { Node n = getNode(); Object result = n.accept(cmd); - if ((result != null) && (result instanceof Throwable)) { + if ((result instanceof Throwable)) { if (result instanceof IMTPException) { throw (IMTPException) result; } else { @@ -102,7 +102,7 @@ public void synchReplication(GlobalReplicationInfo info) throws IMTPException { try { Node n = getNode(); Object result = n.accept(cmd); - if ((result != null) && (result instanceof Throwable)) { + if ((result instanceof Throwable)) { if (result instanceof IMTPException) { throw (IMTPException) result; } else { @@ -121,7 +121,7 @@ public void notifyBecomeMaster(AID masterAid) throws IMTPException { try { Node n = getNode(); Object result = n.accept(cmd); - if ((result != null) && (result instanceof Throwable)) { + if ((result instanceof Throwable)) { if (result instanceof IMTPException) { throw (IMTPException) result; } else { @@ -142,7 +142,7 @@ public void notifyReplicaRemoved(AID masterAid, AID removedReplica, Location whe try { Node n = getNode(); Object result = n.accept(cmd); - if ((result != null) && (result instanceof Throwable)) { + if ((result instanceof Throwable)) { if (result instanceof IMTPException) { throw (IMTPException) result; } else { diff --git a/src/jade/core/replication/AgentReplicationService.java b/src/jade/core/replication/AgentReplicationService.java index 716c476..f65abdc 100644 --- a/src/jade/core/replication/AgentReplicationService.java +++ b/src/jade/core/replication/AgentReplicationService.java @@ -44,23 +44,18 @@ public class AgentReplicationService extends BaseService { public static final String NAME = AgentReplicationHelper.SERVICE_NAME; - - private AgentContainer myContainer; - private MessagingService theMessagingService; - - private Filter outFilter; - private Filter incFilter; - private ServiceComponent localSlice; - // Map a virtual agent to the set of global information associated to it private final Map globalReplications = new Hashtable<>(); // Map a replica agent to the related virtual agent private final Map replicaToVirtualMap = new Hashtable<>(); // Map a master replica agent to the pending replica creation requests private final Map> pendingReplicaCreationRequests = new Hashtable<>(); - private final Map cachedAgentMethods = new HashMap<>(); - + private AgentContainer myContainer; + private MessagingService theMessagingService; + private Filter outFilter; + private Filter incFilter; + private ServiceComponent localSlice; public String getName() { return NAME; @@ -130,866 +125,875 @@ public Slice getLocalSlice() { return localSlice; } - - /** - * Inner class AgentReplicationHelperImpl - */ - private class AgentReplicationHelperImpl implements AgentReplicationHelper { - private AID myAid; - private AID virtualAid; - private final List peerReplicas = new ArrayList<>(); - private ReplicaInfo[] peerReplicasArray = new ReplicaInfo[0]; - - public void init(Agent a) { - myAid = a.getAID(); - - // If the agent retrieving this helper is already a replica, initialize virtualAid - // and peerReplicas from the global replication information - virtualAid = replicaToVirtualMap.get(myAid); - if (virtualAid != null) { - GlobalReplicationInfo info = globalReplications.get(virtualAid); - if (info != null) { - AID[] currentReplicas = info.getAllReplicas(); - for (AID replica : currentReplicas) { - // Exclude the agent itself from peer replicas - if (!replica.equals(myAid)) { - try { - Location location = getLocation(replica); - addPeerReplica(new ReplicaInfo(replica, location)); - } catch (NotFoundException nfe) { - myLogger.log(Logger.WARNING, "Replica " + replica.getLocalName() + " not found. Likely it died in the meanwhile"); - } catch (Exception e) { - myLogger.log(Logger.SEVERE, "Error retrieving location for agent " + replica.getLocalName(), e); - } - } - } - } else { - myLogger.log(Logger.SEVERE, "Virtual agent " + virtualAid.getLocalName() + " for replica agent " + myAid.getLocalName() + " not found"); + private void localNotifyReplicaAddedToMaster(AID masterAid, ReplicaInfo r) { + // Note that this method is invoked in the master replica container --> + // Unlike other notifyXXX() methods, only the "local" version is needed + Agent agent = myContainer.acquireLocalAgent(masterAid); + if (agent != null) { + myContainer.releaseLocalAgent(masterAid); + try { + if (agent instanceof AgentReplicationHelper.Listener) { + ((AgentReplicationHelper.Listener) agent).replicaAdded(r.replicaAid, r.where); } + } catch (Exception e) { + myLogger.log(Logger.WARNING, "Unexpected exception notifying master agent (replicaAdded())", e); } } + } - public AID makeVirtual(String virtualName, int replicationMode) throws ServiceException { - if (virtualAid == null) { - virtualAid = new AID(AID.createGUID(virtualName, myContainer.getPlatformID()), AID.ISGUID); - - // Reserve the virtualName by registering the virtual AID to the AMS - AMSAgentDescription amsd = new AMSAgentDescription(); - amsd.setName(virtualAid); - amsd.setState(AMSAgentDescription.ACTIVE); - Agent agent = myContainer.acquireLocalAgent(myAid); - // Immediately release the agent: AMSService.register() requires that the agent receives the AMS reply - myContainer.releaseLocalAgent(myAid); - if (agent != null) { - try { - AMSService.register(agent, amsd); - } catch (Exception e) { - throw new ServiceException("Error registering virtual name " + virtualName, e); - } + private void notifyReplicaRemovedToMaster(AID masterAid, AID removedReplica, Location where) { + try { + // This is always invoked on the Main Container + if (where == null) { + try { + where = getAgentLocation(removedReplica); + } catch (NotFoundException nfe) { + // If this is triggered by a container fault, the GADT has already been cleaned. + // We are not able to fill the removed replica location. } - - broadcastNewVirtualAgent(virtualAid, myAid, replicationMode); - return virtualAid; - } else { - throw new ServiceException("Agent " + myAid.getLocalName() + " has already been made virtual"); } + Location masterLocation = getAgentLocation(masterAid); + AgentReplicationSlice slice = (AgentReplicationSlice) getFreshSlice(masterLocation.getName()); + slice.notifyReplicaRemoved(masterAid, removedReplica, where); + } catch (Exception e) { + // Should never happen as this masterAid has just been selected (and checked) as new master + myLogger.log(Logger.WARNING, "Error notifying master replica " + masterAid.getLocalName() + " that replica " + removedReplica.getLocalName() + " has been removed", e); } + } - public void createReplica(String replicaName, Location where) throws ServiceException { - if (virtualAid != null) { - if (isMaster()) { - // The agent this helper belongs to is virtualized and is the master replica - // Go on with the replica creation process - AgentReplicationSlice slice = (AgentReplicationSlice) getSlice(where.getName()); - if (slice != null) { - // Notify the destination slice that a replica for our virtual agent is - // going to be created there (see comment in AgentReplicationSlice) - AID replicaAid = new AID(AID.createGUID(replicaName, myContainer.getPlatformID()), AID.ISGUID); - try { - slice.replicaCreationRequested(virtualAid, replicaAid); - } catch (IMTPException imtpe) { - // Get a fresh slice and retry - slice = (AgentReplicationSlice) getFreshSlice(where.getName()); - try { - slice.replicaCreationRequested(virtualAid, replicaAid); - } catch (IMTPException imtpe1) { - throw new ServiceException("IMTP error contacting destination slice", imtpe1); - } - } + private void localNotifyReplicaRemovedToMaster(AID masterAid, AID removedReplica, Location where) { + Agent agent = myContainer.acquireLocalAgent(masterAid); + if (agent != null) { + myContainer.releaseLocalAgent(masterAid); + try { + if (agent instanceof AgentReplicationHelper.Listener) { + ((AgentReplicationHelper.Listener) agent).replicaRemoved(removedReplica, where); + } + } catch (Exception e) { + myLogger.log(Logger.WARNING, "Unexpected exception notifying master agent (becomeMaster())", e); + } + } + } - // Enqueue the replica creation request - List rr = pendingReplicaCreationRequests.get(myAid); - if (rr == null) { - rr = new ArrayList<>(); - pendingReplicaCreationRequests.put(myAid, rr); - } - rr.add(new ReplicaInfo(replicaAid, where)); + private void notifyBecomeMasterToMaster(AID masterAid) { + try { + // This is always invoked on the Main Container + Location masterLocation = getAgentLocation(masterAid); + AgentReplicationSlice slice = (AgentReplicationSlice) getFreshSlice(masterLocation.getName()); + slice.notifyBecomeMaster(masterAid); + } catch (Exception e) { + // Should never happen as this masterAid has just been selected (and checked) as new master + myLogger.log(Logger.WARNING, "Error notifying new master replica " + masterAid.getLocalName() + " it just took the leadership", e); + } + } - // If there are no other ongoing replica creation processes --> directly clone the (master) agent. - if (rr.size() == 1) { - cloneReplica(myAid, replicaName, where); - } - } else { - throw new ServiceException("AgentReplicationService not installed in the destination container " + where.getName() + " for replica " + replicaName); - } - } else { - throw new ServiceException("Agent " + myAid.getLocalName() + " is not the master replica"); + private void localNotifyBecomeMasterToMaster(AID masterAid) { + Agent agent = myContainer.acquireLocalAgent(masterAid); + if (agent != null) { + myContainer.releaseLocalAgent(masterAid); + try { + if (agent instanceof AgentReplicationHelper.Listener) { + ((AgentReplicationHelper.Listener) agent).becomeMaster(); } - } else { - throw new ServiceException("Agent " + myAid.getLocalName() + " has not been made virtual"); + } catch (Exception e) { + myLogger.log(Logger.WARNING, "Unexpected exception notifying master agent (becomeMaster())", e); } } + } - public AID getVirtualAid() { - return virtualAid; + private Location getLocation(AID aid) throws Exception { + if (myContainer.isLocalAgent(aid)) { + return myContainer.getID(); } - public AID getMasterAid() { - if (virtualAid != null) { - GlobalReplicationInfo info = globalReplications.get(virtualAid); - return info.getMaster(); - } - return null; + // Aid lives somewhere else --> ask the slice on the Main Container + AgentReplicationSlice mainSlice = (AgentReplicationSlice) getSlice(MAIN_SLICE); + try { + return mainSlice.getAgentLocation(aid); + } catch (IMTPException imtpe) { + // Get a fresh slice and retry + mainSlice = (AgentReplicationSlice) getFreshSlice(MAIN_SLICE); + return mainSlice.getAgentLocation(aid); } + } - public boolean isMaster() { - if (virtualAid != null) { - GlobalReplicationInfo info = globalReplications.get(virtualAid); - return myAid.equals(info.getMaster()); + private AID getVirtualAid(AID aid) { + Agent agent = myContainer.acquireLocalAgent(aid); + if (agent != null) { + try { + AgentReplicationHelper helper = (AgentReplicationHelper) agent.getHelper(NAME); + return helper.getVirtualAid(); + } catch (ServiceException se) { + // Should never happen since the AgentReplicationService is certainly there + myLogger.log(Logger.WARNING, "Unexpected error retrieving AgentReplicationHelper for agent " + aid.getName()); + return null; + } finally { + myContainer.releaseLocalAgent(aid); } - return false; + } else { + return null; } + } - public Map getReplicas() { - // FIXME: To be implemented - return null; + private void broadcastNewVirtualAgent(AID virtualAid, AID masterAid, int replicationMode) { + myLogger.log(Logger.CONFIG, "Broadcasting new virtual agent " + virtualAid.getLocalName()); + GenericCommand cmd = new GenericCommand(AgentReplicationSlice.H_NEWVIRTUALAGENT, NAME, null); + cmd.addParam(virtualAid); + cmd.addParam(masterAid); + cmd.addParam(replicationMode); + + try { + broadcast(cmd, true); // Include myself + } catch (Exception e) { + myLogger.log(Logger.SEVERE, "Error broadcasting new virtual agent " + virtualAid.getLocalName(), e); } + } - public void invokeReplicatedMethod(String methodName, Object[] arguments) { - ReplicaInfo[] tmp = peerReplicasArray; - myLogger.log(Logger.FINE, "Invoking method " + methodName + " on " + tmp.length + " replica(s)"); - for (ReplicaInfo r : tmp) { - try { - if (!invokeOnReplica(methodName, arguments, r)) { - // This replica agent does not exist anymore --> remove it - removePeerReplica(r); - GlobalReplicationInfo info = globalReplications.get(virtualAid); - if (info != null) { - info.removeReplica(r.replicaAid); - } - } - } catch (Exception e) { - myLogger.log(Logger.SEVERE, "Error propagating call to method " + methodName + " to agent " + r.replicaAid.getLocalName(), e); - } + private void broadcastAddReplica(AID masterAid, ReplicaInfo r) { + AID virtualAid = getVirtualAid(masterAid); + if (virtualAid != null) { + myLogger.log(Logger.CONFIG, "Broadcasting new replica " + r.replicaAid.getLocalName() + " of virtual agent " + virtualAid.getLocalName()); + GenericCommand cmd = new GenericCommand(AgentReplicationSlice.H_ADDREPLICA, NAME, null); + cmd.addParam(virtualAid); + cmd.addParam(r.replicaAid); + cmd.addParam(r.where); + + try { + broadcast(cmd, true); // Include myself + } catch (Exception e) { + myLogger.log(Logger.SEVERE, "Error broadcasting new replica " + r.replicaAid.getLocalName() + " of virtual agent " + virtualAid.getLocalName(), e); } + } else { + myLogger.log(Logger.WARNING, "Cannot find virtual agent for master replica " + masterAid.getLocalName()); } + } - private boolean invokeOnReplica(String methodName, Object[] arguments, ReplicaInfo r) throws Exception { - myLogger.log(Logger.FINER, "Invoking method " + methodName + " on replica " + r.replicaAid.getLocalName()); - // If we get an Exception, refresh the location of the replica (it - // may have moved or be recreated somewhere else) and retry until OK. - // If not found in Main Container --> Ignore: replica has terminated in the meanwhile - do { - AgentReplicationSlice slice = (AgentReplicationSlice) getSlice(r.where.getName()); - if (slice != null) { - try { - try { - slice.invokeAgentMethod(r.replicaAid, methodName, arguments); - // Done: Jump out - break; - } catch (IMTPException imtpe) { - // Try to get a newer slice and repeat... - slice = (AgentReplicationSlice) getFreshSlice(r.where.getName()); - slice.invokeAgentMethod(r.replicaAid, methodName, arguments); - // Done: Jump out - break; - } - } catch (NotFoundException nfe) { - // The replica agent was not found on the container where it was supposed to be - // Possibly it has moved elsewhere --> Check with the Main Container - } - } - - // Not done: Update the replica location and retry - try { - myLogger.log(Logger.CONFIG, "Updating location of replica " + r.replicaAid.getLocalName()); - // The replica agent is alive: update its location and retry - r.where = getLocation(r.replicaAid); - } catch (NotFoundException nfe1) { - // The replica agent does not exist anymore in the whole platform --> silently remove it - return false; - } - } while (true); + private void broadcastMasterReplicaChanged(AID virtualAid, AID newMasterAid) { + myLogger.log(Logger.CONFIG, "Broadcasting master replica changed for virtual agent " + virtualAid.getLocalName() + ". New master replica = " + newMasterAid.getLocalName()); + GenericCommand cmd = new GenericCommand(AgentReplicationSlice.H_MASTERREPLICACHANGED, NAME, null); + cmd.addParam(virtualAid); + cmd.addParam(newMasterAid); - return true; + try { + broadcast(cmd, false); // Do NOT include myself since the change in the local container has already been done + } catch (Exception e) { + myLogger.log(Logger.WARNING, "Error broadcasting master replica changed for virtual agent " + virtualAid.getLocalName(), e); } + } - private synchronized void addPeerReplica(ReplicaInfo r) { - if (!peerReplicas.contains(r)) { - myLogger.log(Logger.CONFIG, "Adding replica " + r.replicaAid.getLocalName() + " to Helper of agent " + myAid.getLocalName()); - peerReplicas.add(r); - peerReplicasArray = peerReplicas.toArray(new ReplicaInfo[0]); - } - } + private void broadcastVirtualAgentDead(AID virtualAid) { + myLogger.log(Logger.CONFIG, "Broadcasting virtual agent " + virtualAid.getLocalName() + " dead"); + GenericCommand cmd = new GenericCommand(AgentReplicationSlice.H_VIRTUALAGENTDEAD, NAME, null); + cmd.addParam(virtualAid); - private synchronized void removePeerReplica(ReplicaInfo r) { - if (peerReplicas.remove(r)) { - myLogger.log(Logger.CONFIG, "Removing replica " + r.replicaAid.getLocalName() + " from Helper of agent " + myAid.getLocalName()); - peerReplicasArray = peerReplicas.toArray(new ReplicaInfo[0]); - } + try { + broadcast(cmd, true); // Include myself + } catch (Exception e) { + myLogger.log(Logger.WARNING, "Error broadcasting master replica changed for virtual agent " + virtualAid.getLocalName(), e); } - } // END of inner class AgentReplicationHelperImpl - + } - /** - * Inner class CommandOutgoingFilter - */ - private class CommandOutgoingFilter extends Filter { - public CommandOutgoingFilter() { - super(); - setPreferredPosition(2); // Before the Messaging (encoding) filter and the security related ones + private void cloneReplica(AID aid, String replicaName, Location where) { + Agent agent = myContainer.acquireLocalAgent(aid); + if (agent != null) { + myLogger.log(Logger.CONFIG, "Cloning agent " + aid.getLocalName() + " to create replica " + replicaName + " on container " + where.getName()); + agent.doClone(where, replicaName); + myContainer.releaseLocalAgent(aid); } + } - @Override - public final boolean accept(VerticalCommand cmd) { - String name = cmd.getName(); - switch (name) { - case MessagingSlice.SEND_MESSAGE -> { - AID receiver = (AID) cmd.getParam(2); - GlobalReplicationInfo info = globalReplications.get(receiver); - if (info != null) { - // Receiver is a virtual AID --> Redirect the SEND_MESSAGE command to one of the implementation replicas - AID replica = info.getReplica(); - AID sender = (AID) cmd.getParam(0); - // NOTE that the gMsg cannot be a MultipleGenericMessage since we are in the outgoing chain - GenericMessage gMsg = (GenericMessage) cmd.getParam(1); - // In case the selected replica is no longer valid, the message will have to be delivered - // again to another replica --> instruct JADE not to clear the message content (see - // jade.core.messaging.OutBox.addLast()) - gMsg.setModifiable(false); - ACLMessage msg = gMsg.getACLMessage(); - if (msg != null) { - msg.addUserDefinedParameter(AgentReplicationHelper.VIRTUAL_RECEIVER, receiver.getLocalName()); - } - sendMessage(sender, gMsg, replica); - - // Veto the original command - return false; - } + private void asynchCloneReplica(AID aid, final String replicaName, final Location where) { + Agent agent = myContainer.acquireLocalAgent(aid); + if (agent != null) { + agent.addBehaviour(new OneShotBehaviour(agent) { + @Override + public void action() { + myLogger.log(Logger.CONFIG, "Cloning agent " + myAgent.getLocalName() + " to create replica " + replicaName + " on container " + where.getName()); + myAgent.doClone(where, replicaName); } - case MessagingSlice.NOTIFY_FAILURE -> { - GenericMessage gMsg = (GenericMessage) cmd.getParam(0); - ACLMessage msg = gMsg.getACLMessage(); - if (msg != null) { - String virtualName = msg.getUserDefinedParameter(AgentReplicationHelper.VIRTUAL_RECEIVER); - if (virtualName != null) { - // This message was originally sent to a virtual agent. The selected - // implementation replica is no longer there or is unreachable however --> - // Remove the dirty replica, then select a new one and retry - AID virtualAid = new AID(AID.createGUID(virtualName, myContainer.getPlatformID()), AID.ISGUID); - AID receiver = (AID) cmd.getParam(1); - removeReplica(virtualAid, receiver); + }); + myContainer.releaseLocalAgent(aid); + } + } - GlobalReplicationInfo info = globalReplications.get(virtualAid); - if (info != null) { - AID newReplica = info.getReplica(); - myLogger.log(Logger.FINE, "Redirecting message " + ACLMessage.getPerformative(msg.getPerformative()) + "[" + msg.getContent() + "] from dirty replica " + receiver.getLocalName() + " to new replica " + newReplica.getLocalName()); - if (receiver.equals(newReplica)) { - // This may happen in COLD_REPLICATION mode when the master replica - // has just died and has not been replaced yet. In this case sending - // this message will certainly fail, but we do it anyway until a new - // master replica is selected. Just wait a little bit in order to avoid - // entering a CPU consuming loop - try { - Thread.sleep(100); - } catch (Exception ignored) { - } - } - sendMessage(msg.getSender(), gMsg, newReplica); + private void sendMessage(AID sender, GenericMessage gMsg, AID receiver) { + GenericCommand cmd = new GenericCommand(MessagingSlice.SEND_MESSAGE, MessagingService.NAME, null); + cmd.addParam(sender); + cmd.addParam(gMsg); + cmd.addParam(receiver); - // Veto the original command - return false; - } - } - } + try { + theMessagingService.submit(cmd); + } catch (ServiceException se) { + // Should never happen + se.printStackTrace(); + } + } + + private void invokeAgentMethod(AID aid, String methodName, Object[] arguments) throws NotFoundException, ServiceException { + Agent agent = myContainer.acquireLocalAgent(aid); + if (agent != null) { + myContainer.releaseLocalAgent(aid); + try { + Method m = getMethod(agent, methodName); + if (myLogger.isLoggable(Logger.FINE)) { + myLogger.log(Logger.FINE, "Invoking replicated method " + methodName + " on agent " + aid.getLocalName()); } - case MainReplicationSlice.LEADERSHIP_ACQUIRED -> - // The master Main Container died and this backup Main just took the leadership. - // Other peripheral containers may have died in the meanwhile --> - // Check all replicated agents - checkAllReplications(); + AgentReplicationHandle.enterReplicatedCall(); + m.invoke(agent, arguments); + } catch (NoSuchMethodException nsme) { + throw new ServiceException("Method " + methodName + " not found in class " + agent.getClass().getName() + " of agent " + agent.getLocalName()); + } catch (IllegalAccessException iae) { + throw new ServiceException("Method " + methodName + " of class " + agent.getClass().getName() + " of agent " + agent.getLocalName() + " cannot be accessed"); + } catch (InvocationTargetException ite) { + throw new ServiceException("Exception excecuting method " + methodName + " of agent " + aid.getLocalName(), ite.getCause()); + } finally { + AgentReplicationHandle.exitReplicatedCall(); } - return true; + } else { + throw new NotFoundException("Agent " + aid.getLocalName() + " not found"); } + } - @Override - public final void postProcess(VerticalCommand cmd) { - if (cmd.getName().equals(AgentMobilityHelper.INFORM_CLONED)) { - AID id = (AID) cmd.getParam(0); - Location where = (Location) cmd.getParam(1); - String newName = (String) cmd.getParam(2); - List rr = pendingReplicaCreationRequests.get(id); - if (rr != null) { - ReplicaInfo r = rr.get(0); - if (r.where.equals(where) && r.replicaAid.getLocalName().equals(newName)) { - // This cloning process was triggered by a replica creation request. - // Remove the pending replica creation request, check if cloning was - // successful and, if this is the case register the new replica. - rr.remove(0); - boolean success = cmd.getReturnValue() == null; - if (success) { - broadcastAddReplica(id, r); - localNotifyReplicaAddedToMaster(id, r); - } + private void addReplica(AID virtualAid, AID replicaAid, Location where) throws Exception { + myLogger.log(Logger.CONFIG, "Received new replica information: virtual=" + virtualAid.getLocalName() + ", replica=" + replicaAid.getLocalName() + ", location=" + where.getName()); + addReplicaVirtualMapping(replicaAid, virtualAid); - // Finally, if there are other pending replica creation requests, serve the next one - if (rr.size() > 0) { - ReplicaInfo nextR = rr.get(0); - // In this very moment the agent state is already AP_COPY --> Cloning the agent now would have no effect - asynchCloneReplica(id, nextR.replicaAid.getLocalName(), nextR.where); - } else { - // NO more pending replica creation requests for agent id - pendingReplicaCreationRequests.remove(id); - } + GlobalReplicationInfo info = globalReplications.get(virtualAid); + if (info != null) { + // If some of the current replicas live in the local container, update the related helper + AID[] currentReplicas = info.getAllReplicas(); + for (AID aid : currentReplicas) { + Agent agent = myContainer.acquireLocalAgent(aid); + if (agent != null) { + try { + AgentReplicationHelperImpl helper = (AgentReplicationHelperImpl) agent.getHelper(NAME); + helper.addPeerReplica(new ReplicaInfo(replicaAid, where)); + } catch (ServiceException se) { + // Should never happen since the AgentReplicationService is certainly installed in this container + myLogger.log(Logger.WARNING, "Unexpected error retrieving AgentReplicationHelper for agent " + aid.getName(), se); + } finally { + myContainer.releaseLocalAgent(aid); } } } + + // Then add the new replica. In this way the helper of the new replica will never + // be updated with the information of the new replica itself + info.addReplica(replicaAid); + } else { + myLogger.log(Logger.WARNING, "Global Replication information for virtual agent " + virtualAid.getLocalName() + " not found in container " + myContainer.getID().getName()); } - } // END of inner class CommandOutgoingFilter + } + private void removeReplica(AID virtualAid, AID replicaAid) { + removeReplicaVirtualMapping(replicaAid); - /** - * Inner class CommandIncomingFilter - */ - private class CommandIncomingFilter extends Filter { - public CommandIncomingFilter() { - super(); - setPreferredPosition(2); // Before the Messaging (encoding) filter and the security related ones - } - - @Override - public final boolean accept(VerticalCommand cmd) { - String name = cmd.getName(); - if (myContainer.getMain() != null) { - switch (name) { - case AgentManagementSlice.INFORM_KILLED: - // If the dead agent is a master replica of a virtual agent, select a new master replica and broadcast the information - AID deadAgent = (AID) cmd.getParam(0); - handleInformKilled(deadAgent); - break; - case Service.NEW_SLICE: - // If the new slice is an AgentReplicationSlice, notify it about the current virtual agents - if (cmd.getService().equals(NAME)) { - String sliceName = (String) cmd.getParam(0); - handleNewSlice(sliceName); - } - break; - case Service.DEAD_NODE: - // A node monitored by this Main Container has just been removed - // If it was a sudden termination (e.g. fault) INFORM_KILLED VCommands - // for agents in the dead node were not issued --> - // Check all replicated agents - checkAllReplications(); - break; - } - } else { - if (name.equals(Service.REATTACHED)) { - // The Main lost all information related to this container --> Notify it again - handleReattached(); - } - } - // Never veto a Command - return true; - } + GlobalReplicationInfo info = globalReplications.get(virtualAid); + if (info != null) { + info.removeReplica(replicaAid); - private void handleInformKilled(AID deadAid) { - AID virtualAid = replicaToVirtualMap.remove(deadAid); - if (virtualAid != null) { - GlobalReplicationInfo info = globalReplications.get(virtualAid); - if (info != null) { - if (deadAid.equals(info.getMaster())) { - // The dead agent is the master replica of a virtual agent - handleMasterReplicaDead(info); - } else { - // The dead agent is a non-master replica --> Just notify the master - notifyReplicaRemovedToMaster(info.getMaster(), deadAid, null); + // If some of the remaining replicas live in the local container, update the related helper + AID[] currentReplicas = info.getAllReplicas(); + for (AID aid : currentReplicas) { + Agent agent = myContainer.acquireLocalAgent(aid); + if (agent != null) { + try { + AgentReplicationHelperImpl helper = (AgentReplicationHelperImpl) agent.getHelper(NAME); + helper.removePeerReplica(new ReplicaInfo(replicaAid, null)); + } catch (ServiceException se) { + // Should never happen since the AgentReplicationService is certainly installed in this container + myLogger.log(Logger.WARNING, "Unexpected error retrieving AgentReplicationHelper for agent " + aid.getLocalName(), se); + } finally { + myContainer.releaseLocalAgent(aid); } } } } + } - private void handleNewSlice(String newSliceName) { - try { - // Be sure to get the new (fresh) slice --> Bypass the service cache - AgentReplicationSlice newSlice = (AgentReplicationSlice) getFreshSlice(newSliceName); - GlobalReplicationInfo[] allInfos = globalReplications.values().toArray(new GlobalReplicationInfo[0]); + private void addReplicaVirtualMapping(AID replicaAid, AID virtualAid) { + AID oldVirtualAid = replicaToVirtualMap.put(replicaAid, virtualAid); + if (oldVirtualAid == null || !oldVirtualAid.equals(virtualAid)) { + myLogger.log(Logger.CONFIG, "Added replica-to-virtual mapping: " + replicaAid.getLocalName() + "-->" + virtualAid.getLocalName()); + } + } - for (GlobalReplicationInfo info : allInfos) { - newSlice.synchReplication(info); - } - } catch (Throwable t) { - myLogger.log(Logger.WARNING, "Error notifying new slice " + newSliceName + " about current replication information", t); - } + private void removeReplicaVirtualMapping(AID replicaAid) { + AID virtualAid = replicaToVirtualMap.remove(replicaAid); + if (virtualAid != null) { + myLogger.log(Logger.CONFIG, "Removed replica-to-virtual mapping: " + replicaAid.getLocalName() + "-->" + virtualAid.getLocalName()); } + } - private void handleReattached() { - try { - // Be sure to get a fresh slice --> Bypass the service cache - AgentReplicationSlice mainSlice = (AgentReplicationSlice) getFreshSlice(MAIN_SLICE); - // Notify the new Main Slice all replication information related to virtual agents - // for which an implementation replica lives in the local container. - // NOTE that the same replication information can be notified to the new Main Slice - // by more than one container, but this case is properly taken into account so - // that duplications are avoided. - AID[] aa = replicaToVirtualMap.keySet().toArray(new AID[0]); - List vv = new ArrayList<>(); - for (AID aid : aa) { - if (myContainer.isLocalAgent(aid)) { - AID virtualAid = replicaToVirtualMap.get(aid); - if (virtualAid != null && !vv.contains(virtualAid)) { - GlobalReplicationInfo info = globalReplications.get(virtualAid); - if (info != null) { - try { - mainSlice.synchReplication(info); - } catch (Exception e) { - myLogger.log(Logger.WARNING, "Error notifying main slice about current local replication information", e); - } - } - vv.add(virtualAid); - } - } + private GlobalReplicationInfo newVirtualAgent(AID virtualAid, AID masterAid, int replicationMode) throws Exception { + GlobalReplicationInfo info = null; + // In the reattach procedure this method can be called in parallel for the same virtual agent + synchronized (globalReplications) { + info = globalReplications.get(virtualAid); + if (info == null) { + myLogger.log(Logger.CONFIG, "New virtual agent: virtual=" + virtualAid.getLocalName() + ", master=" + masterAid.getLocalName()); + info = new GlobalReplicationInfo(virtualAid, masterAid, replicationMode); + globalReplications.put(virtualAid, info); + } else { + // Just check that information are consistent + if (!masterAid.equals(info.getMaster())) { + throw new ServiceException("Inconsistent replication information for virtual agent " + virtualAid.getLocalName() + ": current-master = " + info.getMaster().getLocalName() + ", new-master = " + masterAid.getLocalName()); } - } catch (Throwable t) { - myLogger.log(Logger.WARNING, "Error retrieving main slice.", t); } } - } // END of inner class CommandIncomingFilter - - - /** - * Inner class ReplicaInfo - */ - private class ReplicaInfo { - private final AID replicaAid; - private Location where; - - private ReplicaInfo(AID replicaAid, Location where) { - this.replicaAid = replicaAid; - this.where = where; - } - - @Override - public int hashCode() { - return replicaAid.hashCode(); - } - - @Override - public boolean equals(Object obj) { - return replicaAid.equals(((ReplicaInfo) obj).replicaAid); - } - } // END of inner class ReplicaInfo - + addReplicaVirtualMapping(masterAid, virtualAid); + return info; + } - private void localNotifyReplicaAddedToMaster(AID masterAid, ReplicaInfo r) { - // Note that this method is invoked in the master replica container --> - // Unlike other notifyXXX() methods, only the "local" version is needed - Agent agent = myContainer.acquireLocalAgent(masterAid); - if (agent != null) { - myContainer.releaseLocalAgent(masterAid); - try { - if (agent instanceof AgentReplicationHelper.Listener) { - ((AgentReplicationHelper.Listener) agent).replicaAdded(r.replicaAid, r.where); - } - } catch (Exception e) { - myLogger.log(Logger.WARNING, "Unexpected exception notifying master agent (replicaAdded())", e); - } + private ContainerID getAgentLocation(AID aid) throws NotFoundException { + MainContainer impl = myContainer.getMain(); + if (impl != null) { + return impl.getContainerID(aid); + } else { + // Should never happen + throw new NotFoundException("getAgentLocation() invoked on a non-main container"); } } - private void notifyReplicaRemovedToMaster(AID masterAid, AID removedReplica, Location where) { - try { - // This is always invoked on the Main Container - if (where == null) { + private void handleMasterReplicaDead(GlobalReplicationInfo info) { + // No need to check if impl is null since this can only be executed on a Main Container + MainContainer impl = myContainer.getMain(); + do { + AID newMasterAid = info.masterReplicaDead(); + if (newMasterAid != null) { + // New master replica selected. Check if it is actually alive. Otherwise try again + if (impl.acquireAgentDescriptor(newMasterAid) != null) { + // New master replica alive --> Broadcast the change to all other slices + impl.releaseAgentDescriptor(newMasterAid); + broadcastMasterReplicaChanged(info.getVirtual(), newMasterAid); + // Then notify the selected agent that it became the new master + notifyBecomeMasterToMaster(newMasterAid); + return; + } + } else { + // This virtual agent does not have replicas anymore --> remove it try { - where = getAgentLocation(removedReplica); + impl.deadAgent(info.getVirtual(), false); } catch (NotFoundException nfe) { - // If this is triggered by a container fault, the GADT has already been cleaned. - // We are not able to fill the removed replica location. + // Just ignore } + broadcastVirtualAgentDead(info.getVirtual()); + return; } - Location masterLocation = getAgentLocation(masterAid); - AgentReplicationSlice slice = (AgentReplicationSlice) getFreshSlice(masterLocation.getName()); - slice.notifyReplicaRemoved(masterAid, removedReplica, where); - } catch (Exception e) { - // Should never happen as this masterAid has just been selected (and checked) as new master - myLogger.log(Logger.WARNING, "Error notifying master replica " + masterAid.getLocalName() + " that replica " + removedReplica.getLocalName() + " has been removed", e); - } + } while (true); } - private void localNotifyReplicaRemovedToMaster(AID masterAid, AID removedReplica, Location where) { - Agent agent = myContainer.acquireLocalAgent(masterAid); - if (agent != null) { - myContainer.releaseLocalAgent(masterAid); - try { - if (agent instanceof AgentReplicationHelper.Listener) { - ((AgentReplicationHelper.Listener) agent).replicaRemoved(removedReplica, where); + private void checkAllReplications() { + // No need to check if impl is null since this can only be executed on a Main Container + MainContainer impl = myContainer.getMain(); + // For each virtual agent + // - check if the related master replica is still alive. + // If not handle the dead master replica case. + // - then for each replica check if it is still alive. If not notify the master + GlobalReplicationInfo[] gg = globalReplications.values().toArray(new GlobalReplicationInfo[0]); + for (GlobalReplicationInfo info : gg) { + // Check master + AID masterAid = info.getMaster(); + if (impl.acquireAgentDescriptor(masterAid) != null) { + // Master replica still there --> nothing to do + impl.releaseAgentDescriptor(masterAid); + myLogger.log(Logger.INFO, "Master replica " + masterAid.getLocalName() + " of virtual agent " + info.getVirtual().getLocalName() + " ALIVE"); + } else { + // Master replica is not there anymore --> DEAD + handleMasterReplicaDead(info); + masterAid = info.getMaster(); + } + + // Check other replicas + AID[] allReplicas = info.getAllReplicas(); + for (AID replicaAid : allReplicas) { + if (!replicaAid.equals(masterAid)) { + if (impl.acquireAgentDescriptor(replicaAid) != null) { + // Replica still there --> nothing to do + impl.releaseAgentDescriptor(replicaAid); + myLogger.log(Logger.INFO, "Replica " + replicaAid.getLocalName() + " of virtual agent " + info.getVirtual().getLocalName() + " ALIVE"); + } else { + // Replica is not there anymore --> DEAD + notifyReplicaRemovedToMaster(masterAid, replicaAid, null); + } } - } catch (Exception e) { - myLogger.log(Logger.WARNING, "Unexpected exception notifying master agent (becomeMaster())", e); } } } - private void notifyBecomeMasterToMaster(AID masterAid) { - try { - // This is always invoked on the Main Container - Location masterLocation = getAgentLocation(masterAid); - AgentReplicationSlice slice = (AgentReplicationSlice) getFreshSlice(masterLocation.getName()); - slice.notifyBecomeMaster(masterAid); - } catch (Exception e) { - // Should never happen as this masterAid has just been selected (and checked) as new master - myLogger.log(Logger.WARNING, "Error notifying new master replica " + masterAid.getLocalName() + " it just took the leadership", e); - } - } - - private void localNotifyBecomeMasterToMaster(AID masterAid) { - Agent agent = myContainer.acquireLocalAgent(masterAid); - if (agent != null) { - myContainer.releaseLocalAgent(masterAid); - try { - if (agent instanceof AgentReplicationHelper.Listener) { - ((AgentReplicationHelper.Listener) agent).becomeMaster(); + private Method getMethod(Agent agent, String methodName) throws NoSuchMethodException { + String key = agent.getLocalName() + '#' + methodName; + Method m = cachedAgentMethods.get(key); + if (m == null) { + // NOTE: We cannot use Class.getMethod() since we have parameter values, but not parameter types + Method[] mm = agent.getClass().getMethods(); + for (Method method : mm) { + if (method.getName().equals(methodName)) { + m = method; + cachedAgentMethods.put(key, m); + break; } - } catch (Exception e) { - myLogger.log(Logger.WARNING, "Unexpected exception notifying master agent (becomeMaster())", e); } } + if (m == null) { + throw new NoSuchMethodException(methodName); + } + return m; } - private Location getLocation(AID aid) throws Exception { - if (myContainer.isLocalAgent(aid)) { - return myContainer.getID(); - } + /** + * Inner class AgentReplicationHelperImpl + */ + private class AgentReplicationHelperImpl implements AgentReplicationHelper { + private final List peerReplicas = new ArrayList<>(); + private AID myAid; + private AID virtualAid; + private ReplicaInfo[] peerReplicasArray = new ReplicaInfo[0]; - // Aid lives somewhere else --> ask the slice on the Main Container - AgentReplicationSlice mainSlice = (AgentReplicationSlice) getSlice(MAIN_SLICE); - try { - return mainSlice.getAgentLocation(aid); - } catch (IMTPException imtpe) { - // Get a fresh slice and retry - mainSlice = (AgentReplicationSlice) getFreshSlice(MAIN_SLICE); - return mainSlice.getAgentLocation(aid); - } - } + public void init(Agent a) { + myAid = a.getAID(); - private AID getVirtualAid(AID aid) { - Agent agent = myContainer.acquireLocalAgent(aid); - if (agent != null) { - try { - AgentReplicationHelper helper = (AgentReplicationHelper) agent.getHelper(NAME); - return helper.getVirtualAid(); - } catch (ServiceException se) { - // Should never happen since the AgentReplicationService is certainly there - myLogger.log(Logger.WARNING, "Unexpected error retrieving AgentReplicationHelper for agent " + aid.getName()); - return null; - } finally { - myContainer.releaseLocalAgent(aid); + // If the agent retrieving this helper is already a replica, initialize virtualAid + // and peerReplicas from the global replication information + virtualAid = replicaToVirtualMap.get(myAid); + if (virtualAid != null) { + GlobalReplicationInfo info = globalReplications.get(virtualAid); + if (info != null) { + AID[] currentReplicas = info.getAllReplicas(); + for (AID replica : currentReplicas) { + // Exclude the agent itself from peer replicas + if (!replica.equals(myAid)) { + try { + Location location = getLocation(replica); + addPeerReplica(new ReplicaInfo(replica, location)); + } catch (NotFoundException nfe) { + myLogger.log(Logger.WARNING, "Replica " + replica.getLocalName() + " not found. Likely it died in the meanwhile"); + } catch (Exception e) { + myLogger.log(Logger.SEVERE, "Error retrieving location for agent " + replica.getLocalName(), e); + } + } + } + } else { + myLogger.log(Logger.SEVERE, "Virtual agent " + virtualAid.getLocalName() + " for replica agent " + myAid.getLocalName() + " not found"); + } } - } else { - return null; } - } - private void broadcastNewVirtualAgent(AID virtualAid, AID masterAid, int replicationMode) { - myLogger.log(Logger.CONFIG, "Broadcasting new virtual agent " + virtualAid.getLocalName()); - GenericCommand cmd = new GenericCommand(AgentReplicationSlice.H_NEWVIRTUALAGENT, NAME, null); - cmd.addParam(virtualAid); - cmd.addParam(masterAid); - cmd.addParam(replicationMode); - - try { - broadcast(cmd, true); // Include myself - } catch (Exception e) { - myLogger.log(Logger.SEVERE, "Error broadcasting new virtual agent " + virtualAid.getLocalName(), e); - } - } + public AID makeVirtual(String virtualName, int replicationMode) throws ServiceException { + if (virtualAid == null) { + virtualAid = new AID(AID.createGUID(virtualName, myContainer.getPlatformID()), AID.ISGUID); - private void broadcastAddReplica(AID masterAid, ReplicaInfo r) { - AID virtualAid = getVirtualAid(masterAid); - if (virtualAid != null) { - myLogger.log(Logger.CONFIG, "Broadcasting new replica " + r.replicaAid.getLocalName() + " of virtual agent " + virtualAid.getLocalName()); - GenericCommand cmd = new GenericCommand(AgentReplicationSlice.H_ADDREPLICA, NAME, null); - cmd.addParam(virtualAid); - cmd.addParam(r.replicaAid); - cmd.addParam(r.where); + // Reserve the virtualName by registering the virtual AID to the AMS + AMSAgentDescription amsd = new AMSAgentDescription(); + amsd.setName(virtualAid); + amsd.setState(AMSAgentDescription.ACTIVE); + Agent agent = myContainer.acquireLocalAgent(myAid); + // Immediately release the agent: AMSService.register() requires that the agent receives the AMS reply + myContainer.releaseLocalAgent(myAid); + if (agent != null) { + try { + AMSService.register(agent, amsd); + } catch (Exception e) { + throw new ServiceException("Error registering virtual name " + virtualName, e); + } + } - try { - broadcast(cmd, true); // Include myself - } catch (Exception e) { - myLogger.log(Logger.SEVERE, "Error broadcasting new replica " + r.replicaAid.getLocalName() + " of virtual agent " + virtualAid.getLocalName(), e); + broadcastNewVirtualAgent(virtualAid, myAid, replicationMode); + return virtualAid; + } else { + throw new ServiceException("Agent " + myAid.getLocalName() + " has already been made virtual"); } - } else { - myLogger.log(Logger.WARNING, "Cannot find virtual agent for master replica " + masterAid.getLocalName()); } - } - private void broadcastMasterReplicaChanged(AID virtualAid, AID newMasterAid) { - myLogger.log(Logger.CONFIG, "Broadcasting master replica changed for virtual agent " + virtualAid.getLocalName() + ". New master replica = " + newMasterAid.getLocalName()); - GenericCommand cmd = new GenericCommand(AgentReplicationSlice.H_MASTERREPLICACHANGED, NAME, null); - cmd.addParam(virtualAid); - cmd.addParam(newMasterAid); + public void createReplica(String replicaName, Location where) throws ServiceException { + if (virtualAid != null) { + if (isMaster()) { + // The agent this helper belongs to is virtualized and is the master replica + // Go on with the replica creation process + AgentReplicationSlice slice = (AgentReplicationSlice) getSlice(where.getName()); + if (slice != null) { + // Notify the destination slice that a replica for our virtual agent is + // going to be created there (see comment in AgentReplicationSlice) + AID replicaAid = new AID(AID.createGUID(replicaName, myContainer.getPlatformID()), AID.ISGUID); + try { + slice.replicaCreationRequested(virtualAid, replicaAid); + } catch (IMTPException imtpe) { + // Get a fresh slice and retry + slice = (AgentReplicationSlice) getFreshSlice(where.getName()); + try { + slice.replicaCreationRequested(virtualAid, replicaAid); + } catch (IMTPException imtpe1) { + throw new ServiceException("IMTP error contacting destination slice", imtpe1); + } + } - try { - broadcast(cmd, false); // Do NOT include myself since the change in the local container has already been done - } catch (Exception e) { - myLogger.log(Logger.WARNING, "Error broadcasting master replica changed for virtual agent " + virtualAid.getLocalName(), e); + // Enqueue the replica creation request + List rr = pendingReplicaCreationRequests.computeIfAbsent(myAid, k -> new ArrayList<>()); + rr.add(new ReplicaInfo(replicaAid, where)); + + // If there are no other ongoing replica creation processes --> directly clone the (master) agent. + if (rr.size() == 1) { + cloneReplica(myAid, replicaName, where); + } + } else { + throw new ServiceException("AgentReplicationService not installed in the destination container " + where.getName() + " for replica " + replicaName); + } + } else { + throw new ServiceException("Agent " + myAid.getLocalName() + " is not the master replica"); + } + } else { + throw new ServiceException("Agent " + myAid.getLocalName() + " has not been made virtual"); + } } - } - private void broadcastVirtualAgentDead(AID virtualAid) { - myLogger.log(Logger.CONFIG, "Broadcasting virtual agent " + virtualAid.getLocalName() + " dead"); - GenericCommand cmd = new GenericCommand(AgentReplicationSlice.H_VIRTUALAGENTDEAD, NAME, null); - cmd.addParam(virtualAid); + public AID getVirtualAid() { + return virtualAid; + } - try { - broadcast(cmd, true); // Include myself - } catch (Exception e) { - myLogger.log(Logger.WARNING, "Error broadcasting master replica changed for virtual agent " + virtualAid.getLocalName(), e); + public AID getMasterAid() { + if (virtualAid != null) { + GlobalReplicationInfo info = globalReplications.get(virtualAid); + return info.getMaster(); + } + return null; } - } + public boolean isMaster() { + if (virtualAid != null) { + GlobalReplicationInfo info = globalReplications.get(virtualAid); + return myAid.equals(info.getMaster()); + } + return false; + } - private void cloneReplica(AID aid, String replicaName, Location where) { - Agent agent = myContainer.acquireLocalAgent(aid); - if (agent != null) { - myLogger.log(Logger.CONFIG, "Cloning agent " + aid.getLocalName() + " to create replica " + replicaName + " on container " + where.getName()); - agent.doClone(where, replicaName); - myContainer.releaseLocalAgent(aid); + public Map getReplicas() { + // FIXME: To be implemented + return null; } - } - private void asynchCloneReplica(AID aid, final String replicaName, final Location where) { - Agent agent = myContainer.acquireLocalAgent(aid); - if (agent != null) { - agent.addBehaviour(new OneShotBehaviour(agent) { - @Override - public void action() { - myLogger.log(Logger.CONFIG, "Cloning agent " + myAgent.getLocalName() + " to create replica " + replicaName + " on container " + where.getName()); - myAgent.doClone(where, replicaName); + public void invokeReplicatedMethod(String methodName, Object[] arguments) { + ReplicaInfo[] tmp = peerReplicasArray; + myLogger.log(Logger.FINE, "Invoking method " + methodName + " on " + tmp.length + " replica(s)"); + for (ReplicaInfo r : tmp) { + try { + if (!invokeOnReplica(methodName, arguments, r)) { + // This replica agent does not exist anymore --> remove it + removePeerReplica(r); + GlobalReplicationInfo info = globalReplications.get(virtualAid); + if (info != null) { + info.removeReplica(r.replicaAid); + } + } + } catch (Exception e) { + myLogger.log(Logger.SEVERE, "Error propagating call to method " + methodName + " to agent " + r.replicaAid.getLocalName(), e); } - }); - myContainer.releaseLocalAgent(aid); + } } - } - private void sendMessage(AID sender, GenericMessage gMsg, AID receiver) { - GenericCommand cmd = new GenericCommand(MessagingSlice.SEND_MESSAGE, MessagingService.NAME, null); - cmd.addParam(sender); - cmd.addParam(gMsg); - cmd.addParam(receiver); + private boolean invokeOnReplica(String methodName, Object[] arguments, ReplicaInfo r) throws Exception { + myLogger.log(Logger.FINER, "Invoking method " + methodName + " on replica " + r.replicaAid.getLocalName()); + // If we get an Exception, refresh the location of the replica (it + // may have moved or be recreated somewhere else) and retry until OK. + // If not found in Main Container --> Ignore: replica has terminated in the meanwhile + do { + AgentReplicationSlice slice = (AgentReplicationSlice) getSlice(r.where.getName()); + if (slice != null) { + try { + try { + slice.invokeAgentMethod(r.replicaAid, methodName, arguments); + // Done: Jump out + break; + } catch (IMTPException imtpe) { + // Try to get a newer slice and repeat... + slice = (AgentReplicationSlice) getFreshSlice(r.where.getName()); + slice.invokeAgentMethod(r.replicaAid, methodName, arguments); + // Done: Jump out + break; + } + } catch (NotFoundException nfe) { + // The replica agent was not found on the container where it was supposed to be + // Possibly it has moved elsewhere --> Check with the Main Container + } + } - try { - theMessagingService.submit(cmd); - } catch (ServiceException se) { - // Should never happen - se.printStackTrace(); + // Not done: Update the replica location and retry + try { + myLogger.log(Logger.CONFIG, "Updating location of replica " + r.replicaAid.getLocalName()); + // The replica agent is alive: update its location and retry + r.where = getLocation(r.replicaAid); + } catch (NotFoundException nfe1) { + // The replica agent does not exist anymore in the whole platform --> silently remove it + return false; + } + } while (true); + + return true; } - } - private void invokeAgentMethod(AID aid, String methodName, Object[] arguments) throws NotFoundException, ServiceException { - Agent agent = myContainer.acquireLocalAgent(aid); - if (agent != null) { - myContainer.releaseLocalAgent(aid); - try { - Method m = getMethod(agent, methodName); - if (myLogger.isLoggable(Logger.FINE)) { - myLogger.log(Logger.FINE, "Invoking replicated method " + methodName + " on agent " + aid.getLocalName()); - } - AgentReplicationHandle.enterReplicatedCall(); - m.invoke(agent, arguments); - } catch (NoSuchMethodException nsme) { - throw new ServiceException("Method " + methodName + " not found in class " + agent.getClass().getName() + " of agent " + agent.getLocalName()); - } catch (IllegalAccessException iae) { - throw new ServiceException("Method " + methodName + " of class " + agent.getClass().getName() + " of agent " + agent.getLocalName() + " cannot be accessed"); - } catch (InvocationTargetException ite) { - throw new ServiceException("Exception excecuting method " + methodName + " of agent " + aid.getLocalName(), ite.getCause()); - } finally { - AgentReplicationHandle.exitReplicatedCall(); + private synchronized void addPeerReplica(ReplicaInfo r) { + if (!peerReplicas.contains(r)) { + myLogger.log(Logger.CONFIG, "Adding replica " + r.replicaAid.getLocalName() + " to Helper of agent " + myAid.getLocalName()); + peerReplicas.add(r); + peerReplicasArray = peerReplicas.toArray(new ReplicaInfo[0]); } - } else { - throw new NotFoundException("Agent " + aid.getLocalName() + " not found"); } - } - private void addReplica(AID virtualAid, AID replicaAid, Location where) throws Exception { - myLogger.log(Logger.CONFIG, "Received new replica information: virtual=" + virtualAid.getLocalName() + ", replica=" + replicaAid.getLocalName() + ", location=" + where.getName()); + private synchronized void removePeerReplica(ReplicaInfo r) { + if (peerReplicas.remove(r)) { + myLogger.log(Logger.CONFIG, "Removing replica " + r.replicaAid.getLocalName() + " from Helper of agent " + myAid.getLocalName()); + peerReplicasArray = peerReplicas.toArray(new ReplicaInfo[0]); + } + } + } // END of inner class AgentReplicationHelperImpl - addReplicaVirtualMapping(replicaAid, virtualAid); + /** + * Inner class CommandOutgoingFilter + */ + private class CommandOutgoingFilter extends Filter { + public CommandOutgoingFilter() { + super(); + setPreferredPosition(2); // Before the Messaging (encoding) filter and the security related ones + } - GlobalReplicationInfo info = globalReplications.get(virtualAid); - if (info != null) { - // If some of the current replicas live in the local container, update the related helper - AID[] currentReplicas = info.getAllReplicas(); - for (AID aid : currentReplicas) { - Agent agent = myContainer.acquireLocalAgent(aid); - if (agent != null) { - try { - AgentReplicationHelperImpl helper = (AgentReplicationHelperImpl) agent.getHelper(NAME); - helper.addPeerReplica(new ReplicaInfo(replicaAid, where)); - } catch (ServiceException se) { - // Should never happen since the AgentReplicationService is certainly installed in this container - myLogger.log(Logger.WARNING, "Unexpected error retrieving AgentReplicationHelper for agent " + aid.getName(), se); - } finally { - myContainer.releaseLocalAgent(aid); + @Override + public final boolean accept(VerticalCommand cmd) { + String name = cmd.getName(); + switch (name) { + case MessagingSlice.SEND_MESSAGE -> { + AID receiver = (AID) cmd.getParam(2); + GlobalReplicationInfo info = globalReplications.get(receiver); + if (info != null) { + // Receiver is a virtual AID --> Redirect the SEND_MESSAGE command to one of the implementation replicas + AID replica = info.getReplica(); + AID sender = (AID) cmd.getParam(0); + // NOTE that the gMsg cannot be a MultipleGenericMessage since we are in the outgoing chain + GenericMessage gMsg = (GenericMessage) cmd.getParam(1); + // In case the selected replica is no longer valid, the message will have to be delivered + // again to another replica --> instruct JADE not to clear the message content (see + // jade.core.messaging.OutBox.addLast()) + gMsg.setModifiable(false); + ACLMessage msg = gMsg.getACLMessage(); + if (msg != null) { + msg.addUserDefinedParameter(AgentReplicationHelper.VIRTUAL_RECEIVER, receiver.getLocalName()); + } + sendMessage(sender, gMsg, replica); + + // Veto the original command + return false; } } - } - - // Then add the new replica. In this way the helper of the new replica will never - // be updated with the information of the new replica itself - info.addReplica(replicaAid); - } else { - myLogger.log(Logger.WARNING, "Global Replication information for virtual agent " + virtualAid.getLocalName() + " not found in container " + myContainer.getID().getName()); - } - } + case MessagingSlice.NOTIFY_FAILURE -> { + GenericMessage gMsg = (GenericMessage) cmd.getParam(0); + ACLMessage msg = gMsg.getACLMessage(); + if (msg != null) { + String virtualName = msg.getUserDefinedParameter(AgentReplicationHelper.VIRTUAL_RECEIVER); + if (virtualName != null) { + // This message was originally sent to a virtual agent. The selected + // implementation replica is no longer there or is unreachable however --> + // Remove the dirty replica, then select a new one and retry + AID virtualAid = new AID(AID.createGUID(virtualName, myContainer.getPlatformID()), AID.ISGUID); + AID receiver = (AID) cmd.getParam(1); + removeReplica(virtualAid, receiver); - private void removeReplica(AID virtualAid, AID replicaAid) { - removeReplicaVirtualMapping(replicaAid); + GlobalReplicationInfo info = globalReplications.get(virtualAid); + if (info != null) { + AID newReplica = info.getReplica(); + myLogger.log(Logger.FINE, "Redirecting message " + ACLMessage.getPerformative(msg.getPerformative()) + "[" + msg.getContent() + "] from dirty replica " + receiver.getLocalName() + " to new replica " + newReplica.getLocalName()); + if (receiver.equals(newReplica)) { + // This may happen in COLD_REPLICATION mode when the master replica + // has just died and has not been replaced yet. In this case sending + // this message will certainly fail, but we do it anyway until a new + // master replica is selected. Just wait a little bit in order to avoid + // entering a CPU consuming loop + try { + Thread.sleep(100); + } catch (Exception ignored) { + } + } + sendMessage(msg.getSender(), gMsg, newReplica); - GlobalReplicationInfo info = globalReplications.get(virtualAid); - if (info != null) { - info.removeReplica(replicaAid); + // Veto the original command + return false; + } + } + } + } + case MainReplicationSlice.LEADERSHIP_ACQUIRED -> + // The master Main Container died and this backup Main just took the leadership. + // Other peripheral containers may have died in the meanwhile --> + // Check all replicated agents + checkAllReplications(); + } + return true; + } - // If some of the remaining replicas live in the local container, update the related helper - AID[] currentReplicas = info.getAllReplicas(); - for (AID aid : currentReplicas) { - Agent agent = myContainer.acquireLocalAgent(aid); - if (agent != null) { - try { - AgentReplicationHelperImpl helper = (AgentReplicationHelperImpl) agent.getHelper(NAME); - helper.removePeerReplica(new ReplicaInfo(replicaAid, null)); - } catch (ServiceException se) { - // Should never happen since the AgentReplicationService is certainly installed in this container - myLogger.log(Logger.WARNING, "Unexpected error retrieving AgentReplicationHelper for agent " + aid.getLocalName(), se); - } finally { - myContainer.releaseLocalAgent(aid); + @Override + public final void postProcess(VerticalCommand cmd) { + if (cmd.getName().equals(AgentMobilityHelper.INFORM_CLONED)) { + AID id = (AID) cmd.getParam(0); + Location where = (Location) cmd.getParam(1); + String newName = (String) cmd.getParam(2); + List rr = pendingReplicaCreationRequests.get(id); + if (rr != null) { + ReplicaInfo r = rr.get(0); + if (r.where.equals(where) && r.replicaAid.getLocalName().equals(newName)) { + // This cloning process was triggered by a replica creation request. + // Remove the pending replica creation request, check if cloning was + // successful and, if this is the case register the new replica. + rr.remove(0); + boolean success = cmd.getReturnValue() == null; + if (success) { + broadcastAddReplica(id, r); + localNotifyReplicaAddedToMaster(id, r); + } + + + // Finally, if there are other pending replica creation requests, serve the next one + if (rr.size() > 0) { + ReplicaInfo nextR = rr.get(0); + // In this very moment the agent state is already AP_COPY --> Cloning the agent now would have no effect + asynchCloneReplica(id, nextR.replicaAid.getLocalName(), nextR.where); + } else { + // NO more pending replica creation requests for agent id + pendingReplicaCreationRequests.remove(id); + } } } } } - } - - private void addReplicaVirtualMapping(AID replicaAid, AID virtualAid) { - AID oldVirtualAid = replicaToVirtualMap.put(replicaAid, virtualAid); - if (oldVirtualAid == null || !oldVirtualAid.equals(virtualAid)) { - myLogger.log(Logger.CONFIG, "Added replica-to-virtual mapping: " + replicaAid.getLocalName() + "-->" + virtualAid.getLocalName()); - } - } + } // END of inner class CommandOutgoingFilter - private void removeReplicaVirtualMapping(AID replicaAid) { - AID virtualAid = replicaToVirtualMap.remove(replicaAid); - if (virtualAid != null) { - myLogger.log(Logger.CONFIG, "Removed replica-to-virtual mapping: " + replicaAid.getLocalName() + "-->" + virtualAid.getLocalName()); + /** + * Inner class CommandIncomingFilter + */ + private class CommandIncomingFilter extends Filter { + public CommandIncomingFilter() { + super(); + setPreferredPosition(2); // Before the Messaging (encoding) filter and the security related ones } - } - private GlobalReplicationInfo newVirtualAgent(AID virtualAid, AID masterAid, int replicationMode) throws Exception { - GlobalReplicationInfo info = null; - // In the reattach procedure this method can be called in parallel for the same virtual agent - synchronized (globalReplications) { - info = globalReplications.get(virtualAid); - if (info == null) { - myLogger.log(Logger.CONFIG, "New virtual agent: virtual=" + virtualAid.getLocalName() + ", master=" + masterAid.getLocalName()); - info = new GlobalReplicationInfo(virtualAid, masterAid, replicationMode); - globalReplications.put(virtualAid, info); + @Override + public final boolean accept(VerticalCommand cmd) { + String name = cmd.getName(); + if (myContainer.getMain() != null) { + switch (name) { + case AgentManagementSlice.INFORM_KILLED: + // If the dead agent is a master replica of a virtual agent, select a new master replica and broadcast the information + AID deadAgent = (AID) cmd.getParam(0); + handleInformKilled(deadAgent); + break; + case Service.NEW_SLICE: + // If the new slice is an AgentReplicationSlice, notify it about the current virtual agents + if (cmd.getService().equals(NAME)) { + String sliceName = (String) cmd.getParam(0); + handleNewSlice(sliceName); + } + break; + case Service.DEAD_NODE: + // A node monitored by this Main Container has just been removed + // If it was a sudden termination (e.g. fault) INFORM_KILLED VCommands + // for agents in the dead node were not issued --> + // Check all replicated agents + checkAllReplications(); + break; + } } else { - // Just check that information are consistent - if (!masterAid.equals(info.getMaster())) { - throw new ServiceException("Inconsistent replication information for virtual agent " + virtualAid.getLocalName() + ": current-master = " + info.getMaster().getLocalName() + ", new-master = " + masterAid.getLocalName()); + if (name.equals(Service.REATTACHED)) { + // The Main lost all information related to this container --> Notify it again + handleReattached(); } } + // Never veto a Command + return true; } - addReplicaVirtualMapping(masterAid, virtualAid); - return info; - } - - private ContainerID getAgentLocation(AID aid) throws NotFoundException { - MainContainer impl = myContainer.getMain(); - if (impl != null) { - return impl.getContainerID(aid); - } else { - // Should never happen - throw new NotFoundException("getAgentLocation() invoked on a non-main container"); - } - } - private void handleMasterReplicaDead(GlobalReplicationInfo info) { - // No need to check if impl is null since this can only be executed on a Main Container - MainContainer impl = myContainer.getMain(); - do { - AID newMasterAid = info.masterReplicaDead(); - if (newMasterAid != null) { - // New master replica selected. Check if it is actually alive. Otherwise try again - if (impl.acquireAgentDescriptor(newMasterAid) != null) { - // New master replica alive --> Broadcast the change to all other slices - impl.releaseAgentDescriptor(newMasterAid); - broadcastMasterReplicaChanged(info.getVirtual(), newMasterAid); - // Then notify the selected agent that it became the new master - notifyBecomeMasterToMaster(newMasterAid); - return; - } - } else { - // This virtual agent does not have replicas anymore --> remove it - try { - impl.deadAgent(info.getVirtual(), false); - } catch (NotFoundException nfe) { - // Just ignore + private void handleInformKilled(AID deadAid) { + AID virtualAid = replicaToVirtualMap.remove(deadAid); + if (virtualAid != null) { + GlobalReplicationInfo info = globalReplications.get(virtualAid); + if (info != null) { + if (deadAid.equals(info.getMaster())) { + // The dead agent is the master replica of a virtual agent + handleMasterReplicaDead(info); + } else { + // The dead agent is a non-master replica --> Just notify the master + notifyReplicaRemovedToMaster(info.getMaster(), deadAid, null); + } } - broadcastVirtualAgentDead(info.getVirtual()); - return; } - } while (true); - } + } - private void checkAllReplications() { - // No need to check if impl is null since this can only be executed on a Main Container - MainContainer impl = myContainer.getMain(); - // For each virtual agent - // - check if the related master replica is still alive. - // If not handle the dead master replica case. - // - then for each replica check if it is still alive. If not notify the master - GlobalReplicationInfo[] gg = globalReplications.values().toArray(new GlobalReplicationInfo[0]); - for (GlobalReplicationInfo info : gg) { - // Check master - AID masterAid = info.getMaster(); - if (impl.acquireAgentDescriptor(masterAid) != null) { - // Master replica still there --> nothing to do - impl.releaseAgentDescriptor(masterAid); - myLogger.log(Logger.INFO, "Master replica " + masterAid.getLocalName() + " of virtual agent " + info.getVirtual().getLocalName() + " ALIVE"); - } else { - // Master replica is not there anymore --> DEAD - handleMasterReplicaDead(info); - masterAid = info.getMaster(); + private void handleNewSlice(String newSliceName) { + try { + // Be sure to get the new (fresh) slice --> Bypass the service cache + AgentReplicationSlice newSlice = (AgentReplicationSlice) getFreshSlice(newSliceName); + GlobalReplicationInfo[] allInfos = globalReplications.values().toArray(new GlobalReplicationInfo[0]); + + for (GlobalReplicationInfo info : allInfos) { + newSlice.synchReplication(info); + } + } catch (Throwable t) { + myLogger.log(Logger.WARNING, "Error notifying new slice " + newSliceName + " about current replication information", t); } + } - // Check other replicas - AID[] allReplicas = info.getAllReplicas(); - for (AID replicaAid : allReplicas) { - if (!replicaAid.equals(masterAid)) { - if (impl.acquireAgentDescriptor(replicaAid) != null) { - // Replica still there --> nothing to do - impl.releaseAgentDescriptor(replicaAid); - myLogger.log(Logger.INFO, "Replica " + replicaAid.getLocalName() + " of virtual agent " + info.getVirtual().getLocalName() + " ALIVE"); - } else { - // Replica is not there anymore --> DEAD - notifyReplicaRemovedToMaster(masterAid, replicaAid, null); + private void handleReattached() { + try { + // Be sure to get a fresh slice --> Bypass the service cache + AgentReplicationSlice mainSlice = (AgentReplicationSlice) getFreshSlice(MAIN_SLICE); + // Notify the new Main Slice all replication information related to virtual agents + // for which an implementation replica lives in the local container. + // NOTE that the same replication information can be notified to the new Main Slice + // by more than one container, but this case is properly taken into account so + // that duplications are avoided. + AID[] aa = replicaToVirtualMap.keySet().toArray(new AID[0]); + List vv = new ArrayList<>(); + for (AID aid : aa) { + if (myContainer.isLocalAgent(aid)) { + AID virtualAid = replicaToVirtualMap.get(aid); + if (virtualAid != null && !vv.contains(virtualAid)) { + GlobalReplicationInfo info = globalReplications.get(virtualAid); + if (info != null) { + try { + mainSlice.synchReplication(info); + } catch (Exception e) { + myLogger.log(Logger.WARNING, "Error notifying main slice about current local replication information", e); + } + } + vv.add(virtualAid); + } } } + } catch (Throwable t) { + myLogger.log(Logger.WARNING, "Error retrieving main slice.", t); } } - } + } // END of inner class CommandIncomingFilter + + /** + * Inner class ReplicaInfo + */ + private class ReplicaInfo { + private final AID replicaAid; + private Location where; + + private ReplicaInfo(AID replicaAid, Location where) { + this.replicaAid = replicaAid; + this.where = where; + } + @Override + public int hashCode() { + return replicaAid.hashCode(); + } + + @Override + public boolean equals(Object obj) { + return replicaAid.equals(((ReplicaInfo) obj).replicaAid); + } + } // END of inner class ReplicaInfo /** * Inner class ServiceComponent @@ -1016,32 +1020,27 @@ public VerticalCommand serve(HorizontalCommand cmd) { String methodName = (String) cmd.getParam(1); Object[] arguments = (Object[]) cmd.getParam(2); invokeAgentMethod(aid, methodName, arguments); - break; } case AgentReplicationSlice.H_ADDREPLICA -> { AID virtualAid = (AID) cmd.getParam(0); AID replicaAid = (AID) cmd.getParam(1); Location where = (Location) cmd.getParam(2); addReplica(virtualAid, replicaAid, where); - break; } case AgentReplicationSlice.H_NEWVIRTUALAGENT -> { AID virtualAid = (AID) cmd.getParam(0); AID masterAid = (AID) cmd.getParam(1); int replicationMode = (Integer) cmd.getParam(2); newVirtualAgent(virtualAid, masterAid, replicationMode); - break; } case AgentReplicationSlice.H_GETAGENTLOCATION -> { AID aid = (AID) cmd.getParam(0); cmd.setReturnValue(getAgentLocation(aid)); - break; } case AgentReplicationSlice.H_REPLICACREATIONREQUESTED -> { AID virtualAid = (AID) cmd.getParam(0); AID replicaAid = (AID) cmd.getParam(1); addReplicaVirtualMapping(replicaAid, virtualAid); - break; } case AgentReplicationSlice.H_SYNCHREPLICATION -> { AID virtualAid = (AID) cmd.getParam(0); @@ -1058,7 +1057,6 @@ public VerticalCommand serve(HorizontalCommand cmd) { addReplicaVirtualMapping(replicaAid, virtualAid); } } - break; } case AgentReplicationSlice.H_MASTERREPLICACHANGED -> { AID virtualAid = (AID) cmd.getParam(0); @@ -1067,25 +1065,21 @@ public VerticalCommand serve(HorizontalCommand cmd) { if (info != null) { info.masterReplicaChanged(newMasterAid); } - break; } case AgentReplicationSlice.H_VIRTUALAGENTDEAD -> { AID virtualAid = (AID) cmd.getParam(0); globalReplications.remove(virtualAid); myLogger.log(Logger.CONFIG, "Virtual agent " + virtualAid.getLocalName() + " removed"); - break; } case AgentReplicationSlice.H_NOTIFYBECOMEMASTER -> { AID newMasterAid = (AID) cmd.getParam(0); localNotifyBecomeMasterToMaster(newMasterAid); - break; } case AgentReplicationSlice.H_NOTIFYREPLICAREMOVED -> { AID masterAid = (AID) cmd.getParam(0); AID removedReplica = (AID) cmd.getParam(1); Location where = (Location) cmd.getParam(2); localNotifyReplicaRemovedToMaster(masterAid, removedReplica, where); - break; } } } catch (Throwable t) { @@ -1096,25 +1090,5 @@ public VerticalCommand serve(HorizontalCommand cmd) { } // END of inner class ServiceComponent - private Method getMethod(Agent agent, String methodName) throws NoSuchMethodException { - String key = agent.getLocalName() + '#' + methodName; - Method m = cachedAgentMethods.get(key); - if (m == null) { - // NOTE: We cannot use Class.getMethod() since we have parameter values, but not parameter types - Method[] mm = agent.getClass().getMethods(); - for (Method method : mm) { - if (method.getName().equals(methodName)) { - m = method; - cachedAgentMethods.put(key, m); - break; - } - } - } - if (m == null) { - throw new NoSuchMethodException(methodName); - } - return m; - } - } diff --git a/src/jade/core/replication/GlobalReplicationInfo.java b/src/jade/core/replication/GlobalReplicationInfo.java index 994f13a..b58e16a 100644 --- a/src/jade/core/replication/GlobalReplicationInfo.java +++ b/src/jade/core/replication/GlobalReplicationInfo.java @@ -30,11 +30,10 @@ class GlobalReplicationInfo implements Serializable { private final AID virtualAid; - private AID masterAid; private final int replicationMode; private final RoundList allReplicas = new RoundList(); - private final Logger myLogger = Logger.getJADELogger(getClass().getName()); + private AID masterAid; GlobalReplicationInfo(AID virtual, AID master, int replicationMode) { this.virtualAid = virtual; diff --git a/src/jade/core/replication/MainReplicationHandle.java b/src/jade/core/replication/MainReplicationHandle.java index 2b1acdd..25e0cc7 100644 --- a/src/jade/core/replication/MainReplicationHandle.java +++ b/src/jade/core/replication/MainReplicationHandle.java @@ -36,9 +36,8 @@ public class MainReplicationHandle { //#J2ME_EXCLUDE_BEGIN private final String myService; - private MainReplicationService replicationService; - private final Logger myLogger = Logger.getMyLogger(getClass().getName()); + private MainReplicationService replicationService; //#J2ME_EXCLUDE_END public MainReplicationHandle(Service svc, ServiceFinder sf) { diff --git a/src/jade/core/replication/MainReplicationProxy.java b/src/jade/core/replication/MainReplicationProxy.java index 236e4b8..aea7915 100644 --- a/src/jade/core/replication/MainReplicationProxy.java +++ b/src/jade/core/replication/MainReplicationProxy.java @@ -45,7 +45,7 @@ public int getLabel() throws IMTPException { Node n = getNode(); Object result = n.accept(cmd); - if ((result != null) && (result instanceof Throwable)) { + if ((result instanceof Throwable)) { if (result instanceof IMTPException) { throw (IMTPException) result; } else { @@ -65,7 +65,7 @@ public String getPlatformManagerAddress() throws IMTPException { Node n = getNode(); Object result = n.accept(cmd); - if ((result != null) && (result instanceof Throwable)) { + if ((result instanceof Throwable)) { if (result instanceof IMTPException) { throw (IMTPException) result; } else { @@ -130,7 +130,7 @@ public void fillGADT(AID[] agents, ContainerID[] containers) throws IMTPExceptio Node n = getNode(); Object result = n.accept(cmd); - if ((result != null) && (result instanceof Throwable)) { + if ((result instanceof Throwable)) { if (result instanceof IMTPException) { throw (IMTPException) result; } else { @@ -205,7 +205,7 @@ public void suspendedAgent(AID name) throws IMTPException, NotFoundException { Node n = getNode(); Object result = n.accept(cmd); - if ((result != null) && (result instanceof Throwable)) { + if ((result instanceof Throwable)) { if (result instanceof IMTPException) { throw (IMTPException) result; } else if (result instanceof NotFoundException) { @@ -295,7 +295,7 @@ public void newTool(AID tool) throws IMTPException { Node n = getNode(); Object result = n.accept(cmd); - if ((result != null) && (result instanceof Throwable)) { + if ((result instanceof Throwable)) { if (result instanceof IMTPException) { throw (IMTPException) result; } else { diff --git a/src/jade/core/replication/MainReplicationService.java b/src/jade/core/replication/MainReplicationService.java index 09b2d0a..c1ce77b 100644 --- a/src/jade/core/replication/MainReplicationService.java +++ b/src/jade/core/replication/MainReplicationService.java @@ -63,6 +63,17 @@ public class MainReplicationService extends BaseService { private static final boolean INCLUDE_MYSELF = true; private static final String[] OWNED_COMMANDS = new String[]{MainReplicationSlice.LEADERSHIP_ACQUIRED}; + private final List replicas = new LinkedList<>(); + private final Map cachedServiceMethods = new HashMap<>(); + private AgentContainer myContainer; + private ServiceComponent localSlice; + private Filter outFilter; + private Filter inFilter; + private int myLabel = -1; + private boolean snapshotOnFailure = false; + // Owned copies of Main Container and Service Manager + private MainContainerImpl myMain; + private PlatformManagerImpl myPlatformManager; public void init(AgentContainer ac, Profile p) throws ProfileException { super.init(ac, p); @@ -173,6 +184,57 @@ protected int checkConnectivity(Node unreachableNode) { return REMOVE_NODE; } + void broadcastToReplicas(HorizontalCommand cmd, boolean includeSelf) throws IMTPException, ServiceException { + Object[] slices = replicas.toArray(); + + String localNodeName = getLocalNode().getName(); + for (Object o : slices) { + MainReplicationSlice slice = (MainReplicationSlice) o; + + String sliceName = slice.getNode().getName(); + if (includeSelf || !sliceName.equals(localNodeName)) { + slice.serve(cmd); + Object ret = cmd.getReturnValue(); + if (ret instanceof Throwable) { + // FIXME: This may happen due to the fact that the replica is terminating. E.g. a tool running on + // the terminating replica that deregisters from the AMS: the DeadTool event may be processed + // when the replica is already dead. In these cases we should find a way to hide the exception + myLogger.log(Logger.SEVERE, "Error propagating H-command " + cmd.getName() + " to slice " + sliceName, (Throwable) ret); + } + } + } + } + + public String dump(String key) { + StringBuilder sb = new StringBuilder(); + sb.append("- Replicas:\n"); + try { + Object[] slices = replicas.toArray(); + String localNodeName = getLocalNode().getName(); + for (Object o : slices) { + MainReplicationSlice slice = (MainReplicationSlice) o; + String sliceName = slice.getNode().getName(); + if (!sliceName.equals(localNodeName)) { + sb.append(" - ").append(sliceName).append("\n"); + } + } + } catch (Exception e) { + e.printStackTrace(); + sb.append(e); + } + sb.append("- Label = ").append(myLabel).append("\n"); + sb.append("- Monitored Label = ").append(localSlice.monitoredLabel).append("\n"); + sb.append("- Monitored PlatformManager replica = ").append(localSlice.monitoredSvcMgr).append("\n"); + String monitoredNodeStr = "UNKNOWN(Monitor null)"; + if (localSlice.nodeMonitor != null) { + Node n = localSlice.nodeMonitor.getNode(); + monitoredNodeStr = (n != null ? n.getName() : "null"); + } + sb.append("- Monitored Node = ").append(monitoredNodeStr).append("\n"); + sb.append(super.dump(key)); + return (sb.toString()); + } + /** * Inner class CommandOutgoingFilter * Keep tool agents information in synch among replicas @@ -226,7 +288,6 @@ private void handleOrphanNode(VerticalCommand cmd) throws IMTPException, Service } } // End of CommandOutgoingFilter class - /** * Inner class CommandIncomingFilter * Keep agents and MTPs information in synch among replicas @@ -252,7 +313,7 @@ public void postProcess(VerticalCommand cmd) { private void handleInformCreated(VerticalCommand cmd) throws IMTPException, NotFoundException, NameClashException, JADESecurityException, ServiceException { Object ret = cmd.getReturnValue(); // Avoid propagating to other slices in case the agent creation failed due to a name-clash - if (!(ret != null && ret instanceof NameClashException)) { + if (!(ret instanceof NameClashException)) { Object[] params = cmd.getParams(); AID agentID = (AID) params[0]; @@ -322,12 +383,21 @@ private void handleDeadMTP(VerticalCommand cmd) throws IMTPException, ServiceExc } } // End of CommandIncomingFilter class - /** * Inner class ServiceComponent */ private class ServiceComponent implements Slice, NodeEventListener { + // The active object monitoring the remote node + NodeFailureMonitor nodeMonitor; + // The integer label of the monitored slice + int monitoredLabel; + String monitoredSvcMgr; + + // Implementation of the Service.Slice interface + private Node toBeMonitored; + private boolean monitoredNodeUnreachable = false; + public ServiceComponent() { myMain = (MainContainerImpl) myContainer.getMain(); myPlatformManager = (PlatformManagerImpl) myMain.getPlatformManager(); @@ -361,8 +431,6 @@ private void attachTo(int label, MainReplicationSlice slice) throws IMTPExceptio nodeMonitor.start(slice.getNode(), this); } - // Implementation of the Service.Slice interface - public Service getService() { return MainReplicationService.this; } @@ -519,8 +587,8 @@ private void addReplica(String sliceName, String smAddr, int sliceIndex, NodeDes amsd.setState(AMSAgentDescription.SUSPENDED); List suspendedAgents = myMain.amsSearch(amsd, -1); // '-1' means 'all the results' - for (Object suspendedAgent : suspendedAgents) { - AMSAgentDescription desc = (AMSAgentDescription) suspendedAgent; + for (AMSAgentDescription suspendedAgent : suspendedAgents) { + AMSAgentDescription desc = suspendedAgent; try { slice.suspendedAgent(desc.getName()); } catch (NotFoundException nfe) { @@ -641,6 +709,8 @@ private void newMTP(MTPDescriptor mtp, ContainerID cid) throws IMTPException { myMain.newMTP(mtp, cid); } + // Implementation of the NodeEventListener interface + private void deadMTP(MTPDescriptor mtp, ContainerID cid) throws IMTPException { myMain.deadMTP(mtp, cid); } @@ -678,8 +748,6 @@ private void dumpGADT() { System.out.println("------------------"); } - // Implementation of the NodeEventListener interface - public void nodeAdded(Node n) { myLogger.log(Logger.INFO, "Start monitoring main node <" + n.getName() + ">"); monitoredNodeUnreachable = false; @@ -783,83 +851,5 @@ private void handleOrphanNode(String nodeId) { } } - // The active object monitoring the remote node - NodeFailureMonitor nodeMonitor; - - // The integer label of the monitored slice - int monitoredLabel; - - String monitoredSvcMgr; - private Node toBeMonitored; - private boolean monitoredNodeUnreachable = false; - } // End of ServiceComponent class - - private AgentContainer myContainer; - - private ServiceComponent localSlice; - - private Filter outFilter; - private Filter inFilter; - - private int myLabel = -1; - private final List replicas = new LinkedList<>(); - private boolean snapshotOnFailure = false; - - // Owned copies of Main Container and Service Manager - private MainContainerImpl myMain; - private PlatformManagerImpl myPlatformManager; - - private final Map cachedServiceMethods = new HashMap<>(); - - void broadcastToReplicas(HorizontalCommand cmd, boolean includeSelf) throws IMTPException, ServiceException { - Object[] slices = replicas.toArray(); - - String localNodeName = getLocalNode().getName(); - for (Object o : slices) { - MainReplicationSlice slice = (MainReplicationSlice) o; - - String sliceName = slice.getNode().getName(); - if (includeSelf || !sliceName.equals(localNodeName)) { - slice.serve(cmd); - Object ret = cmd.getReturnValue(); - if (ret instanceof Throwable) { - // FIXME: This may happen due to the fact that the replica is terminating. E.g. a tool running on - // the terminating replica that deregisters from the AMS: the DeadTool event may be processed - // when the replica is already dead. In these cases we should find a way to hide the exception - myLogger.log(Logger.SEVERE, "Error propagating H-command " + cmd.getName() + " to slice " + sliceName, (Throwable) ret); - } - } - } - } - - public String dump(String key) { - StringBuilder sb = new StringBuilder(); - sb.append("- Replicas:\n"); - try { - Object[] slices = replicas.toArray(); - String localNodeName = getLocalNode().getName(); - for (Object o : slices) { - MainReplicationSlice slice = (MainReplicationSlice) o; - String sliceName = slice.getNode().getName(); - if (!sliceName.equals(localNodeName)) { - sb.append(" - ").append(sliceName).append("\n"); - } - } - } catch (Exception e) { - e.printStackTrace(); - sb.append(e); - } - sb.append("- Label = ").append(myLabel).append("\n"); - sb.append("- Monitored Label = ").append(localSlice.monitoredLabel).append("\n"); - sb.append("- Monitored PlatformManager replica = ").append(localSlice.monitoredSvcMgr).append("\n"); - String monitoredNodeStr = "UNKNOWN(Monitor null)"; - if (localSlice.nodeMonitor != null) { - Node n = localSlice.nodeMonitor.getNode(); - monitoredNodeStr = (n != null ? n.getName() : "null"); - } - sb.append("- Monitored Node = ").append(monitoredNodeStr).append("\n"); - sb.append(super.dump(key)); - return (sb.toString()); - } } diff --git a/src/jade/core/resource/ResourceManagementProxy.java b/src/jade/core/resource/ResourceManagementProxy.java index 0dc036e..6248a5a 100644 --- a/src/jade/core/resource/ResourceManagementProxy.java +++ b/src/jade/core/resource/ResourceManagementProxy.java @@ -40,7 +40,7 @@ public byte[] getResource(String name, int fetchMode) throws Exception { Node n = getNode(); Object result = n.accept(cmd); - if ((result != null) && (result instanceof Throwable)) { + if ((result instanceof Throwable)) { if (result instanceof Exception) { throw (Exception) result; } else { diff --git a/src/jade/core/resource/ResourceManagementService.java b/src/jade/core/resource/ResourceManagementService.java index 27b3f79..4ff8c24 100644 --- a/src/jade/core/resource/ResourceManagementService.java +++ b/src/jade/core/resource/ResourceManagementService.java @@ -44,6 +44,10 @@ public class ResourceManagementService extends BaseService { private ServiceComponent localSlice; private ResourceManagementHelper helper; + public static ResourceManagementHelper getHelper() { + return SingletonResourceManagementHelper.getInstance().getHelper(); + } + @Override public void init(AgentContainer ac, Profile p) throws ProfileException { super.init(ac, p); @@ -84,11 +88,6 @@ public ServiceHelper getHelper(Agent a) { return helper; } - public static ResourceManagementHelper getHelper() { - return SingletonResourceManagementHelper.getInstance().getHelper(); - } - - /** * Inner class ServiceComponent */ diff --git a/src/jade/core/resource/SingletonResourceManagementHelper.java b/src/jade/core/resource/SingletonResourceManagementHelper.java index 41bfe39..1aed3b6 100644 --- a/src/jade/core/resource/SingletonResourceManagementHelper.java +++ b/src/jade/core/resource/SingletonResourceManagementHelper.java @@ -30,18 +30,17 @@ class SingletonResourceManagementHelper { + private final static SingletonResourceManagementHelper theInstance = new SingletonResourceManagementHelper(); private final List helpers; - private final static SingletonResourceManagementHelper theInstance = new SingletonResourceManagementHelper(); + private SingletonResourceManagementHelper() { + helpers = new ArrayList<>(); + } public final static SingletonResourceManagementHelper getInstance() { return theInstance; } - private SingletonResourceManagementHelper() { - helpers = new ArrayList<>(); - } - public void addHelper(ResourceManagementHelper helper) { helpers.add(helper); } diff --git a/src/jade/core/sam/DefaultSAMInfoHandlerImpl.java b/src/jade/core/sam/DefaultSAMInfoHandlerImpl.java index af5e9a6..90972e6 100644 --- a/src/jade/core/sam/DefaultSAMInfoHandlerImpl.java +++ b/src/jade/core/sam/DefaultSAMInfoHandlerImpl.java @@ -41,18 +41,14 @@ class DefaultSAMInfoHandlerImpl implements SAMInfoHandler { private final Map counters = new HashMap<>(); private final SimpleDateFormat timeStampFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm"); + private final Logger myLogger = Logger.getMyLogger(getClass().getName()); private String csvSeparator; - private List summaryFields = null; private List summaryValues = null; private PrintStream summaryFile = null; - - private File samInfoDirectory; private String fileSeparator; - private final Logger myLogger = Logger.getMyLogger(getClass().getName()); - public void initialize(Profile p) throws Exception { fileSeparator = System.getProperty("file.separator"); diff --git a/src/jade/core/sam/Poller.java b/src/jade/core/sam/Poller.java index 5dd0069..45d5e06 100644 --- a/src/jade/core/sam/Poller.java +++ b/src/jade/core/sam/Poller.java @@ -33,12 +33,11 @@ class Poller extends Thread { private final SAMService myService; - private volatile SAMInfoHandler[] handlers; private final long period; + private final Logger myLogger = Logger.getMyLogger(getClass().getName()); + private volatile SAMInfoHandler[] handlers; private boolean active; - private Timer watchDogTimer = null; - private final Logger myLogger = Logger.getMyLogger(getClass().getName()); Poller(SAMService service, long p, SAMInfoHandler[] hh) { super(); diff --git a/src/jade/core/sam/SAMInfo.java b/src/jade/core/sam/SAMInfo.java index 775eab3..2983ac0 100644 --- a/src/jade/core/sam/SAMInfo.java +++ b/src/jade/core/sam/SAMInfo.java @@ -36,19 +36,16 @@ * polling time. */ public class SAMInfo implements Serializable { - @Serial - private static final long serialVersionUID = 84762938792387L; - public static final String DEFAULT_AGGREGATION_SEPARATOR = "#"; public static final char DEFAULT_AGGREGATION_SEPARATOR_CHAR = '#'; public static final String SUM_AGGREGATION_SEPARATOR = "+"; public static final char SUM_AGGREGATION_SEPARATOR_CHAR = '+'; public static final String AVG_AGGREGATION_SEPARATOR = "@"; public static final char AVG_AGGREGATION_SEPARATOR_CHAR = '@'; - public static final int AVG_AGGREGATION = 0; public static final int SUM_AGGREGATION = 1; - + @Serial + private static final long serialVersionUID = 84762938792387L; private final Map entityMeasures; private final Map counterValues; @@ -62,67 +59,6 @@ public class SAMInfo implements Serializable { this.counterValues = counterValues; } - /** - * Provides the measures of all monitored entities in form of a Map. - * - * @return A Map mapping monitored entity names to their measures - */ - public Map getEntityMeasures() { - return entityMeasures; - } - - /** - * Provides the differential values of all monitored counters in form of a Map. - * - * @return A Map mapping monitored counter names to their differential values - */ - public Map getCounterValues() { - return counterValues; - } - - void update(SAMInfo info) { - // Update entity measures - Map mm = info.getEntityMeasures(); - for (String entityName : mm.keySet()) { - AverageMeasure newM = mm.get(entityName); - // If this is a new entity --> add it. Otherwise update the measure we have internally - AverageMeasure m = entityMeasures.get(entityName); - if (m == null) { - entityMeasures.put(entityName, newM); - } else { - m.update(newM); - } - } - - // Update counter values - Map vv = info.getCounterValues(); - for (String counterName : vv.keySet()) { - long newV = vv.get(counterName); - // If this is a new counter --> add it. Otherwise sum to the value we have internally - counterValues.merge(counterName, newV, Long::sum); - } - } - - /** - * If there are entities/counters of the form a#b, a#c... produce an aggregated entity a. - * Since a itself may have the form a1#a2, iterate until there are no more aggregations - */ - void computeAggregatedValues() { - // Aggregate measures - Map aggregatedMeasures = oneShotComputeAggregatedMeasures(entityMeasures); - while (aggregatedMeasures.size() > 0) { - addAllMeasures(aggregatedMeasures, entityMeasures); - aggregatedMeasures = oneShotComputeAggregatedMeasures(aggregatedMeasures); - } - - // Aggregate counters - Map aggregatedCounters = oneShotComputeAggregatedCounters(counterValues); - while (aggregatedCounters.size() > 0) { - addAllCounters(aggregatedCounters, counterValues); - aggregatedCounters = oneShotComputeAggregatedCounters(aggregatedCounters); - } - } - private static Map oneShotComputeAggregatedMeasures(Map measures) { Map aggregatedMeasures = new HashMap<>(); for (String entityName : measures.keySet()) { @@ -189,7 +125,6 @@ private static void addAllCounters(Map cc1, Map cc2) } } - public static final AggregationInfo getAggregationInfo(String name, int defaultAggregation) { for (int i = name.length() - 1; i >= 0; --i) { AggregationInfo ai = null; @@ -211,6 +146,66 @@ public static final AggregationInfo getAggregationInfo(String name, int defaultA return null; } + /** + * Provides the measures of all monitored entities in form of a Map. + * + * @return A Map mapping monitored entity names to their measures + */ + public Map getEntityMeasures() { + return entityMeasures; + } + + /** + * Provides the differential values of all monitored counters in form of a Map. + * + * @return A Map mapping monitored counter names to their differential values + */ + public Map getCounterValues() { + return counterValues; + } + + void update(SAMInfo info) { + // Update entity measures + Map mm = info.getEntityMeasures(); + for (String entityName : mm.keySet()) { + AverageMeasure newM = mm.get(entityName); + // If this is a new entity --> add it. Otherwise update the measure we have internally + AverageMeasure m = entityMeasures.get(entityName); + if (m == null) { + entityMeasures.put(entityName, newM); + } else { + m.update(newM); + } + } + + // Update counter values + Map vv = info.getCounterValues(); + for (String counterName : vv.keySet()) { + long newV = vv.get(counterName); + // If this is a new counter --> add it. Otherwise sum to the value we have internally + counterValues.merge(counterName, newV, Long::sum); + } + } + + /** + * If there are entities/counters of the form a#b, a#c... produce an aggregated entity a. + * Since a itself may have the form a1#a2, iterate until there are no more aggregations + */ + void computeAggregatedValues() { + // Aggregate measures + Map aggregatedMeasures = oneShotComputeAggregatedMeasures(entityMeasures); + while (aggregatedMeasures.size() > 0) { + addAllMeasures(aggregatedMeasures, entityMeasures); + aggregatedMeasures = oneShotComputeAggregatedMeasures(aggregatedMeasures); + } + + // Aggregate counters + Map aggregatedCounters = oneShotComputeAggregatedCounters(counterValues); + while (aggregatedCounters.size() > 0) { + addAllCounters(aggregatedCounters, counterValues); + aggregatedCounters = oneShotComputeAggregatedCounters(aggregatedCounters); + } + } /** * Inner class AggregationInfo diff --git a/src/jade/core/sam/SAMService.java b/src/jade/core/sam/SAMService.java index f1f9def..3331972 100644 --- a/src/jade/core/sam/SAMService.java +++ b/src/jade/core/sam/SAMService.java @@ -39,20 +39,22 @@ public class SAMService extends BaseService { public static final String SAM_INFO_HANDLERS = "jade_core_sam_SAMService_handlers"; public static final String SAM_INFO_HANDLERS_DEFAULT = "jade.core.sam.DefaultSAMInfoHandlerImpl"; - + private static final Object singletonLock = new Object(); + private static SAMHelper singletonHelper; private final List monitoredEntities = new ArrayList<>(); private final List monitoredCounters = new ArrayList<>(); - - private Poller poller; - private final SAMHelper myHelper = new SAMHelperImpl(); - private static final Object singletonLock = new Object(); - private static SAMHelper singletonHelper; private final ServiceComponent localSlice = new ServiceComponent(); + private Poller poller; private Filter outgoingFilter = null; private Profile myProfile; + public static SAMHelper getSingletonHelper() { + synchronized (singletonLock) { + return singletonHelper; + } + } public String getName() { return SAMHelper.SERVICE_NAME; @@ -156,12 +158,6 @@ public ServiceHelper getHelper(Agent a) { return myHelper; } - public static SAMHelper getSingletonHelper() { - synchronized (singletonLock) { - return singletonHelper; - } - } - @Override public Class getHorizontalInterface() { return SAMSlice.class; @@ -194,6 +190,29 @@ private Map getCounterValues() { } } + private EntityInfo getEntityInfo(String entityName) { + for (EntityInfo info : monitoredEntities) { + if (info.getName().equals(entityName)) { + return info; + } + } + // Entity not found --> create it + EntityInfo info = new EntityInfo(entityName); + monitoredEntities.add(info); + return info; + } + + private CounterInfo getCounterInfo(String counterName) { + for (CounterInfo info : monitoredCounters) { + if (info.getName().equals(counterName)) { + return info; + } + } + // Counter not found --> create it + CounterInfo info = new CounterInfo(counterName); + monitoredCounters.add(info); + return info; + } /** * Inner class SAMHelperImpl @@ -244,7 +263,6 @@ public void init(Agent a) { } } // END of inner class SAMHelperImpl - /** * Inner class ServiceComponent */ @@ -278,7 +296,6 @@ public VerticalCommand serve(HorizontalCommand cmd) { } } // END of inner class ServiceComponent - /** * Inner class EntityInfo */ @@ -308,19 +325,6 @@ AverageMeasure getMeasure() { } } // END of inner class EntityInfo - private EntityInfo getEntityInfo(String entityName) { - for (EntityInfo info : monitoredEntities) { - if (info.getName().equals(entityName)) { - return info; - } - } - // Entity not found --> create it - EntityInfo info = new EntityInfo(entityName); - monitoredEntities.add(info); - return info; - } - - /** * Inner class CounterInfo */ @@ -359,16 +363,4 @@ long getValue() { return result; } } // END of inner class CounterInfo - - private CounterInfo getCounterInfo(String counterName) { - for (CounterInfo info : monitoredCounters) { - if (info.getName().equals(counterName)) { - return info; - } - } - // Counter not found --> create it - CounterInfo info = new CounterInfo(counterName); - monitoredCounters.add(info); - return info; - } } diff --git a/src/jade/domain/AMSService.java b/src/jade/domain/AMSService.java index 2286bfe..7e1ea04 100644 --- a/src/jade/domain/AMSService.java +++ b/src/jade/domain/AMSService.java @@ -85,6 +85,12 @@ public class AMSService extends FIPAService { cm.registerOntology(o); } + /** + * Default constructor. + */ + public AMSService() { + } + /** * check that the AMSAgentDescription contains the mandatory * slots, i.e. the agent name and the agent state. @@ -147,7 +153,6 @@ public static void register(Agent a, AID AMSName, AMSAgentDescription amsd) thro doFipaRequestClient(a, request); } - /** * registers a AMSAgentDescription with the default AMS * @@ -232,7 +237,6 @@ public static void deregister(Agent a) throws FIPAException { deregister(a, amsd); } - /** * Modifies data contained within a AMS * agent. @@ -379,7 +383,6 @@ public static AMSAgentDescription[] search(Agent a, AID AMSName, AMSAgentDescrip return search(a, AMSName, amsd, constraints); } - /** * In some cases it is more convenient to execute this tasks in a non-blocking way. * This method returns a non-blocking behaviour that can be added to the queue of the agent behaviours, as usual, by using Agent.addBehaviour(). @@ -459,6 +462,7 @@ public static RequestFIPAServiceBehaviour getNonBlockingBehaviour(Agent a, Strin SearchConstraints constraints = new SearchConstraints(); return getNonBlockingBehaviour(a, a.getAMS(), actionName, amsd, constraints); } + //#MIDP_EXCLUDE_END /** * the default AMS is used. @@ -471,8 +475,6 @@ public static RequestFIPAServiceBehaviour getNonBlockingBehaviour(Agent a, AID a SearchConstraints constraints = new SearchConstraints(); return getNonBlockingBehaviour(a, amsName, actionName, amsd, constraints); } - //#MIDP_EXCLUDE_END - /** * Extracts the receiver a message could not be delivered to from @@ -529,11 +531,5 @@ public static String getFailureReason(Agent a, ACLMessage failure) throws FIPAEx throw new FIPAException("Invalid content. " + e); } } - - /** - * Default constructor. - */ - public AMSService() { - } } diff --git a/src/jade/domain/DFDBKB.java b/src/jade/domain/DFDBKB.java index a153902..dc9d57c 100644 --- a/src/jade/domain/DFDBKB.java +++ b/src/jade/domain/DFDBKB.java @@ -73,137 +73,17 @@ public class DFDBKB extends DBKB { private static final String AGENTRESOLVER = "agentresolver"; private static final String AGENTADDRESS = "agentaddress"; private static final String DFAGENTDESCR = "dfagentdescr"; - - // Number of registrations after the last lease-time-cleanup - private int regsCnt = 0; - - private boolean tablesReady = false; - + private final StringACLCodec codec = new StringACLCodec(); /** * Default data type for very long strings */ protected String DEFAULT_LONGVARCHAR_TYPE = "LONGVARCHAR"; - + // Number of registrations after the last lease-time-cleanup + private int regsCnt = 0; + private boolean tablesReady = false; // This is used to generate unique IDs private String localIPAddress; - private static class PreparedStatements { - // prepared SQL statements - private final PreparedStatement stm_selNrOfPropForKey; - private final PreparedStatement stm_selNrOfDescrForAID; - private final PreparedStatement stm_selAgentAddresses; - private final PreparedStatement stm_selAgentResolverAIDs; - private final PreparedStatement stm_selAgentUserDefSlot; - private final PreparedStatement stm_selLease; - private final PreparedStatement stm_selProtocols; - private final PreparedStatement stm_selLanguages; - private final PreparedStatement stm_selOntologies; - private final PreparedStatement stm_selServices; - private final PreparedStatement stm_selServiceProtocols; - private final PreparedStatement stm_selServiceLanguages; - private final PreparedStatement stm_selServiceOntologies; - private final PreparedStatement stm_selServiceProperties; - private final PreparedStatement stm_selExpiredDescr; - private final PreparedStatement stm_selSubscriptions; - - private final PreparedStatement stm_selAllProtocols; - private final PreparedStatement stm_selCountAllProtocols; - private final PreparedStatement stm_selAllLanguages; - private final PreparedStatement stm_selCountAllLanguages; - private final PreparedStatement stm_selAllOntologies; - private final PreparedStatement stm_selCountAllOntologies; - - private final PreparedStatement stm_insAgentDescr; - private final PreparedStatement stm_insAgentAddress; - private final PreparedStatement stm_insAgentUserDefSlot; - private final PreparedStatement stm_insAgentResolverAID; - private final PreparedStatement stm_insLanguage; - private final PreparedStatement stm_insOntology; - private final PreparedStatement stm_insProtocol; - private final PreparedStatement stm_insService; - private final PreparedStatement stm_insServiceProtocol; - private final PreparedStatement stm_insServiceOntology; - private final PreparedStatement stm_insServiceLanguage; - private final PreparedStatement stm_insServiceProperty; - private final PreparedStatement stm_insSubscription; - private final PreparedStatement stm_delAgentDescr; - private final PreparedStatement stm_delAgentUserDefSlot; - private final PreparedStatement stm_delAgentResolver; - private final PreparedStatement stm_delAgentAddress; - - private final PreparedStatement stm_selDescrId; - private final PreparedStatement stm_selServiceId; - private final PreparedStatement stm_delService; - private final PreparedStatement stm_delLanguage; - private final PreparedStatement stm_delProtocol; - private final PreparedStatement stm_delOntology; - - private final PreparedStatement stm_delServiceLanguage; - private final PreparedStatement stm_delServiceOntology; - private final PreparedStatement stm_delServiceProtocol; - private final PreparedStatement stm_delServiceProperty; - private final PreparedStatement stm_delSubscription; - - private PreparedStatements(Connection conn) throws SQLException { - // select statements - stm_selNrOfPropForKey = conn.prepareStatement("SELECT COUNT(*) FROM SERVICEPROPERTY where PROPKEY = ?"); - stm_selNrOfDescrForAID = conn.prepareStatement("SELECT COUNT(*) FROM dfagentdescr WHERE aid = ?"); - stm_selAgentAddresses = conn.prepareStatement("SELECT address FROM agentaddress WHERE aid = ?"); - stm_selAgentResolverAIDs = conn.prepareStatement("SELECT resolveraid FROM agentresolver WHERE aid = ?"); - stm_selAgentUserDefSlot = conn.prepareStatement("SELECT slotkey, slotval FROM agentuserdefslot WHERE aid = ?"); - stm_selLease = conn.prepareStatement("SELECT id, lease FROM dfagentdescr WHERE aid = ?"); - stm_selProtocols = conn.prepareStatement("SELECT protocol FROM protocol WHERE descrid = ?"); - stm_selLanguages = conn.prepareStatement("SELECT language FROM language WHERE descrid = ?"); - stm_selOntologies = conn.prepareStatement("SELECT ontology FROM ontology WHERE descrid = ?"); - stm_selServices = conn.prepareStatement("SELECT id, sname, stype, sownership FROM service WHERE descrid = ?"); - stm_selServiceProtocols = conn.prepareStatement("SELECT protocol FROM serviceprotocol WHERE serviceid = ?"); - stm_selServiceLanguages = conn.prepareStatement("SELECT ontology FROM serviceontology WHERE serviceid = ?"); - stm_selServiceOntologies = conn.prepareStatement("SELECT language FROM servicelanguage WHERE serviceid = ?"); - stm_selServiceProperties = conn.prepareStatement("SELECT propkey, propval_str, propval_obj FROM serviceproperty WHERE serviceid = ?"); - stm_selDescrId = conn.prepareStatement("SELECT id FROM dfagentdescr WHERE aid = ?"); - stm_selServiceId = conn.prepareStatement("SELECT id FROM service WHERE descrid = ?"); - stm_selExpiredDescr = conn.prepareStatement("SELECT aid FROM dfagentdescr WHERE lease < ? AND lease <> '-1'"); - stm_selSubscriptions = conn.prepareStatement("SELECT * FROM subscription"); - - stm_selAllProtocols = conn.prepareStatement("SELECT descrid, protocol FROM protocol ORDER BY descrid"); - stm_selCountAllProtocols = conn.prepareStatement("SELECT COUNT(*) FROM protocol"); - stm_selAllLanguages = conn.prepareStatement("SELECT descrid, language FROM language ORDER BY descrid"); - stm_selCountAllLanguages = conn.prepareStatement("SELECT COUNT(*) FROM language"); - stm_selAllOntologies = conn.prepareStatement("SELECT descrid, ontology FROM ontology ORDER BY descrid"); - stm_selCountAllOntologies = conn.prepareStatement("SELECT COUNT(*) FROM ontology"); - - stm_insAgentDescr = conn.prepareStatement("INSERT INTO dfagentdescr VALUES (?, ?, ?)"); - stm_insAgentAddress = conn.prepareStatement("INSERT INTO agentaddress VALUES (?, ?, ?)"); - stm_insAgentUserDefSlot = conn.prepareStatement("INSERT INTO agentuserdefslot VALUES (?, ?, ?, ?)"); - stm_insAgentResolverAID = conn.prepareStatement("INSERT INTO agentresolver VALUES (?, ?, ?)"); - stm_insLanguage = conn.prepareStatement("INSERT INTO language VALUES (?, ?)"); - stm_insOntology = conn.prepareStatement("INSERT INTO ontology VALUES (?, ?)"); - stm_insProtocol = conn.prepareStatement("INSERT INTO protocol VALUES (?, ?)"); - stm_insService = conn.prepareStatement("INSERT INTO service VALUES (?, ?, ?, ?, ?)"); - stm_insServiceProtocol = conn.prepareStatement("INSERT INTO serviceprotocol VALUES (?, ?)"); - stm_insServiceOntology = conn.prepareStatement("INSERT INTO serviceontology VALUES (?, ?)"); - stm_insServiceLanguage = conn.prepareStatement("INSERT INTO servicelanguage VALUES (?, ?)"); - stm_insServiceProperty = conn.prepareStatement("INSERT INTO serviceproperty VALUES (?, ?, ?, ?, ?)"); - stm_insSubscription = conn.prepareStatement("INSERT INTO subscription VALUES (?, ?)"); - - - // delete statements - stm_delAgentDescr = conn.prepareStatement("DELETE FROM dfagentdescr WHERE id = ?"); - stm_delAgentUserDefSlot = conn.prepareStatement("DELETE FROM agentuserdefslot WHERE aid = ?"); - stm_delAgentResolver = conn.prepareStatement("DELETE FROM agentresolver WHERE aid = ?"); - stm_delAgentAddress = conn.prepareStatement("DELETE FROM agentaddress WHERE aid = ?"); - stm_delLanguage = conn.prepareStatement("DELETE FROM language WHERE descrid = ?"); - stm_delProtocol = conn.prepareStatement("DELETE FROM protocol WHERE descrid = ?"); - stm_delOntology = conn.prepareStatement("DELETE FROM ontology WHERE descrid = ?"); - stm_delService = conn.prepareStatement("DELETE FROM service WHERE descrid = ?"); - stm_delServiceLanguage = conn.prepareStatement("DELETE FROM servicelanguage WHERE serviceid = ?"); - stm_delServiceOntology = conn.prepareStatement("DELETE FROM serviceontology WHERE serviceid = ?"); - stm_delServiceProtocol = conn.prepareStatement("DELETE FROM serviceprotocol WHERE serviceid = ?"); - stm_delServiceProperty = conn.prepareStatement("DELETE FROM serviceproperty WHERE serviceid = ?"); - stm_delSubscription = conn.prepareStatement("DELETE FROM subscription WHERE id = ?"); - } - } - /** * Constructor * @@ -219,6 +99,10 @@ public DFDBKB(int maxResultLimit, String drv, String url, String user, String pa super(drv, url, user, passwd, maxResultLimit, cleanTables); } + private static boolean needSerialization(Object value) { + return !((value instanceof String) && (((String) value).length() <= MAX_PROP_LENGTH)); + } + /** * Initializes all used SQL statements, the DB tables and the logging */ @@ -456,7 +340,6 @@ protected void createIndices() { } } - /** * Creates the proper DB tables. */ @@ -791,10 +674,6 @@ private void saveProperty(PreparedStatements pss, String serviceId, Property pro pss.stm_insServiceProperty.addBatch(); } - private static boolean needSerialization(Object value) { - return !((value instanceof String) && (((String) value).length() <= MAX_PROP_LENGTH)); - } - /** * Insert a new DFD object. * @@ -919,7 +798,7 @@ protected List searchSingle(DFAgentDescription template, int Statement s = null; try { - select = createSelect((DFAgentDescription) template); + select = createSelect(template); s = getConnectionWrapper().getConnection().createStatement(); if (maxResult >= 0) { @@ -1023,54 +902,6 @@ protected KBIterator iteratorSingle(Object template) throws SQLException { } } - - /** - * Inner class DFDBKBIterator - */ - private class DFDBKBIterator implements KBIterator { - private Statement s = null; - private ResultSet rs = null; - private boolean hasMoreElements = false; - - public DFDBKBIterator(Statement s, ResultSet rs) throws SQLException { - this.s = s; - this.rs = rs; - if (rs != null) { - // Move to the first row - hasMoreElements = rs.next(); - } - } - - public boolean hasNext() { - return hasMoreElements; - } - - public Object next() { - if (hasMoreElements) { - try { - String name = rs.getString("aid"); - DFAgentDescription dfd = getDFD(name); - hasMoreElements = rs.next(); - return dfd; - } catch (SQLException sqle) { - hasMoreElements = false; - throw new NoSuchElementException("DB Error. " + sqle.getMessage()); - } - } - throw new NoSuchElementException(""); - } - - public void remove() { - // Not implemented - } - - public void close() { - closeResultSet(rs); - closeStatement(s); - } - } // END of inner class DFDBKBIterator - - /** * Reconstructs an AID object corresponding to the given AID name * @@ -1232,7 +1063,6 @@ private DFAgentDescription getDFD(String aidN, Map> allLang return dfd; } - private void loadOntologies(String descrId, DFAgentDescription dfd, Map> allOntologies) throws SQLException { if (allOntologies != null) { List ontos = allOntologies.get(descrId); @@ -1369,7 +1199,6 @@ private void removeServices(String descrId) throws SQLException { } } - /** * Delete the DFD object corresponding to the indicated agent name. */ @@ -1426,7 +1255,6 @@ private void remove(String aid) throws SQLException { } } - /** * Convert a template DFAgentDescription into the SQL SELECT * operation that returns the AID names whose DFAgentDescriptions @@ -1605,10 +1433,6 @@ private boolean isMultiValueProperty(String propKey) throws SQLException { return found > 0; } - //////////////////////////////////////// - // DB cleaning methods - //////////////////////////////////////// - /** * Removes DF registrations and subscriptions whose lease time * has expired. @@ -1620,6 +1444,10 @@ private void clean() { cleanExpiredSubscriptions(); } + //////////////////////////////////////// + // DB cleaning methods + //////////////////////////////////////// + /** * Removes DF registrations whose lease time has expired. */ @@ -1651,8 +1479,6 @@ private void cleanExpiredSubscriptions() { //FIXME: To be implemented } - private final StringACLCodec codec = new StringACLCodec(); - @Override protected void subscribeSingle(Object dfd, SubscriptionResponder.Subscription s) throws SQLException { ACLMessage aclM = s.getMessage(); @@ -1723,7 +1549,6 @@ public Enumeration getSubscriptions() { return subscriptions.elements(); } - @Override protected void unsubscribeSingle(SubscriptionResponder.Subscription sub) throws SQLException { ACLMessage aclM = sub.getMessage(); @@ -1734,7 +1559,6 @@ protected void unsubscribeSingle(SubscriptionResponder.Subscription sub) throws logger.log(Logger.WARNING, "No subscription to delete."); } - /** * Removes a registration from the database. * @@ -1763,12 +1587,6 @@ private boolean deregisterSubscription(String convID) throws SQLException { } } - - //////////////////////////////////////////////// - // Helper methods - //////////////////////////////////////////////// - - /** * Closes an open result set and logs an appropriate error message * when it fails @@ -1800,6 +1618,11 @@ private void closeStatement(Statement s) { } } + + //////////////////////////////////////////////// + // Helper methods + //////////////////////////////////////////////// + /** * Serializes any serializable object to a Base64 encoded string * @@ -1899,4 +1722,167 @@ protected String replace(String str, String pattern, String replaceWith) { result.append(str.substring(s)); return result.toString(); } + + private static class PreparedStatements { + // prepared SQL statements + private final PreparedStatement stm_selNrOfPropForKey; + private final PreparedStatement stm_selNrOfDescrForAID; + private final PreparedStatement stm_selAgentAddresses; + private final PreparedStatement stm_selAgentResolverAIDs; + private final PreparedStatement stm_selAgentUserDefSlot; + private final PreparedStatement stm_selLease; + private final PreparedStatement stm_selProtocols; + private final PreparedStatement stm_selLanguages; + private final PreparedStatement stm_selOntologies; + private final PreparedStatement stm_selServices; + private final PreparedStatement stm_selServiceProtocols; + private final PreparedStatement stm_selServiceLanguages; + private final PreparedStatement stm_selServiceOntologies; + private final PreparedStatement stm_selServiceProperties; + private final PreparedStatement stm_selExpiredDescr; + private final PreparedStatement stm_selSubscriptions; + + private final PreparedStatement stm_selAllProtocols; + private final PreparedStatement stm_selCountAllProtocols; + private final PreparedStatement stm_selAllLanguages; + private final PreparedStatement stm_selCountAllLanguages; + private final PreparedStatement stm_selAllOntologies; + private final PreparedStatement stm_selCountAllOntologies; + + private final PreparedStatement stm_insAgentDescr; + private final PreparedStatement stm_insAgentAddress; + private final PreparedStatement stm_insAgentUserDefSlot; + private final PreparedStatement stm_insAgentResolverAID; + private final PreparedStatement stm_insLanguage; + private final PreparedStatement stm_insOntology; + private final PreparedStatement stm_insProtocol; + private final PreparedStatement stm_insService; + private final PreparedStatement stm_insServiceProtocol; + private final PreparedStatement stm_insServiceOntology; + private final PreparedStatement stm_insServiceLanguage; + private final PreparedStatement stm_insServiceProperty; + private final PreparedStatement stm_insSubscription; + private final PreparedStatement stm_delAgentDescr; + private final PreparedStatement stm_delAgentUserDefSlot; + private final PreparedStatement stm_delAgentResolver; + private final PreparedStatement stm_delAgentAddress; + + private final PreparedStatement stm_selDescrId; + private final PreparedStatement stm_selServiceId; + private final PreparedStatement stm_delService; + private final PreparedStatement stm_delLanguage; + private final PreparedStatement stm_delProtocol; + private final PreparedStatement stm_delOntology; + + private final PreparedStatement stm_delServiceLanguage; + private final PreparedStatement stm_delServiceOntology; + private final PreparedStatement stm_delServiceProtocol; + private final PreparedStatement stm_delServiceProperty; + private final PreparedStatement stm_delSubscription; + + private PreparedStatements(Connection conn) throws SQLException { + // select statements + stm_selNrOfPropForKey = conn.prepareStatement("SELECT COUNT(*) FROM SERVICEPROPERTY where PROPKEY = ?"); + stm_selNrOfDescrForAID = conn.prepareStatement("SELECT COUNT(*) FROM dfagentdescr WHERE aid = ?"); + stm_selAgentAddresses = conn.prepareStatement("SELECT address FROM agentaddress WHERE aid = ?"); + stm_selAgentResolverAIDs = conn.prepareStatement("SELECT resolveraid FROM agentresolver WHERE aid = ?"); + stm_selAgentUserDefSlot = conn.prepareStatement("SELECT slotkey, slotval FROM agentuserdefslot WHERE aid = ?"); + stm_selLease = conn.prepareStatement("SELECT id, lease FROM dfagentdescr WHERE aid = ?"); + stm_selProtocols = conn.prepareStatement("SELECT protocol FROM protocol WHERE descrid = ?"); + stm_selLanguages = conn.prepareStatement("SELECT language FROM language WHERE descrid = ?"); + stm_selOntologies = conn.prepareStatement("SELECT ontology FROM ontology WHERE descrid = ?"); + stm_selServices = conn.prepareStatement("SELECT id, sname, stype, sownership FROM service WHERE descrid = ?"); + stm_selServiceProtocols = conn.prepareStatement("SELECT protocol FROM serviceprotocol WHERE serviceid = ?"); + stm_selServiceLanguages = conn.prepareStatement("SELECT ontology FROM serviceontology WHERE serviceid = ?"); + stm_selServiceOntologies = conn.prepareStatement("SELECT language FROM servicelanguage WHERE serviceid = ?"); + stm_selServiceProperties = conn.prepareStatement("SELECT propkey, propval_str, propval_obj FROM serviceproperty WHERE serviceid = ?"); + stm_selDescrId = conn.prepareStatement("SELECT id FROM dfagentdescr WHERE aid = ?"); + stm_selServiceId = conn.prepareStatement("SELECT id FROM service WHERE descrid = ?"); + stm_selExpiredDescr = conn.prepareStatement("SELECT aid FROM dfagentdescr WHERE lease < ? AND lease <> '-1'"); + stm_selSubscriptions = conn.prepareStatement("SELECT * FROM subscription"); + + stm_selAllProtocols = conn.prepareStatement("SELECT descrid, protocol FROM protocol ORDER BY descrid"); + stm_selCountAllProtocols = conn.prepareStatement("SELECT COUNT(*) FROM protocol"); + stm_selAllLanguages = conn.prepareStatement("SELECT descrid, language FROM language ORDER BY descrid"); + stm_selCountAllLanguages = conn.prepareStatement("SELECT COUNT(*) FROM language"); + stm_selAllOntologies = conn.prepareStatement("SELECT descrid, ontology FROM ontology ORDER BY descrid"); + stm_selCountAllOntologies = conn.prepareStatement("SELECT COUNT(*) FROM ontology"); + + stm_insAgentDescr = conn.prepareStatement("INSERT INTO dfagentdescr VALUES (?, ?, ?)"); + stm_insAgentAddress = conn.prepareStatement("INSERT INTO agentaddress VALUES (?, ?, ?)"); + stm_insAgentUserDefSlot = conn.prepareStatement("INSERT INTO agentuserdefslot VALUES (?, ?, ?, ?)"); + stm_insAgentResolverAID = conn.prepareStatement("INSERT INTO agentresolver VALUES (?, ?, ?)"); + stm_insLanguage = conn.prepareStatement("INSERT INTO language VALUES (?, ?)"); + stm_insOntology = conn.prepareStatement("INSERT INTO ontology VALUES (?, ?)"); + stm_insProtocol = conn.prepareStatement("INSERT INTO protocol VALUES (?, ?)"); + stm_insService = conn.prepareStatement("INSERT INTO service VALUES (?, ?, ?, ?, ?)"); + stm_insServiceProtocol = conn.prepareStatement("INSERT INTO serviceprotocol VALUES (?, ?)"); + stm_insServiceOntology = conn.prepareStatement("INSERT INTO serviceontology VALUES (?, ?)"); + stm_insServiceLanguage = conn.prepareStatement("INSERT INTO servicelanguage VALUES (?, ?)"); + stm_insServiceProperty = conn.prepareStatement("INSERT INTO serviceproperty VALUES (?, ?, ?, ?, ?)"); + stm_insSubscription = conn.prepareStatement("INSERT INTO subscription VALUES (?, ?)"); + + + // delete statements + stm_delAgentDescr = conn.prepareStatement("DELETE FROM dfagentdescr WHERE id = ?"); + stm_delAgentUserDefSlot = conn.prepareStatement("DELETE FROM agentuserdefslot WHERE aid = ?"); + stm_delAgentResolver = conn.prepareStatement("DELETE FROM agentresolver WHERE aid = ?"); + stm_delAgentAddress = conn.prepareStatement("DELETE FROM agentaddress WHERE aid = ?"); + stm_delLanguage = conn.prepareStatement("DELETE FROM language WHERE descrid = ?"); + stm_delProtocol = conn.prepareStatement("DELETE FROM protocol WHERE descrid = ?"); + stm_delOntology = conn.prepareStatement("DELETE FROM ontology WHERE descrid = ?"); + stm_delService = conn.prepareStatement("DELETE FROM service WHERE descrid = ?"); + stm_delServiceLanguage = conn.prepareStatement("DELETE FROM servicelanguage WHERE serviceid = ?"); + stm_delServiceOntology = conn.prepareStatement("DELETE FROM serviceontology WHERE serviceid = ?"); + stm_delServiceProtocol = conn.prepareStatement("DELETE FROM serviceprotocol WHERE serviceid = ?"); + stm_delServiceProperty = conn.prepareStatement("DELETE FROM serviceproperty WHERE serviceid = ?"); + stm_delSubscription = conn.prepareStatement("DELETE FROM subscription WHERE id = ?"); + } + } + + /** + * Inner class DFDBKBIterator + */ + private class DFDBKBIterator implements KBIterator { + private Statement s = null; + private ResultSet rs = null; + private boolean hasMoreElements = false; + + public DFDBKBIterator(Statement s, ResultSet rs) throws SQLException { + this.s = s; + this.rs = rs; + if (rs != null) { + // Move to the first row + hasMoreElements = rs.next(); + } + } + + public boolean hasNext() { + return hasMoreElements; + } + + public Object next() { + if (hasMoreElements) { + try { + String name = rs.getString("aid"); + DFAgentDescription dfd = getDFD(name); + hasMoreElements = rs.next(); + return dfd; + } catch (SQLException sqle) { + hasMoreElements = false; + throw new NoSuchElementException("DB Error. " + sqle.getMessage()); + } + } + throw new NoSuchElementException(""); + } + + public void remove() { + // Not implemented + } + + public void close() { + closeResultSet(rs); + closeStatement(s); + } + } // END of inner class DFDBKBIterator } diff --git a/src/jade/domain/DFGUIManagement/DFAppletOntology.java b/src/jade/domain/DFGUIManagement/DFAppletOntology.java index fc8496e..4995b92 100644 --- a/src/jade/domain/DFGUIManagement/DFAppletOntology.java +++ b/src/jade/domain/DFGUIManagement/DFAppletOntology.java @@ -40,14 +40,13 @@ */ /** - This class represents the ontology - DFApplet-management, containing all JADE extensions - related to applet management. There is only a single instance of - this class. -

- The package contains one class for each Frame in the ontology. -

- + * This class represents the ontology + * DFApplet-management, containing all JADE extensions + * related to applet management. There is only a single instance of + * this class. + *

+ * The package contains one class for each Frame in the ontology. + *

*/ @@ -55,16 +54,6 @@ public class DFAppletOntology extends Ontology implements DFAppletVocabulary { private static final Ontology theInstance = new DFAppletOntology(); - /** - This method grants access to the unique instance of the - ontology. - @return An Ontology object, containing the concepts - of the ontology. - */ - public static Ontology getInstance() { - return theInstance; - } - private DFAppletOntology() { super(NAME, FIPAManagementOntology.getInstance(), new ReflectiveIntrospector()); @@ -107,4 +96,15 @@ private DFAppletOntology() { } + /** + * This method grants access to the unique instance of the + * ontology. + * + * @return An Ontology object, containing the concepts + * of the ontology. + */ + public static Ontology getInstance() { + return theInstance; + } + } diff --git a/src/jade/domain/DFGUIManagement/DeregisterFrom.java b/src/jade/domain/DFGUIManagement/DeregisterFrom.java index 2e39067..f37c774 100644 --- a/src/jade/domain/DFGUIManagement/DeregisterFrom.java +++ b/src/jade/domain/DFGUIManagement/DeregisterFrom.java @@ -42,27 +42,20 @@ public class DeregisterFrom implements AgentAction { private AID df; private DFAgentDescription description; - public void setDf(AID df) { - this.df = df; - } - public AID getDf() { return df; } - public void setDescription(DFAgentDescription description) { - this.description = description; + public void setDf(AID df) { + this.df = df; } public DFAgentDescription getDescription() { return description; } - /** - * @deprecated Use setDf() instead. - */ - public void setParentDF(Object df) { - setDf((AID) df); + public void setDescription(DFAgentDescription description) { + this.description = description; } /** @@ -72,6 +65,13 @@ public Object getParentDF() { return getDf(); } + /** + * @deprecated Use setDf() instead. + */ + public void setParentDF(Object df) { + setDf((AID) df); + } + /** * @deprecated Use setDescription() instead. */ diff --git a/src/jade/domain/DFGUIManagement/Federate.java b/src/jade/domain/DFGUIManagement/Federate.java index 5cb4822..ebde21c 100644 --- a/src/jade/domain/DFGUIManagement/Federate.java +++ b/src/jade/domain/DFGUIManagement/Federate.java @@ -42,27 +42,20 @@ public class Federate implements AgentAction { private AID df; private DFAgentDescription description; - public void setDf(AID df) { - this.df = df; - } - public AID getDf() { return df; } - public void setDescription(DFAgentDescription description) { - this.description = description; + public void setDf(AID df) { + this.df = df; } public DFAgentDescription getDescription() { return description; } - /** - * @deprecated Use setDf() instead. - */ - public void setParentDF(Object parent) { - setDf((AID) parent); + public void setDescription(DFAgentDescription description) { + this.description = description; } /** @@ -73,10 +66,10 @@ public Object getParentDF() { } /** - * @deprecated Use setDescription() instead. + * @deprecated Use setDf() instead. */ - public void setChildrenDF(Object desc) { - setDescription((DFAgentDescription) desc); + public void setParentDF(Object parent) { + setDf((AID) parent); } /** @@ -85,4 +78,11 @@ public void setChildrenDF(Object desc) { public Object getChildrenDF() { return getDescription(); } + + /** + * @deprecated Use setDescription() instead. + */ + public void setChildrenDF(Object desc) { + setDescription((DFAgentDescription) desc); + } } \ No newline at end of file diff --git a/src/jade/domain/DFGUIManagement/GetDescriptionUsed.java b/src/jade/domain/DFGUIManagement/GetDescriptionUsed.java index 603e60e..70fc6ed 100644 --- a/src/jade/domain/DFGUIManagement/GetDescriptionUsed.java +++ b/src/jade/domain/DFGUIManagement/GetDescriptionUsed.java @@ -40,12 +40,12 @@ public class GetDescriptionUsed implements AgentAction { private AID parentDF; - public void setParentDF(AID parent) { - parentDF = parent; - } - public AID getParentDF() { return parentDF; } + public void setParentDF(AID parent) { + parentDF = parent; + } + } \ No newline at end of file diff --git a/src/jade/domain/DFGUIManagement/ModifyOn.java b/src/jade/domain/DFGUIManagement/ModifyOn.java index f3ea7d4..c8cddfb 100644 --- a/src/jade/domain/DFGUIManagement/ModifyOn.java +++ b/src/jade/domain/DFGUIManagement/ModifyOn.java @@ -42,6 +42,10 @@ public class ModifyOn implements AgentAction { private AID df; private DFAgentDescription description; + public AID getDf() { + return df; + } + /** * The df on which the modify action will be perfomed. */ @@ -50,17 +54,13 @@ public void setDf(AID parent) { df = parent; } - public AID getDf() { - return df; + public DFAgentDescription getDescription() { + return description; } public void setDescription(DFAgentDescription desc) { description = desc; } - public DFAgentDescription getDescription() { - return description; - } - } \ No newline at end of file diff --git a/src/jade/domain/DFGUIManagement/RegisterWith.java b/src/jade/domain/DFGUIManagement/RegisterWith.java index 9e63d83..a144588 100644 --- a/src/jade/domain/DFGUIManagement/RegisterWith.java +++ b/src/jade/domain/DFGUIManagement/RegisterWith.java @@ -43,19 +43,19 @@ public class RegisterWith implements AgentAction { private AID df; private DFAgentDescription description; - public void setDf(AID parent) { - df = parent; - } - public AID getDf() { return df; } - public void setDescription(DFAgentDescription desc) { - description = desc; + public void setDf(AID parent) { + df = parent; } public DFAgentDescription getDescription() { return description; } + + public void setDescription(DFAgentDescription desc) { + description = desc; + } } \ No newline at end of file diff --git a/src/jade/domain/DFGUIManagement/SearchOn.java b/src/jade/domain/DFGUIManagement/SearchOn.java index 76c89e1..a4533d6 100644 --- a/src/jade/domain/DFGUIManagement/SearchOn.java +++ b/src/jade/domain/DFGUIManagement/SearchOn.java @@ -44,6 +44,10 @@ public class SearchOn implements AgentAction { private DFAgentDescription description; private SearchConstraints constraints; + public AID getDf() { + return df; + } + /** * The df on which the search will be made. */ @@ -51,23 +55,19 @@ public void setDf(AID parent) { df = parent; } - public AID getDf() { - return df; + public DFAgentDescription getDescription() { + return description; } public void setDescription(DFAgentDescription desc) { description = desc; } - public DFAgentDescription getDescription() { - return description; + public SearchConstraints getConstraints() { + return constraints; } public void setConstraints(SearchConstraints c) { constraints = c; } - - public SearchConstraints getConstraints() { - return constraints; - } } \ No newline at end of file diff --git a/src/jade/domain/DFHSQLKB.java b/src/jade/domain/DFHSQLKB.java index ed81360..5459e99 100644 --- a/src/jade/domain/DFHSQLKB.java +++ b/src/jade/domain/DFHSQLKB.java @@ -39,20 +39,20 @@ */ public class DFHSQLKB extends DFDBKB { + protected final static String CACHE_SCALE = "8"; + protected final static String CACHE_SIZE_SCALE = "8"; + protected final static String GC_INTERVAL = "10000"; private static final String db_driver = "org.hsqldb.jdbcDriver"; private static final String db_url = "jdbc:hsqldb:file:dfdb"; private static final String db_user = "sa"; private static final String db_passwd = ""; - protected final static String CACHE_SCALE = "8"; - protected final static String CACHE_SIZE_SCALE = "8"; - protected final static String GC_INTERVAL = "10000"; - /** * Constructor + * * @param maxResultLimit JADE internal limit for the number of maximum search results. - * @param cleanTables specifies whether the KB should delete all existing tables for the DF at startup + * @param cleanTables specifies whether the KB should delete all existing tables for the DF at startup * @throws SQLException if a database access error occurs */ public DFHSQLKB(int maxResultLimit, boolean cleanTables) throws SQLException { diff --git a/src/jade/domain/DFKBFactory.java b/src/jade/domain/DFKBFactory.java index cdef504..a9049c2 100644 --- a/src/jade/domain/DFKBFactory.java +++ b/src/jade/domain/DFKBFactory.java @@ -31,15 +31,16 @@ import java.sql.SQLException; /** - * The DFKBFactory class creates - * knowledge base objects used by the DF. + * The DFKBFactory class creates + * knowledge base objects used by the DF. * *

- * To run JADE with your own knowledge base implementation a new - * sub class of DFKBFactory, overriding the appropriate method(s), - * has to be implemented and specified by the command line parameter + * To run JADE with your own knowledge base implementation a new + * sub class of DFKBFactory, overriding the appropriate method(s), + * has to be implemented and specified by the command line parameter * -jade_domain_df_kb-factory. *

+ * * @author Roland Mungenast - Profactor * @since JADE 3.3 */ @@ -47,6 +48,7 @@ public class DFKBFactory { /** * Returns the memory based knowledge base which will be used by the DF + * * @param maxResultLimit internal limit for the maximum number of search results */ protected MemKB getDFMemKB(int maxResultLimit) { @@ -55,12 +57,13 @@ protected MemKB getDFMemKB(int maxResultLimit) { /** * Returns the database based knowledge base which will be used by the DF + * * @param maxResultLimit JADE internal limit for the maximum number of search results - * @param driver database driver - * @param url database url - * @param user user for the database access - * @param passwd password for the database access - * @param cleanTables specifies whether the KB should delete all existing tables for the DF at startup + * @param driver database driver + * @param url database url + * @param user user for the database access + * @param passwd password for the database access + * @param cleanTables specifies whether the KB should delete all existing tables for the DF at startup * @throws SQLException if the database cannot be initialized */ protected DBKB getDFDBKB(int maxResultLimit, String driver, String url, String user, String passwd, boolean cleanTables) throws SQLException { diff --git a/src/jade/domain/DFMemKB.java b/src/jade/domain/DFMemKB.java index aeff98b..61fe664 100644 --- a/src/jade/domain/DFMemKB.java +++ b/src/jade/domain/DFMemKB.java @@ -51,39 +51,6 @@ public DFMemKB(int maxResultLimit) { clean(); } - - protected Object insert(Object name, Object fact) { - DFAgentDescription desc = (DFAgentDescription) fact; - if (desc.getLeaseTime() != null) { - entriesToDelete = true; - } - return super.insert(name, fact); - } - - /** - * Scan the facts and remove those whose lease time has expired. - */ - protected void clean() { - - if (entriesToDelete) { - ArrayList toBeRemoved = new ArrayList<>(); - for (Object o : facts.values()) { - DFAgentDescription dfd = (DFAgentDescription) o; - if (dfd.checkLeaseTimeExpired()) { - toBeRemoved.add(dfd.getName()); - } - } - for (AID aid : toBeRemoved) { - facts.remove(aid); - } - } - } - - // match - public final boolean match(DFAgentDescription template, DFAgentDescription fact) { - return compare(template, fact); - } - public static boolean compare(DFAgentDescription template, DFAgentDescription fact) { try { @@ -249,4 +216,36 @@ public static boolean compareServiceDesc(ServiceDescription template, ServiceDes return true; } + + protected Object insert(Object name, Object fact) { + DFAgentDescription desc = (DFAgentDescription) fact; + if (desc.getLeaseTime() != null) { + entriesToDelete = true; + } + return super.insert(name, fact); + } + + /** + * Scan the facts and remove those whose lease time has expired. + */ + protected void clean() { + + if (entriesToDelete) { + ArrayList toBeRemoved = new ArrayList<>(); + for (Object o : facts.values()) { + DFAgentDescription dfd = (DFAgentDescription) o; + if (dfd.checkLeaseTimeExpired()) { + toBeRemoved.add(dfd.getName()); + } + } + for (AID aid : toBeRemoved) { + facts.remove(aid); + } + } + } + + // match + public final boolean match(DFAgentDescription template, DFAgentDescription fact) { + return compare(template, fact); + } } diff --git a/src/jade/domain/DFService.java b/src/jade/domain/DFService.java index e5a55c4..f8c205e 100644 --- a/src/jade/domain/DFService.java +++ b/src/jade/domain/DFService.java @@ -91,6 +91,15 @@ public class DFService extends FIPAService { private static final long OFFSET = 10000; // 10 sec private static final String SPACE_COLON = " :"; private static final String SPACE_BRACKET = " ("; + // constant used to set max results of SearchConstraints + private static final Long MINUSONE = -1L; + + + /** + * Default constructor. + */ + public DFService() { + } /** * check that the DFAgentDescription contains the mandatory @@ -111,7 +120,7 @@ static void checkIsValid(DFAgentDescription dfd, boolean checkServices) throws M if (checkServices) { // Iterator i = dfd.getAllServices(); // ServiceDescription sd; - for(ServiceDescription sd:dfd.getAllServices()) { + for (ServiceDescription sd : dfd.getAllServices()) { if (sd.getName() == null) throw new MissingParameter(FIPAManagementVocabulary.SERVICEDESCRIPTION, FIPAManagementVocabulary.SERVICEDESCRIPTION_NAME); if (sd.getType() == null) @@ -120,7 +129,6 @@ static void checkIsValid(DFAgentDescription dfd, boolean checkServices) throws M } } - /** * Register a new DF-Description with a DF agent. *

@@ -164,7 +172,6 @@ public static DFAgentDescription register(Agent a, AID dfName, DFAgentDescriptio return decodeDone(reply.getContent()); } - /** * Registers a DFAgentDescription with the default DF * @@ -245,7 +252,6 @@ public static void deregister(Agent a) throws FIPAException { deregister(a, a.getDefaultDF()); } - /** * Modifies a previously registered DF-Description within a DF * agent. @@ -345,9 +351,6 @@ protected void onWake() { } } - // constant used to set max results of SearchConstraints - private static final Long MINUSONE = -1L; - /** * Searches for data contained within a DF agent. * @@ -428,6 +431,10 @@ public static DFAgentDescription[] search(Agent a, AID dfName, DFAgentDescriptio return search(a, dfName, dfd, null); } + /////////////////////////////////// + // Message preparation methods + /////////////////////////////////// + /** * Searches the DF and remains blocked until a result is found or the * specified timeout has expired. @@ -464,10 +471,6 @@ public static DFAgentDescription[] searchUntilFound(Agent a, AID dfName, DFAgent return result; } - /////////////////////////////////// - // Message preparation methods - /////////////////////////////////// - /** * Utility method that creates a suitable message to be used * to REQUEST a DF agent to perform a given action of the @@ -546,6 +549,10 @@ public static ACLMessage getSubscriptionMessage(Agent a, AID dfName, DFAgentDesc return createSubscriptionMessage(a, dfName, template, constraints); } + /////////////////////////////////// + // Decoding methods + /////////////////////////////////// + /** * Utility method that creates a suitable message to be used * to CANCEL a subscription to a DF agent. @@ -569,10 +576,6 @@ public static ACLMessage createCancelMessage(Agent a, AID dfName, ACLMessage sub return cancel; } - /////////////////////////////////// - // Decoding methods - /////////////////////////////////// - /** * Process the content of the final inform (Done) message * resulting from a register or deregister @@ -695,7 +698,6 @@ private static DFAgentDescription parseDfd(SimpleSLTokenizer parser) throws Exce return dfd; } - /** * The parser content has the form: * service-description ......) @@ -875,6 +877,10 @@ private static DFAgentDescription[] decodeDfdSequence(String s) throws Exception return items; } + /////////////////////////////////// + // Encoding methods + /////////////////////////////////// + /** * Start indicates the index of the first char after the open parenthesis */ @@ -903,10 +909,6 @@ private static int countUntilEnclosing(String s, int start) { return cnt - start; } - /////////////////////////////////// - // Encoding methods - /////////////////////////////////// - /** * This is package scoped as it is used by DFUpdateBehaviour and * DFSearchBehaviour. @@ -1056,6 +1058,9 @@ private static void encodeAggregate(StringBuffer sb, Iterator agg, String agg } } + + //#MIDP_EXCLUDE_BEGIN + private static void encodeString(StringBuffer sb, String s) { if (SimpleSLTokenizer.isAWord(s)) { sb.append(s); @@ -1064,9 +1069,6 @@ private static void encodeString(StringBuffer sb, String s) { } } - - //#MIDP_EXCLUDE_BEGIN - /** * In some cases it is more convenient to execute this tasks in a non-blocking way. * This method returns a non-blocking behaviour that can be added to the queue of the agent behaviours, as usual, by using Agent.addBehaviour(). @@ -1123,7 +1125,6 @@ public static RequestFIPAServiceBehaviour getNonBlockingBehaviour(Agent a, Strin return getNonBlockingBehaviour(a, a.getDefaultDF(), actionName, dfd, constraints); } - /** * the default SearchContraints are used. * a default AgentDescription is used, where only the agent AID is set. @@ -1139,7 +1140,6 @@ public static RequestFIPAServiceBehaviour getNonBlockingBehaviour(Agent a, AID d return getNonBlockingBehaviour(a, dfName, actionName, dfd, constraints); } - /** * The defautl DF is used. * the default SearchContraints are used. @@ -1152,6 +1152,7 @@ public static RequestFIPAServiceBehaviour getNonBlockingBehaviour(Agent a, Strin constraints.setMaxResults(MINUSONE); return getNonBlockingBehaviour(a, a.getDefaultDF(), actionName, dfd, constraints); } + //#MIDP_EXCLUDE_END /** * the default SearchContraints are used. @@ -1164,13 +1165,6 @@ public static RequestFIPAServiceBehaviour getNonBlockingBehaviour(Agent a, AID d constraints.setMaxResults(MINUSONE); return getNonBlockingBehaviour(a, dfName, actionName, dfd, constraints); } - //#MIDP_EXCLUDE_END - - /** - * Default constructor. - */ - public DFService() { - } } diff --git a/src/jade/domain/DFSubscriber.java b/src/jade/domain/DFSubscriber.java index 5091baa..08a60de 100644 --- a/src/jade/domain/DFSubscriber.java +++ b/src/jade/domain/DFSubscriber.java @@ -2,14 +2,11 @@ import jade.core.Agent; import jade.domain.FIPAAgentManagement.DFAgentDescription; -import jade.domain.FIPAAgentManagement.ServiceDescription; import jade.lang.acl.ACLMessage; import jade.proto.SubscriptionInitiator; import jade.util.Logger; import java.io.Serial; -import java.util.Iterator; -import java.util.List; //#PJAVA_EXCLUDE_FILE //#MIDP_EXCLUDE_FILE @@ -22,7 +19,7 @@ public abstract class DFSubscriber extends SubscriptionInitiator { private boolean firstNotificationReceived = false; - private DFAgentDescription template; + private final DFAgentDescription template; public DFSubscriber(Agent a, DFAgentDescription template) { super(a, DFService.createSubscriptionMessage(a, a.getDefaultDF(), template, null)); diff --git a/src/jade/domain/FIPAAgentManagement/AMSAgentDescription.java b/src/jade/domain/FIPAAgentManagement/AMSAgentDescription.java index 6fd8d03..78147d9 100644 --- a/src/jade/domain/FIPAAgentManagement/AMSAgentDescription.java +++ b/src/jade/domain/FIPAAgentManagement/AMSAgentDescription.java @@ -86,50 +86,41 @@ public AMSAgentDescription() { } /** - * Set the name slot of this object. - * - * @param n The agent identifier for the name. - */ - public void setName(AID n) { - name = n; - } - - /** - * Set the ownership slot of this object. + * Retrieve the name slot of this object. * - * @param n The string for the ownership. + * @return The value of the name slot, or + * null if no value was set. */ - public void setOwnership(String n) { - ownership = n; + public AID getName() { + return name; } /** - * Set the state slot of this object. + * Set the name slot of this object. * - * @param n The string for the state. + * @param n The agent identifier for the name. */ - public void setState(String n) { - state = n; + public void setName(AID n) { + name = n; } /** - * Retrieve the name slot of this object. + * Retrieve the ownership slot of this object. * - * @return The value of the name slot, or + * @return The value of the ownership slot, or * null if no value was set. */ - public AID getName() { - return name; + public String getOwnership() { + return ownership; } /** - * Retrieve the ownership slot of this object. + * Set the ownership slot of this object. * - * @return The value of the ownership slot, or - * null if no value was set. + * @param n The string for the ownership. */ - public String getOwnership() { - return ownership; + public void setOwnership(String n) { + ownership = n; } /** @@ -142,4 +133,13 @@ public String getState() { return state; } + /** + * Set the state slot of this object. + * + * @param n The string for the state. + */ + public void setState(String n) { + state = n; + } + } diff --git a/src/jade/domain/FIPAAgentManagement/APDescription.java b/src/jade/domain/FIPAAgentManagement/APDescription.java index dd98295..1ae92fb 100644 --- a/src/jade/domain/FIPAAgentManagement/APDescription.java +++ b/src/jade/domain/FIPAAgentManagement/APDescription.java @@ -41,8 +41,8 @@ */ public class APDescription implements Concept { - private String name; private final List services = new ArrayList<>(1); + private String name; /** @@ -51,15 +51,6 @@ public class APDescription implements Concept { public APDescription() { } - /** - * Set the name slot of this object. - * - * @param n The string for the platform name. - */ - public void setName(String n) { - name = n; - } - /** * Retrieve the name slot of this object. * @@ -70,6 +61,15 @@ public String getName() { return name; } + /** + * Set the name slot of this object. + * + * @param n The string for the platform name. + */ + public void setName(String n) { + name = n; + } + /** * Add a service to the ap-services slot collection * of this object. diff --git a/src/jade/domain/FIPAAgentManagement/APService.java b/src/jade/domain/FIPAAgentManagement/APService.java index 5ead56e..714cebb 100644 --- a/src/jade/domain/FIPAAgentManagement/APService.java +++ b/src/jade/domain/FIPAAgentManagement/APService.java @@ -61,15 +61,6 @@ public APService(String type, String[] addresses) { Collections.addAll(this.addresses, addresses); } - /** - * Set the name slot of this object. - * - * @param n The string for the platform service name. - */ - public void setName(String n) { - name = n; - } - /** * Retrieve the name slot of this object. * @@ -82,12 +73,12 @@ public String getName() { } /** - * Set the type slot of this object. + * Set the name slot of this object. * - * @param t The string for the platform service type. + * @param n The string for the platform service name. */ - public void setType(String t) { - type = t; + public void setName(String n) { + name = n; } /** @@ -101,6 +92,15 @@ public String getType() { return type; } + /** + * Set the type slot of this object. + * + * @param t The string for the platform service type. + */ + public void setType(String t) { + type = t; + } + /** * Add a service to the addresses slot collection * of this object. diff --git a/src/jade/domain/FIPAAgentManagement/DFAgentDescription.java b/src/jade/domain/FIPAAgentManagement/DFAgentDescription.java index 7d30abd..682dacd 100644 --- a/src/jade/domain/FIPAAgentManagement/DFAgentDescription.java +++ b/src/jade/domain/FIPAAgentManagement/DFAgentDescription.java @@ -40,13 +40,11 @@ */ public class DFAgentDescription implements Concept { - private AID name; private final List services = new ArrayList<>(); private final List interactionProtocols = new ArrayList<>(); private final List ontology = new ArrayList<>(); private final List language = new ArrayList<>(); - - + private AID name; // Added lease default value -1 //private Date leaseTime = new Date(-1); private Date leaseTime; @@ -58,15 +56,6 @@ public class DFAgentDescription implements Concept { public DFAgentDescription() { } - /** - * Set the identifier of the agent - * - * @param n the identifier of the agent - */ - public void setName(AID n) { - name = n; - } - /** * Retrieve the agent identifier for the described agent. * @@ -77,15 +66,12 @@ public AID getName() { } /** - * Set the lease time for the registration of this DFAgentDescription - * as an absolute time. + * Set the identifier of the agent * - * @param absoluteTime The lease time for the registration of this - * DFAgentDescription as an absolute time. Use null - * (default) to indicate an infinite lease time + * @param n the identifier of the agent */ - public void setLeaseTime(Date absoluteTime) { - leaseTime = absoluteTime; + public void setName(AID n) { + name = n; } /** @@ -101,6 +87,18 @@ public Date getLeaseTime() { return leaseTime; } + /** + * Set the lease time for the registration of this DFAgentDescription + * as an absolute time. + * + * @param absoluteTime The lease time for the registration of this + * DFAgentDescription as an absolute time. Use null + * (default) to indicate an infinite lease time + */ + public void setLeaseTime(Date absoluteTime) { + leaseTime = absoluteTime; + } + /** * Set the lease time for the registration of this * DFAgentDescription as a relative time. diff --git a/src/jade/domain/FIPAAgentManagement/Deregister.java b/src/jade/domain/FIPAAgentManagement/Deregister.java index e61ef3c..276ad87 100644 --- a/src/jade/domain/FIPAAgentManagement/Deregister.java +++ b/src/jade/domain/FIPAAgentManagement/Deregister.java @@ -46,16 +46,6 @@ public class Deregister implements AgentAction { public Deregister() { } - /** - * Set the description slot of this object. - * - * @param desc An AMS or DF description for this action. - */ - public void setDescription(Object desc) { - description = desc; - } - - /** * Retrieve the description slot of this object. * @@ -66,4 +56,13 @@ public Object getDescription() { return description; } + /** + * Set the description slot of this object. + * + * @param desc An AMS or DF description for this action. + */ + public void setDescription(Object desc) { + description = desc; + } + } diff --git a/src/jade/domain/FIPAAgentManagement/Envelope.java b/src/jade/domain/FIPAAgentManagement/Envelope.java index 2e46e47..bdf6774 100644 --- a/src/jade/domain/FIPAAgentManagement/Envelope.java +++ b/src/jade/domain/FIPAAgentManagement/Envelope.java @@ -140,15 +140,6 @@ public Iterator getAllTo() { return to.iterator(); } - /** - * Set the from slot of this object. - * - * @param id The agent identifier for the envelope sender. - */ - public void setFrom(AID id) { - from = id; - } - /** * Retrieve the from slot of this object. * @@ -160,12 +151,12 @@ public AID getFrom() { } /** - * Set the comments slot of this object. + * Set the from slot of this object. * - * @param c The string for the envelope comments. + * @param id The agent identifier for the envelope sender. */ - public void setComments(String c) { - comments = c; + public void setFrom(AID id) { + from = id; } /** @@ -179,12 +170,12 @@ public String getComments() { } /** - * Set the acl-representation slot of this object. + * Set the comments slot of this object. * - * @param r The string for the ACL representation. + * @param c The string for the envelope comments. */ - public void setAclRepresentation(String r) { - aclRepresentation = r; + public void setComments(String c) { + comments = c; } /** @@ -199,12 +190,12 @@ public String getAclRepresentation() { } /** - * Set the payload-length slot of this object. + * Set the acl-representation slot of this object. * - * @param l The payload length, in bytes. + * @param r The string for the ACL representation. */ - public void setPayloadLength(Long l) { - payloadLength = l; + public void setAclRepresentation(String r) { + aclRepresentation = r; } /** @@ -218,16 +209,12 @@ public Long getPayloadLength() { } /** - * Set the payload-encoding slot of this object. - * This slot can be used to specify a different charset than - * the standard one (US-ASCII) in order for instance to support - * accentuated characters in the content slot of the ACL message - * (e.g. setPayloadEncoding("UTF-8")). + * Set the payload-length slot of this object. * - * @param e The string for the payload encoding. + * @param l The payload length, in bytes. */ - public void setPayloadEncoding(String e) { - payloadEncoding = e; + public void setPayloadLength(Long l) { + payloadLength = l; } /** @@ -241,12 +228,16 @@ public String getPayloadEncoding() { } /** - * Set the date slot of this object. + * Set the payload-encoding slot of this object. + * This slot can be used to specify a different charset than + * the standard one (US-ASCII) in order for instance to support + * accentuated characters in the content slot of the ACL message + * (e.g. setPayloadEncoding("UTF-8")). * - * @param d The envelope date. + * @param e The string for the payload encoding. */ - public void setDate(Date d) { - date = d; + public void setPayloadEncoding(String e) { + payloadEncoding = e; } /** @@ -259,6 +250,15 @@ public Date getDate() { return date; } + /** + * Set the date slot of this object. + * + * @param d The envelope date. + */ + public void setDate(Date d) { + date = d; + } + /** * Add an agent identifier to the intended-receiver * slot collection of this object. @@ -299,16 +299,6 @@ public Iterator getAllIntendedReceiver() { return intendedReceiver.iterator(); } - /** - * Set the received slot of this object. - * - * @param ro The received object for the received - * slot. - */ - public void setReceived(ReceivedObject ro) { - addStamp(ro); - } - /** * Retrieve the received slot of this object. * @@ -322,6 +312,16 @@ public ReceivedObject getReceived() { return stamps.get(stamps.size() - 1); } + /** + * Set the received slot of this object. + * + * @param ro The received object for the received + * slot. + */ + public void setReceived(ReceivedObject ro) { + addStamp(ro); + } + /** * Add a received-object stamp to this message * envelope. This method is used by the ACC to add a new stamp to @@ -491,6 +491,10 @@ public Object clone() { //#MIDP_EXCLUDE_BEGIN + // For persistence service + private ArrayList getTo() { + return to; + } // For persistence service private void setTo(ArrayList al) { @@ -498,8 +502,8 @@ private void setTo(ArrayList al) { } // For persistence service - private ArrayList getTo() { - return to; + private ArrayList getIntendedReceivers() { + return intendedReceiver; } // For persistence service @@ -508,8 +512,8 @@ private void setIntendedReceivers(ArrayList al) { } // For persistence service - private ArrayList getIntendedReceivers() { - return intendedReceiver; + private ArrayList getProperties() { + return properties; } // For persistence service @@ -517,11 +521,6 @@ private void setProperties(ArrayList al) { properties = al; } - // For persistence service - private ArrayList getProperties() { - return properties; - } - //#MIDP_EXCLUDE_END } diff --git a/src/jade/domain/FIPAAgentManagement/ExceptionOntology.java b/src/jade/domain/FIPAAgentManagement/ExceptionOntology.java index 6727991..cdcb485 100644 --- a/src/jade/domain/FIPAAgentManagement/ExceptionOntology.java +++ b/src/jade/domain/FIPAAgentManagement/ExceptionOntology.java @@ -48,23 +48,12 @@ public class ExceptionOntology extends Ontology implements ExceptionVocabulary { private static final Ontology theInstance = new ExceptionOntology(); - /** - * This method returns the unique instance (according to the singleton - * pattern) of the Exception-ontology. - * - * @return The singleton Ontology object, containing the - * schemas for the elements of the Exception-ontology. - */ - public static Ontology getInstance() { - return theInstance; - } - private ExceptionOntology() { //#MIDP_EXCLUDE_BEGIN super(NAME, BasicOntology.getInstance(), new BCReflectiveIntrospector()); //#MIDP_EXCLUDE_END - - /*#MIDP_INCLUDE_BEGIN + + /*#MIDP_INCLUDE_BEGIN super(NAME, BasicOntology.getInstance(), null); #MIDP_INCLUDE_END*/ @@ -85,8 +74,8 @@ private ExceptionOntology() { add(new PredicateSchema(UNRECOGNISEDPARAMETERVALUE), UnrecognisedParameterValue.class); add(new PredicateSchema(INTERNALERROR), InternalError.class); //#MIDP_EXCLUDE_END - - /*#MIDP_INCLUDE_BEGIN + + /*#MIDP_INCLUDE_BEGIN add(new PredicateSchema(UNAUTHORISED)); add(new PredicateSchema(UNSUPPORTEDACT)); add(new PredicateSchema(UNEXPECTEDACT)); @@ -144,5 +133,16 @@ private ExceptionOntology() { } } + /** + * This method returns the unique instance (according to the singleton + * pattern) of the Exception-ontology. + * + * @return The singleton Ontology object, containing the + * schemas for the elements of the Exception-ontology. + */ + public static Ontology getInstance() { + return theInstance; + } + } diff --git a/src/jade/domain/FIPAAgentManagement/FIPAManagementOntology.java b/src/jade/domain/FIPAAgentManagement/FIPAManagementOntology.java index 0b04338..d78c777 100644 --- a/src/jade/domain/FIPAAgentManagement/FIPAManagementOntology.java +++ b/src/jade/domain/FIPAAgentManagement/FIPAManagementOntology.java @@ -42,23 +42,12 @@ public class FIPAManagementOntology extends Ontology implements FIPAManagementVo private static final Ontology theInstance = new FIPAManagementOntology(); - /** - * This method returns the unique instance (according to the singleton - * pattern) of the FIPA-Agent-Management-ontology. - * - * @return The singleton Ontology object, containing the - * schemas for the elements of the FIPA-Agent-Management-ontology. - */ - public static Ontology getInstance() { - return theInstance; - } - private FIPAManagementOntology() { //#MIDP_EXCLUDE_BEGIN super(NAME, new Ontology[]{ExceptionOntology.getInstance(), SerializableOntology.getInstance()}, new BCReflectiveIntrospector()); //#MIDP_EXCLUDE_END - - /*#MIDP_INCLUDE_BEGIN + + /*#MIDP_INCLUDE_BEGIN super(NAME, ExceptionOntology.getInstance(), null); #MIDP_INCLUDE_END*/ @@ -84,8 +73,8 @@ private FIPAManagementOntology() { add(new PredicateSchema(ALREADYREGISTERED), AlreadyRegistered.class); add(new PredicateSchema(NOTREGISTERED), NotRegistered.class); //#MIDP_EXCLUDE_END - - /*#MIDP_INCLUDE_BEGIN + + /*#MIDP_INCLUDE_BEGIN add(new ConceptSchema(DFAGENTDESCRIPTION)); add(new ConceptSchema(SERVICEDESCRIPTION)); add(new ConceptSchema(SEARCHCONSTRAINTS)); @@ -95,13 +84,13 @@ private FIPAManagementOntology() { add(new ConceptSchema(RECEIVEDOBJECT)); add(new ConceptSchema(APDESCRIPTION)); add(new ConceptSchema(APSERVICE)); - + add(new AgentActionSchema(REGISTER)); add(new AgentActionSchema(DEREGISTER)); add(new AgentActionSchema(MODIFY)); add(new AgentActionSchema(SEARCH)); add(new AgentActionSchema(GETDESCRIPTION)); - + add(new PredicateSchema(ALREADYREGISTERED)); add(new PredicateSchema(NOTREGISTERED)); #MIDP_INCLUDE_END*/ @@ -188,4 +177,15 @@ private FIPAManagementOntology() { oe.printStackTrace(); } } + + /** + * This method returns the unique instance (according to the singleton + * pattern) of the FIPA-Agent-Management-ontology. + * + * @return The singleton Ontology object, containing the + * schemas for the elements of the FIPA-Agent-Management-ontology. + */ + public static Ontology getInstance() { + return theInstance; + } } diff --git a/src/jade/domain/FIPAAgentManagement/InternalError.java b/src/jade/domain/FIPAAgentManagement/InternalError.java index 980132e..e03185c 100644 --- a/src/jade/domain/FIPAAgentManagement/InternalError.java +++ b/src/jade/domain/FIPAAgentManagement/InternalError.java @@ -34,6 +34,11 @@ public class InternalError extends FailureException implements Predicate { + /** + * @serial + */ + String s1; + public InternalError(String msg) { super("(internal-error \"" + msg + "\")"); s1 = msg; @@ -43,18 +48,13 @@ public InternalError() { this("unknown-error"); } - /** - * @serial - */ - String s1; + public String getErrorMessage() { + return s1; + } public void setErrorMessage(String s) { s1 = s; setMessage("(internal-error \"" + s1 + "\")"); } - public String getErrorMessage() { - return s1; - } - } diff --git a/src/jade/domain/FIPAAgentManagement/MissingArgument.java b/src/jade/domain/FIPAAgentManagement/MissingArgument.java index c4eb895..2641ecb 100644 --- a/src/jade/domain/FIPAAgentManagement/MissingArgument.java +++ b/src/jade/domain/FIPAAgentManagement/MissingArgument.java @@ -34,28 +34,28 @@ public class MissingArgument extends RefuseException implements Predicate { + /** + * @serial + */ + String s1; + public MissingArgument() { this("Unknown-argument-name"); } + public MissingArgument(String argumentName) { super("(missing-argument " + argumentName + ")"); s1 = argumentName; } - - /** - * @serial - */ - String s1; + public String getArgumentName() { + return s1; + } public void setArgumentName(String a) { s1 = a; setMessage("(missing-argument " + s1 + ")"); } - public String getArgumentName() { - return s1; - } - } diff --git a/src/jade/domain/FIPAAgentManagement/MissingParameter.java b/src/jade/domain/FIPAAgentManagement/MissingParameter.java index 2f8aca5..2b083f7 100644 --- a/src/jade/domain/FIPAAgentManagement/MissingParameter.java +++ b/src/jade/domain/FIPAAgentManagement/MissingParameter.java @@ -34,29 +34,33 @@ public class MissingParameter extends RefuseException implements Predicate { + /** + * @serial + */ + String s1, s2; + public MissingParameter() { this("Unkown-object", "Unknown-parameter-name"); } + public MissingParameter(String objectName, String parameterName) { super("(missing-parameter " + objectName + " " + parameterName + ")"); s1 = objectName; s2 = parameterName; } - - /** - * @serial - */ - String s1, s2; + public String getObjectName() { + return s1; + } public void setObjectName(String a) { s1 = a; setMessage("(missing-parameter " + s1 + " " + s2 + ")"); } - public String getObjectName() { - return s1; + public String getParameterName() { + return s2; } public void setParameterName(String a) { @@ -64,9 +68,5 @@ public void setParameterName(String a) { setMessage("(missing-parameter " + s1 + " " + s2 + ")"); } - public String getParameterName() { - return s2; - } - } \ No newline at end of file diff --git a/src/jade/domain/FIPAAgentManagement/Modify.java b/src/jade/domain/FIPAAgentManagement/Modify.java index 467a219..16b37a3 100644 --- a/src/jade/domain/FIPAAgentManagement/Modify.java +++ b/src/jade/domain/FIPAAgentManagement/Modify.java @@ -52,15 +52,6 @@ public class Modify implements AgentAction { public Modify() { } - /** - * Set the description slot of this object. - * - * @param desc An AMS or DF description for this action. - */ - public void setDescription(Object desc) { - description = desc; - } - /** * Retrieve the description slot of this object. * @@ -71,4 +62,13 @@ public Object getDescription() { return description; } + /** + * Set the description slot of this object. + * + * @param desc An AMS or DF description for this action. + */ + public void setDescription(Object desc) { + description = desc; + } + } diff --git a/src/jade/domain/FIPAAgentManagement/Property.java b/src/jade/domain/FIPAAgentManagement/Property.java index eaca9ba..4a7f60e 100644 --- a/src/jade/domain/FIPAAgentManagement/Property.java +++ b/src/jade/domain/FIPAAgentManagement/Property.java @@ -63,13 +63,16 @@ public Property(String name, Object value) { this.value = value; } - /** - * Set the name of the property object. - * - * @param n The new name for this property. - */ - public void setName(String n) { - name = n; + public static Properties convertPropertyListToProperties(List pp) { + if (pp == null) { + return null; + } else { + Properties props = new Properties(); + for (Property p : pp) { + props.put(p.getName(), p.getValue()); + } + return props; + } } /** @@ -83,13 +86,12 @@ public String getName() { } /** - * Set the value for this property object, attached to the - * property name. + * Set the name of the property object. * - * @param o The new Java object to attach to the property name. + * @param n The new name for this property. */ - public void setValue(Object o) { - value = o; + public void setName(String n) { + name = n; } /** @@ -103,6 +105,16 @@ public Object getValue() { return value; } + /** + * Set the value for this property object, attached to the + * property name. + * + * @param o The new Java object to attach to the property name. + */ + public void setValue(Object o) { + value = o; + } + //#J2ME_EXCLUDE_BEGIN // For persistence only private void setsvalue(java.io.Serializable s) { @@ -113,18 +125,6 @@ private java.io.Serializable getsvalue() { return (java.io.Serializable) value; } - public static Properties convertPropertyListToProperties(List pp) { - if (pp == null) { - return null; - } else { - Properties props = new Properties(); - for (Property p : pp) { - props.put(p.getName(), p.getValue()); - } - return props; - } - } - //#J2ME_EXCLUDE_END //#MIDP_EXCLUDE_BEGIN diff --git a/src/jade/domain/FIPAAgentManagement/ReceivedObject.java b/src/jade/domain/FIPAAgentManagement/ReceivedObject.java index f79a467..f0f0034 100644 --- a/src/jade/domain/FIPAAgentManagement/ReceivedObject.java +++ b/src/jade/domain/FIPAAgentManagement/ReceivedObject.java @@ -57,17 +57,6 @@ public ReceivedObject() { via = ""; } - - /** - * Set the by slot of this object. - * - * @param b The identifier for the ACC that received the envelope - * containing this object. - */ - public void setBy(String b) { - by = b; - } - /** * Retrieve the by slot of this object. This slot * identifies the ACC that received the envelope containing this @@ -81,13 +70,13 @@ public String getBy() { } /** - * Set the from slot of this object. + * Set the by slot of this object. * - * @param f The identifier for the ACC that sent the envelope + * @param b The identifier for the ACC that received the envelope * containing this object. */ - public void setFrom(String f) { - from = f; + public void setBy(String b) { + by = b; } /** @@ -103,13 +92,13 @@ public String getFrom() { } /** - * Set the date slot of this object. + * Set the from slot of this object. * - * @param d The date when the envelope containing this object was - * sent. + * @param f The identifier for the ACC that sent the envelope + * containing this object. */ - public void setDate(Date d) { - date = d; + public void setFrom(String f) { + from = f; } /** @@ -125,12 +114,13 @@ public Date getDate() { } /** - * Set the id slot of this object. + * Set the date slot of this object. * - * @param i A unique id for the envelope containing this object. + * @param d The date when the envelope containing this object was + * sent. */ - public void setId(String i) { - id = i; + public void setDate(Date d) { + date = d; } /** @@ -145,13 +135,12 @@ public String getId() { } /** - * Set the via slot of this object. + * Set the id slot of this object. * - * @param v The name of the MTP over which the envelope containing - * this object was sent. + * @param i A unique id for the envelope containing this object. */ - public void setVia(String v) { - via = v; + public void setId(String i) { + id = i; } /** @@ -166,6 +155,16 @@ public String getVia() { return via; } + /** + * Set the via slot of this object. + * + * @param v The name of the MTP over which the envelope containing + * this object was sent. + */ + public void setVia(String v) { + via = v; + } + /** * Retrieve a string representation for this received object. * diff --git a/src/jade/domain/FIPAAgentManagement/Register.java b/src/jade/domain/FIPAAgentManagement/Register.java index 55040b8..f096b65 100644 --- a/src/jade/domain/FIPAAgentManagement/Register.java +++ b/src/jade/domain/FIPAAgentManagement/Register.java @@ -51,15 +51,6 @@ public class Register implements AgentAction { public Register() { } - /** - * Set the description slot of this object. - * - * @param desc An AMS or DF description for this action. - */ - public void setDescription(Object desc) { - description = desc; - } - /** * Retrieve the description slot of this object. * @@ -70,4 +61,13 @@ public Object getDescription() { return description; } + /** + * Set the description slot of this object. + * + * @param desc An AMS or DF description for this action. + */ + public void setDescription(Object desc) { + description = desc; + } + } diff --git a/src/jade/domain/FIPAAgentManagement/Search.java b/src/jade/domain/FIPAAgentManagement/Search.java index fedab44..dda56b6 100644 --- a/src/jade/domain/FIPAAgentManagement/Search.java +++ b/src/jade/domain/FIPAAgentManagement/Search.java @@ -48,15 +48,6 @@ public class Search implements AgentAction { public Search() { } - /** - * Set the description slot of this object. - * - * @param desc An AMS or DF description for this action. - */ - public void setDescription(Object desc) { - description = desc; - } - /** * Retrieve the description slot of this object. * @@ -68,12 +59,12 @@ public Object getDescription() { } /** - * Set the constraints slot of this object. + * Set the description slot of this object. * - * @param s The search constraints for this action. + * @param desc An AMS or DF description for this action. */ - public void setConstraints(SearchConstraints s) { - constraints = s; + public void setDescription(Object desc) { + description = desc; } /** @@ -86,4 +77,13 @@ public SearchConstraints getConstraints() { return constraints; } + /** + * Set the constraints slot of this object. + * + * @param s The search constraints for this action. + */ + public void setConstraints(SearchConstraints s) { + constraints = s; + } + } diff --git a/src/jade/domain/FIPAAgentManagement/SearchConstraints.java b/src/jade/domain/FIPAAgentManagement/SearchConstraints.java index 8010801..fd81930 100644 --- a/src/jade/domain/FIPAAgentManagement/SearchConstraints.java +++ b/src/jade/domain/FIPAAgentManagement/SearchConstraints.java @@ -73,17 +73,6 @@ public void renewSearchId() { } } - - /** - * Set the search-id slot of this object. - * - * @param searchId The unique identifier associated with this - * search operation. - */ - public void setSearchId(String searchId) { - search_id = searchId; - } - /** * Retrieve the search-id slot of this object. This * slot uniquely identifies a search operation. @@ -95,15 +84,14 @@ public String getSearchId() { return search_id; } - /** - * Set the max-depth slot of this object. + * Set the search-id slot of this object. * - * @param l The value of the maximum recursion depth of this - * search over the DF federation graph. + * @param searchId The unique identifier associated with this + * search operation. */ - public void setMaxDepth(Long l) { - max_depth = l; + public void setSearchId(String searchId) { + search_id = searchId; } /** @@ -119,13 +107,13 @@ public Long getMaxDepth() { } /** - * Set the max-results slot of this object. + * Set the max-depth slot of this object. * - * @param l The maximum number of results to retrieve - * in response to this search operation. + * @param l The value of the maximum recursion depth of this + * search over the DF federation graph. */ - public void setMaxResults(Long l) { - max_results = l; + public void setMaxDepth(Long l) { + max_depth = l; } /** @@ -140,4 +128,14 @@ public Long getMaxResults() { return max_results; } + /** + * Set the max-results slot of this object. + * + * @param l The maximum number of results to retrieve + * in response to this search operation. + */ + public void setMaxResults(Long l) { + max_results = l; + } + } diff --git a/src/jade/domain/FIPAAgentManagement/ServiceDescription.java b/src/jade/domain/FIPAAgentManagement/ServiceDescription.java index b5d5ab5..374756a 100644 --- a/src/jade/domain/FIPAAgentManagement/ServiceDescription.java +++ b/src/jade/domain/FIPAAgentManagement/ServiceDescription.java @@ -28,6 +28,7 @@ import java.util.ArrayList; import java.util.Iterator; import java.util.List; +import java.util.Objects; /** * This class models a service data type. @@ -37,13 +38,13 @@ */ public class ServiceDescription implements Concept { - private String name; - private String type; - private String ownership; private final List interactionProtocols = new ArrayList<>(); private final List ontology = new ArrayList<>(); private final List language = new ArrayList<>(); private final List properties = new ArrayList<>(); + private String name; + private String type; + private String ownership; /** * Default constructor. A default constructor is necessary for @@ -52,15 +53,6 @@ public class ServiceDescription implements Concept { public ServiceDescription() { } - /** - * Set the name slot of this object. - * - * @param n The name of the described service. - */ - public void setName(String n) { - name = n; - } - /** * Retrieve the name slot of this object. * @@ -72,12 +64,12 @@ public String getName() { } /** - * Set the type slot of this object. + * Set the name slot of this object. * - * @param t The type of the described service. + * @param n The name of the described service. */ - public void setType(String t) { - type = t; + public void setName(String n) { + name = n; } /** @@ -90,6 +82,15 @@ public String getType() { return type; } + /** + * Set the type slot of this object. + * + * @param t The type of the described service. + */ + public void setType(String t) { + type = t; + } + /** * Add a protocol name to the protocols slot * collection of this object. @@ -211,15 +212,6 @@ public Iterator getAllLanguages() { return language.iterator(); } - /** - * Set the ownership slot of this object. - * - * @param o The name of the entity owning the described service. - */ - public void setOwnership(String o) { - ownership = o; - } - /** * Retrieve the ownership slot of this object. * @@ -230,6 +222,15 @@ public String getOwnership() { return ownership; } + /** + * Set the ownership slot of this object. + * + * @param o The name of the entity owning the described service. + */ + public void setOwnership(String o) { + ownership = o; + } + /** * Add a property to the properties slot collection * of this object. @@ -277,12 +278,12 @@ public boolean equals(Object o) { ServiceDescription that = (ServiceDescription) o; - if (name != null ? !name.equals(that.name) : that.name != null) return false; - return type != null ? type.equals(that.type) : that.type == null; + if (!Objects.equals(name, that.name)) return false; + return Objects.equals(type, that.type); } @Override public String toString() { - return "Service{" + name + '\'' + type + '}'; + return "Service{" + name + '\'' + type + '}'; } } diff --git a/src/jade/domain/FIPAAgentManagement/UnexpectedAct.java b/src/jade/domain/FIPAAgentManagement/UnexpectedAct.java index ce76e1d..1c625df 100644 --- a/src/jade/domain/FIPAAgentManagement/UnexpectedAct.java +++ b/src/jade/domain/FIPAAgentManagement/UnexpectedAct.java @@ -34,6 +34,11 @@ public class UnexpectedAct extends NotUnderstoodException implements Predicate { + /** + * @serial + */ + String s; + public UnexpectedAct() { super("(Unexpected-act unknwon"); } @@ -43,18 +48,13 @@ public UnexpectedAct(String act) { s = act; } - /** - * @serial - */ - String s; + public String getAct() { + return s; + } public void setAct(String a) { s = a; setMessage("(Unexpected-act " + a + ")"); } - public String getAct() { - return s; - } - } diff --git a/src/jade/domain/FIPAAgentManagement/UnexpectedArgument.java b/src/jade/domain/FIPAAgentManagement/UnexpectedArgument.java index af7a579..3cd3bc0 100644 --- a/src/jade/domain/FIPAAgentManagement/UnexpectedArgument.java +++ b/src/jade/domain/FIPAAgentManagement/UnexpectedArgument.java @@ -34,28 +34,28 @@ public class UnexpectedArgument extends RefuseException implements Predicate { + /** + * @serial + */ + String s1; + public UnexpectedArgument() { this("Unknown-argument-name"); } + public UnexpectedArgument(String argumentName) { super("(unexpected-argument " + argumentName + ")"); s1 = argumentName; } - - /** - * @serial - */ - String s1; + public String getArgumentName() { + return s1; + } public void setArgumentName(String a) { s1 = a; setMessage("(unexpected-argument " + s1 + ")"); } - public String getArgumentName() { - return s1; - } - } diff --git a/src/jade/domain/FIPAAgentManagement/UnexpectedParameter.java b/src/jade/domain/FIPAAgentManagement/UnexpectedParameter.java index fe5f326..9e4ef11 100644 --- a/src/jade/domain/FIPAAgentManagement/UnexpectedParameter.java +++ b/src/jade/domain/FIPAAgentManagement/UnexpectedParameter.java @@ -34,6 +34,11 @@ public class UnexpectedParameter extends RefuseException implements Predicate { + /** + * @serial + */ + String s1, s2; + public UnexpectedParameter() { this("unknown-Object-Name", "unknown-parameter-name"); } @@ -44,18 +49,17 @@ public UnexpectedParameter(String objectName, String parameterName) { s2 = parameterName; } - /** - * @serial - */ - String s1, s2; + public String getObjectName() { + return s1; + } public void setObjectName(String a) { s1 = a; setMessage("(unexpected-parameter " + s1 + " " + s2 + ")"); } - public String getObjectName() { - return s1; + public String getParameterName() { + return s2; } public void setParameterName(String a) { @@ -63,8 +67,4 @@ public void setParameterName(String a) { setMessage("(unexpected-parameter " + s1 + " " + s2 + ")"); } - public String getParameterName() { - return s2; - } - } diff --git a/src/jade/domain/FIPAAgentManagement/UnrecognisedParameterValue.java b/src/jade/domain/FIPAAgentManagement/UnrecognisedParameterValue.java index c086395..0d6bab1 100644 --- a/src/jade/domain/FIPAAgentManagement/UnrecognisedParameterValue.java +++ b/src/jade/domain/FIPAAgentManagement/UnrecognisedParameterValue.java @@ -34,6 +34,11 @@ public class UnrecognisedParameterValue extends RefuseException implements Predicate { + /** + * @serial + */ + String s1, s2; + public UnrecognisedParameterValue() { this("unknown-parameter-name", "unknown-parameter-value"); } @@ -44,18 +49,17 @@ public UnrecognisedParameterValue(String parameterName, String parameterValue) { s2 = parameterValue; } - /** - * @serial - */ - String s1, s2; + public String getParameterName() { + return s1; + } public void setParameterName(String a) { s1 = a; setMessage("(unrecognised-parameter-value " + s1 + " \"" + s2 + "\")"); } - public String getParameterName() { - return s1; + public String getParameterValue() { + return s2; } public void setParameterValue(String a) { @@ -63,9 +67,5 @@ public void setParameterValue(String a) { setMessage("(unrecognised-parameter-value " + s1 + " \"" + s2 + "\")"); } - public String getParameterValue() { - return s2; - } - } diff --git a/src/jade/domain/FIPAAgentManagement/UnrecognisedValue.java b/src/jade/domain/FIPAAgentManagement/UnrecognisedValue.java index 74aa52a..4b1d43e 100644 --- a/src/jade/domain/FIPAAgentManagement/UnrecognisedValue.java +++ b/src/jade/domain/FIPAAgentManagement/UnrecognisedValue.java @@ -34,6 +34,11 @@ public class UnrecognisedValue extends NotUnderstoodException implements Predicate { + /** + * @serial + */ + String s; + public UnrecognisedValue() { this("unknown-value"); } @@ -43,18 +48,13 @@ public UnrecognisedValue(String value) { s = value; } - /** - * @serial - */ - String s; + public String getValue() { + return s; + } public void setValue(String a) { s = a; setMessage("(unrecognised-value \"" + s + "\")"); } - public String getValue() { - return s; - } - } diff --git a/src/jade/domain/FIPAAgentManagement/UnsupportedAct.java b/src/jade/domain/FIPAAgentManagement/UnsupportedAct.java index 885ae7d..ac2aeb2 100644 --- a/src/jade/domain/FIPAAgentManagement/UnsupportedAct.java +++ b/src/jade/domain/FIPAAgentManagement/UnsupportedAct.java @@ -33,6 +33,8 @@ public class UnsupportedAct extends NotUnderstoodException implements Predicate { + String s; + public UnsupportedAct() { super("(unsupported-act unknown)"); } @@ -42,15 +44,13 @@ public UnsupportedAct(String act) { s = act; } - String s; + public String getAct() { + return s; + } public void setAct(String a) { s = a; setMessage("(unsupported-act " + a + ")"); } - public String getAct() { - return s; - } - } diff --git a/src/jade/domain/FIPAAgentManagement/UnsupportedFunction.java b/src/jade/domain/FIPAAgentManagement/UnsupportedFunction.java index b811994..4aa812c 100644 --- a/src/jade/domain/FIPAAgentManagement/UnsupportedFunction.java +++ b/src/jade/domain/FIPAAgentManagement/UnsupportedFunction.java @@ -34,6 +34,11 @@ public class UnsupportedFunction extends RefuseException implements Predicate { + /** + * @serial + */ + String s; + public UnsupportedFunction() { this("unknown-func"); } @@ -43,18 +48,13 @@ public UnsupportedFunction(String func) { s = func; } - /** - * @serial - */ - String s; + public String getFunction() { + return s; + } public void setFunction(String a) { s = a; setMessage("(unsupported-function " + s + ")"); } - public String getFunction() { - return s; - } - } diff --git a/src/jade/domain/FIPAAgentManagement/UnsupportedValue.java b/src/jade/domain/FIPAAgentManagement/UnsupportedValue.java index 3985519..6bc83bb 100644 --- a/src/jade/domain/FIPAAgentManagement/UnsupportedValue.java +++ b/src/jade/domain/FIPAAgentManagement/UnsupportedValue.java @@ -47,13 +47,13 @@ public UnsupportedValue(String value) { s = value; } + public String getValue() { + return s; + } + public void setValue(String a) { s = a; setMessage("(Unsupported-value \"" + a + "\")"); } - public String getValue() { - return s; - } - } diff --git a/src/jade/domain/FIPAException.java b/src/jade/domain/FIPAException.java index 07c387b..ea4aea9 100644 --- a/src/jade/domain/FIPAException.java +++ b/src/jade/domain/FIPAException.java @@ -79,6 +79,16 @@ public ACLMessage getACLMessage() { return msg; } + /** + * Get the content of the ACL message representing this exception + * + * @return A string representing the message content that describes + * this FIPA exception. + **/ + public String getMessage() { + return content; + } + /** * Set the content of the ACL message representing this exception * @@ -90,16 +100,6 @@ protected void setMessage(String message) { msg.setContent(message); } - /** - * Get the content of the ACL message representing this exception - * - * @return A string representing the message content that describes - * this FIPA exception. - **/ - public String getMessage() { - return content; - } - } diff --git a/src/jade/domain/JADEAgentManagement/CreateAgent.java b/src/jade/domain/JADEAgentManagement/CreateAgent.java index f575098..e0e69f1 100644 --- a/src/jade/domain/JADEAgentManagement/CreateAgent.java +++ b/src/jade/domain/JADEAgentManagement/CreateAgent.java @@ -44,9 +44,9 @@ */ public class CreateAgent implements AgentAction { + private final List arguments = new ArrayList<>(); private String agentName; private String className; - private final List arguments = new ArrayList<>(); private ContainerID container; //#MIDP_EXCLUDE_BEGIN private JADEPrincipal owner; @@ -60,16 +60,6 @@ public class CreateAgent implements AgentAction { public CreateAgent() { } - /** - * Set the agent-name slot of this action. - * - * @param an The local name (i.e. without the platform ID) of the - * agent to create. - */ - public void setAgentName(String an) { - agentName = an; - } - /** * Retrieve the value of the agent-name slot of this * event, containing the local name (i.e. without the platform ID) @@ -83,13 +73,13 @@ public String getAgentName() { } /** - * Set the class-name slot of this action. + * Set the agent-name slot of this action. * - * @param cn The name of the Java class implementing the agent to - * create. + * @param an The local name (i.e. without the platform ID) of the + * agent to create. */ - public void setClassName(String cn) { - className = cn; + public void setAgentName(String an) { + agentName = an; } /** @@ -105,13 +95,13 @@ public String getClassName() { } /** - * Set the container slot of this action. + * Set the class-name slot of this action. * - * @param cid The container identifier of the container where the - * agent is to be created. + * @param cn The name of the Java class implementing the agent to + * create. */ - public void setContainer(ContainerID cid) { - container = cid; + public void setClassName(String cn) { + className = cn; } /** @@ -126,17 +116,18 @@ public ContainerID getContainer() { return container; } - //#MIDP_EXCLUDE_BEGIN - /** - * Set the principal of the owner of the agent to be created. + * Set the container slot of this action. * - * @param p The principal of the owner of the agent to be created. + * @param cid The container identifier of the container where the + * agent is to be created. */ - public void setOwner(JADEPrincipal p) { - owner = p; + public void setContainer(ContainerID cid) { + container = cid; } + //#MIDP_EXCLUDE_BEGIN + /** * @return The principal of the owner of the agent to be created. */ @@ -145,12 +136,12 @@ public JADEPrincipal getOwner() { } /** - * Set the initial credentials to be granted to the agent to be created. + * Set the principal of the owner of the agent to be created. * - * @param c The initial credentials to be granted to the agent to be created. + * @param p The principal of the owner of the agent to be created. */ - public void setInitialCredentials(Credentials c) { - initialCredentials = c; + public void setOwner(JADEPrincipal p) { + owner = p; } /** @@ -159,6 +150,15 @@ public void setInitialCredentials(Credentials c) { public Credentials getInitialCredentials() { return initialCredentials; } + + /** + * Set the initial credentials to be granted to the agent to be created. + * + * @param c The initial credentials to be granted to the agent to be created. + */ + public void setInitialCredentials(Credentials c) { + initialCredentials = c; + } //#MIDP_EXCLUDE_END /** diff --git a/src/jade/domain/JADEAgentManagement/DebugOff.java b/src/jade/domain/JADEAgentManagement/DebugOff.java index a0d55eb..288bd0c 100644 --- a/src/jade/domain/JADEAgentManagement/DebugOff.java +++ b/src/jade/domain/JADEAgentManagement/DebugOff.java @@ -40,8 +40,8 @@ */ public class DebugOff implements AgentAction { - private AID debugger; private final List debuggedAgents = new ArrayList<>(); + private AID debugger; private String password; /** @@ -51,15 +51,6 @@ public class DebugOff implements AgentAction { public DebugOff() { } - /** - * Set the debugger slot of this action. - * - * @param id The agent identifier of the debugger agent. - */ - public void setDebugger(AID id) { - debugger = id; - } - /** * Retrieve the value of the debugger slot of this * action, containing the agent identifier of the debugger agent. @@ -71,6 +62,15 @@ public AID getDebugger() { return debugger; } + /** + * Set the debugger slot of this action. + * + * @param id The agent identifier of the debugger agent. + */ + public void setDebugger(AID id) { + debugger = id; + } + /** * Remove all agent identifiers from the * debugged-agents slot collection of this object. @@ -123,16 +123,6 @@ public ArrayList getCloneOfDebuggedAgents() { } //#APIDOC_EXCLUDE_END - /** - * Set the password slot of this action. - * - * @param p The password used to authenticate the principal - * requesting this action. - */ - public void setPassword(String p) { - password = p; - } - /** * Retrieve the value of the password slot of this * action, containing the password used to authenticate the @@ -145,4 +135,14 @@ public String getPassword() { return password; } + /** + * Set the password slot of this action. + * + * @param p The password used to authenticate the principal + * requesting this action. + */ + public void setPassword(String p) { + password = p; + } + } diff --git a/src/jade/domain/JADEAgentManagement/DebugOn.java b/src/jade/domain/JADEAgentManagement/DebugOn.java index 8ce70bb..b1e7ae2 100644 --- a/src/jade/domain/JADEAgentManagement/DebugOn.java +++ b/src/jade/domain/JADEAgentManagement/DebugOn.java @@ -40,8 +40,8 @@ */ public class DebugOn implements AgentAction { - private AID debugger; private final List debuggedAgents = new ArrayList<>(); + private AID debugger; private String password; @@ -52,15 +52,6 @@ public class DebugOn implements AgentAction { public DebugOn() { } - /** - * Set the debugger slot of this action. - * - * @param id The agent identifier of the debugger agent. - */ - public void setDebugger(AID id) { - debugger = id; - } - /** * Retrieve the value of the debugger slot of this * action, containing the agent identifier of the debugger agent. @@ -72,6 +63,15 @@ public AID getDebugger() { return debugger; } + /** + * Set the debugger slot of this action. + * + * @param id The agent identifier of the debugger agent. + */ + public void setDebugger(AID id) { + debugger = id; + } + /** * Remove all agent identifiers from the * debugged-agents slot collection of this object. @@ -125,16 +125,6 @@ public ArrayList getCloneOfDebuggedAgents() { //#APIDOC_EXCLUDE_END - /** - * Set the password slot of this action. - * - * @param p The password used to authenticate the principal - * requesting this action. - */ - public void setPassword(String p) { - password = p; - } - /** * Retrieve the value of the password slot of this * action, containing the password used to authenticate the @@ -147,4 +137,14 @@ public String getPassword() { return password; } + /** + * Set the password slot of this action. + * + * @param p The password used to authenticate the principal + * requesting this action. + */ + public void setPassword(String p) { + password = p; + } + } diff --git a/src/jade/domain/JADEAgentManagement/InstallMTP.java b/src/jade/domain/JADEAgentManagement/InstallMTP.java index bcb3de7..066e6dd 100644 --- a/src/jade/domain/JADEAgentManagement/InstallMTP.java +++ b/src/jade/domain/JADEAgentManagement/InstallMTP.java @@ -49,15 +49,6 @@ public class InstallMTP implements AgentAction { public InstallMTP() { } - /** - * Set the address slot of this action. - * - * @param a The address URL of the MTP endpoint to install. - */ - public void setAddress(String a) { - address = a; - } - /** * Retrieve the value of the address slot of this * action, containing the address URL of the MTP to install. @@ -70,13 +61,12 @@ public String getAddress() { } /** - * Set the container slot of this action. + * Set the address slot of this action. * - * @param cid The container identifier of the container where the - * new MTP is to be deployed. + * @param a The address URL of the MTP endpoint to install. */ - public void setContainer(ContainerID cid) { - container = cid; + public void setAddress(String a) { + address = a; } /** @@ -92,13 +82,13 @@ public ContainerID getContainer() { } /** - * Set the class-name slot of this action. + * Set the container slot of this action. * - * @param a The name of the Java class implementing the MTP - * endpoint to install. + * @param cid The container identifier of the container where the + * new MTP is to be deployed. */ - public void setClassName(String a) { - className = a; + public void setContainer(ContainerID cid) { + container = cid; } /** @@ -113,4 +103,14 @@ public String getClassName() { return className; } + /** + * Set the class-name slot of this action. + * + * @param a The name of the Java class implementing the MTP + * endpoint to install. + */ + public void setClassName(String a) { + className = a; + } + } diff --git a/src/jade/domain/JADEAgentManagement/JADEManagementOntology.java b/src/jade/domain/JADEAgentManagement/JADEManagementOntology.java index 0622e04..ba645c5 100644 --- a/src/jade/domain/JADEAgentManagement/JADEManagementOntology.java +++ b/src/jade/domain/JADEAgentManagement/JADEManagementOntology.java @@ -50,23 +50,12 @@ public class JADEManagementOntology extends Ontology implements JADEManagementVo // The singleton instance of this ontology private static final Ontology theInstance = new JADEManagementOntology(); - /** - * This method returns the unique instance (according to the singleton - * pattern) of the JADE-Agent-Management-ontology. - * - * @return The singleton Ontology object, containing the - * schemas for the elements of the JADE-Agent-Management-ontology. - */ - public static Ontology getInstance() { - return theInstance; - } - private JADEManagementOntology() { //#MIDP_EXCLUDE_BEGIN super(NAME, new Ontology[]{ExceptionOntology.getInstance(), SerializableOntology.getInstance()}, new BCReflectiveIntrospector()); //#MIDP_EXCLUDE_END - - /*#MIDP_INCLUDE_BEGIN + + /*#MIDP_INCLUDE_BEGIN super(NAME, ExceptionOntology.getInstance(), null); #MIDP_INCLUDE_END*/ @@ -97,13 +86,13 @@ private JADEManagementOntology() { add(new PredicateSchema(ALREADYREGISTERED), AlreadyRegistered.class); add(new PredicateSchema(NOTREGISTERED), NotRegistered.class); //#MIDP_EXCLUDE_END - - /*#MIDP_INCLUDE_BEGIN + + /*#MIDP_INCLUDE_BEGIN // Concepts definitions add(new ConceptSchema(LOCATION)); add(new ConceptSchema(CONTAINERID)); add(new ConceptSchema(PLATFORMID)); - + // AgentActions definitions add(new AgentActionSchema(SHUTDOWNPLATFORM)); add(new AgentActionSchema(KILLCONTAINER)); @@ -198,6 +187,17 @@ private JADEManagementOntology() { } } + /** + * This method returns the unique instance (according to the singleton + * pattern) of the JADE-Agent-Management-ontology. + * + * @return The singleton Ontology object, containing the + * schemas for the elements of the JADE-Agent-Management-ontology. + */ + public static Ontology getInstance() { + return theInstance; + } + /** * This method allows to replace wildcards with a set of defined values. * diff --git a/src/jade/domain/JADEAgentManagement/KillAgent.java b/src/jade/domain/JADEAgentManagement/KillAgent.java index a27c5d5..aba603f 100644 --- a/src/jade/domain/JADEAgentManagement/KillAgent.java +++ b/src/jade/domain/JADEAgentManagement/KillAgent.java @@ -49,15 +49,6 @@ public class KillAgent implements AgentAction { public KillAgent() { } - /** - * Set the agent slot of this action. - * - * @param id The agent identifier of the agent to terminate. - */ - public void setAgent(AID id) { - agent = id; - } - /** * Retrieve the value of the agent slot of this * event, containing the agent identifier of the agent to @@ -71,13 +62,12 @@ public AID getAgent() { } /** - * Set the password slot of this action. + * Set the agent slot of this action. * - * @param p The password to authenticate the principal requesting - * the agent termination. + * @param id The agent identifier of the agent to terminate. */ - public void setPassword(String p) { - password = p; + public void setAgent(AID id) { + agent = id; } /** @@ -92,4 +82,14 @@ public String getPassword() { return password; } + /** + * Set the password slot of this action. + * + * @param p The password to authenticate the principal requesting + * the agent termination. + */ + public void setPassword(String p) { + password = p; + } + } diff --git a/src/jade/domain/JADEAgentManagement/KillContainer.java b/src/jade/domain/JADEAgentManagement/KillContainer.java index 8a5836c..c15b210 100644 --- a/src/jade/domain/JADEAgentManagement/KillContainer.java +++ b/src/jade/domain/JADEAgentManagement/KillContainer.java @@ -49,16 +49,6 @@ public class KillContainer implements AgentAction { public KillContainer() { } - /** - * Set the container slot of this action. - * - * @param cid The container identifier of the container to - * terminate. - */ - public void setContainer(ContainerID cid) { - container = cid; - } - /** * Retrieve the value of the container slot of this * event, containing the container identifier of the container to @@ -72,13 +62,13 @@ public ContainerID getContainer() { } /** - * Set the password slot of this action. + * Set the container slot of this action. * - * @param p The password to authenticate the principal requesting - * the container termination. + * @param cid The container identifier of the container to + * terminate. */ - public void setPassword(String p) { - password = p; + public void setContainer(ContainerID cid) { + container = cid; } /** @@ -93,4 +83,14 @@ public String getPassword() { return password; } + /** + * Set the password slot of this action. + * + * @param p The password to authenticate the principal requesting + * the container termination. + */ + public void setPassword(String p) { + password = p; + } + } diff --git a/src/jade/domain/JADEAgentManagement/QueryAgentsOnLocation.java b/src/jade/domain/JADEAgentManagement/QueryAgentsOnLocation.java index f6f8f62..cc9208d 100644 --- a/src/jade/domain/JADEAgentManagement/QueryAgentsOnLocation.java +++ b/src/jade/domain/JADEAgentManagement/QueryAgentsOnLocation.java @@ -47,15 +47,6 @@ public class QueryAgentsOnLocation implements AgentAction { public QueryAgentsOnLocation() { } - /** - * Set the location slot of this action. - * - * @param loc The location for which the agent list is requested. - */ - public void setLocation(Location loc) { - location = loc; - } - /** * Retrieve the value of the location slot of this * event, containing the location for which the agent list is @@ -68,4 +59,13 @@ public Location getLocation() { return location; } + /** + * Set the location slot of this action. + * + * @param loc The location for which the agent list is requested. + */ + public void setLocation(Location loc) { + location = loc; + } + } diff --git a/src/jade/domain/JADEAgentManagement/SniffOff.java b/src/jade/domain/JADEAgentManagement/SniffOff.java index 10b9503..1673319 100644 --- a/src/jade/domain/JADEAgentManagement/SniffOff.java +++ b/src/jade/domain/JADEAgentManagement/SniffOff.java @@ -40,8 +40,8 @@ */ public class SniffOff implements AgentAction { - private AID sniffer; private final List sniffedAgents = new ArrayList<>(); + private AID sniffer; private String password; @@ -52,15 +52,6 @@ public class SniffOff implements AgentAction { public SniffOff() { } - /** - * Set the sniffer slot of this action. - * - * @param id The agent identifier of the sniffer agent. - */ - public void setSniffer(AID id) { - sniffer = id; - } - /** * Retrieve the value of the sniffer slot of this * action, containing the agent identifier of the sniffer agent. @@ -72,6 +63,15 @@ public AID getSniffer() { return sniffer; } + /** + * Set the sniffer slot of this action. + * + * @param id The agent identifier of the sniffer agent. + */ + public void setSniffer(AID id) { + sniffer = id; + } + /** * Remove all agent identifiers from the * sniffed-agents slot collection of this object. @@ -124,16 +124,6 @@ public ArrayList getCloneOfSniffedAgents() { } //#APIDOC_EXCLUDE_END - /** - * Set the password slot of this action. - * - * @param p The password used to authenticate the principal - * requesting this action. - */ - public void setPassword(String p) { - password = p; - } - /** * Retrieve the value of the password slot of this * action, containing the password used to authenticate the @@ -146,4 +136,14 @@ public String getPassword() { return password; } + /** + * Set the password slot of this action. + * + * @param p The password used to authenticate the principal + * requesting this action. + */ + public void setPassword(String p) { + password = p; + } + } diff --git a/src/jade/domain/JADEAgentManagement/SniffOn.java b/src/jade/domain/JADEAgentManagement/SniffOn.java index 425d60b..ffa6722 100644 --- a/src/jade/domain/JADEAgentManagement/SniffOn.java +++ b/src/jade/domain/JADEAgentManagement/SniffOn.java @@ -40,8 +40,8 @@ */ public class SniffOn implements AgentAction { - private AID sniffer; private final List sniffedAgents = new ArrayList<>(); + private AID sniffer; private String password; @@ -52,15 +52,6 @@ public class SniffOn implements AgentAction { public SniffOn() { } - /** - * Set the sniffer slot of this action. - * - * @param id The agent identifier of the sniffer agent. - */ - public void setSniffer(AID id) { - sniffer = id; - } - /** * Retrieve the value of the sniffer slot of this * action, containing the agent identifier of the sniffer agent. @@ -72,6 +63,15 @@ public AID getSniffer() { return sniffer; } + /** + * Set the sniffer slot of this action. + * + * @param id The agent identifier of the sniffer agent. + */ + public void setSniffer(AID id) { + sniffer = id; + } + /** * Remove all agent identifiers from the * sniffed-agents slot collection of this object. @@ -121,16 +121,6 @@ public ArrayList getCloneOfSniffedAgents() { return (ArrayList) ((ArrayList) sniffedAgents).clone(); } - /** - * Set the password slot of this action. - * - * @param p The password used to authenticate the principal - * requesting this action. - */ - public void setPassword(String p) { - password = p; - } - /** * Retrieve the value of the password slot of this * action, containing the password used to authenticate the @@ -143,5 +133,15 @@ public String getPassword() { return password; } + /** + * Set the password slot of this action. + * + * @param p The password used to authenticate the principal + * requesting this action. + */ + public void setPassword(String p) { + password = p; + } + } diff --git a/src/jade/domain/JADEAgentManagement/UninstallMTP.java b/src/jade/domain/JADEAgentManagement/UninstallMTP.java index e01fe7d..9326b42 100644 --- a/src/jade/domain/JADEAgentManagement/UninstallMTP.java +++ b/src/jade/domain/JADEAgentManagement/UninstallMTP.java @@ -49,15 +49,6 @@ public class UninstallMTP implements AgentAction { public UninstallMTP() { } - /** - * Set the address slot of this action. - * - * @param a The address URL of the MTP endpoint to uninstall. - */ - public void setAddress(String a) { - address = a; - } - /** * Retrieve the value of the address slot of this * action, containing the address URL of the MTP to uninstall. @@ -70,13 +61,12 @@ public String getAddress() { } /** - * Set the container slot of this action. + * Set the address slot of this action. * - * @param cid The container identifier of the container where the - * MTP to uninstall is deployed. + * @param a The address URL of the MTP endpoint to uninstall. */ - public void setContainer(ContainerID cid) { - container = cid; + public void setAddress(String a) { + address = a; } /** @@ -91,5 +81,15 @@ public ContainerID getContainer() { return container; } + /** + * Set the container slot of this action. + * + * @param cid The container identifier of the container where the + * MTP to uninstall is deployed. + */ + public void setContainer(ContainerID cid) { + container = cid; + } + } diff --git a/src/jade/domain/JADEAgentManagement/WhereIsAgentAction.java b/src/jade/domain/JADEAgentManagement/WhereIsAgentAction.java index e9ea917..f680a6a 100644 --- a/src/jade/domain/JADEAgentManagement/WhereIsAgentAction.java +++ b/src/jade/domain/JADEAgentManagement/WhereIsAgentAction.java @@ -49,16 +49,6 @@ public class WhereIsAgentAction implements AgentAction { public WhereIsAgentAction() { } - /** - * Set the agent-identifier slot of this action. - * - * @param id The agent identifier for the agent whose location is - * requested. - */ - public void setAgentIdentifier(AID id) { - agentName = id; - } - /** * Retrieve the value of the agent-identifier slot of * this action, containing the agent identifier for the agent @@ -71,4 +61,14 @@ public AID getAgentIdentifier() { return agentName; } + /** + * Set the agent-identifier slot of this action. + * + * @param id The agent identifier for the agent whose location is + * requested. + */ + public void setAgentIdentifier(AID id) { + agentName = id; + } + } diff --git a/src/jade/domain/KBManagement/DBKB.java b/src/jade/domain/KBManagement/DBKB.java index c178b93..6e9067d 100644 --- a/src/jade/domain/KBManagement/DBKB.java +++ b/src/jade/domain/KBManagement/DBKB.java @@ -49,50 +49,22 @@ */ public abstract class DBKB extends KB { - /** - * Used database driver - */ - protected String driver = "sun.jdbc.odbc.JdbcOdbcDriver"; - /** * This ThreadLocal is used to hold connections and associated additional information * (such as prepared statements) currently used by each Thread */ private final ThreadLocal connections = new ThreadLocal<>(); - - private String url; private final String username; private final String password; - + /** + * Used database driver + */ + protected String driver = "sun.jdbc.odbc.JdbcOdbcDriver"; /** * Specifies whether the KB should delete all existing tables for the DF at startup */ protected boolean cleanTables; - - protected class ConnectionWrapper { - private Connection conn; - private Object info; - - public ConnectionWrapper(Connection conn) { - this.conn = conn; - } - - public Connection getConnection() { - return conn; - } - - public void setConnection(Connection conn) { - this.conn = conn; - } - - public Object getInfo() { - return info; - } - - public void setInfo(Object info) { - this.info = info; - } - } + private String url; /** * Constructs a new DFKB and establishes a connection to the database @@ -220,7 +192,6 @@ private void invalidateConnectionWrapper() throws SQLException { } } - @Override protected Object insert(Object name, Object fact) { try { @@ -373,6 +344,30 @@ public void unsubscribe(SubscriptionResponder.Subscription s) { protected abstract void unsubscribeSingle(SubscriptionResponder.Subscription s) throws SQLException; + protected class ConnectionWrapper { + private Connection conn; + private Object info; + + public ConnectionWrapper(Connection conn) { + this.conn = conn; + } + + public Connection getConnection() { + return conn; + } + + public void setConnection(Connection conn) { + this.conn = conn; + } + + public Object getInfo() { + return info; + } + + public void setInfo(Object info) { + this.info = info; + } + } /** * Inner class EmptyKBIterator diff --git a/src/jade/domain/KBManagement/KB.java b/src/jade/domain/KBManagement/KB.java index 562520b..6a807c8 100644 --- a/src/jade/domain/KBManagement/KB.java +++ b/src/jade/domain/KBManagement/KB.java @@ -39,7 +39,9 @@ */ -/** Base class for AMS and DF Knowledge Base*/ +/** + * Base class for AMS and DF Knowledge Base + */ public abstract class KB { protected LeaseManager lm; protected SubscriptionResponder sr; diff --git a/src/jade/domain/KBManagement/MemKB.java b/src/jade/domain/KBManagement/MemKB.java index ce6c746..0317061 100644 --- a/src/jade/domain/KBManagement/MemKB.java +++ b/src/jade/domain/KBManagement/MemKB.java @@ -43,19 +43,69 @@ */ public abstract class MemKB extends KB { + protected final static int MAX_REGISTER_WITHOUT_CLEAN = 100; + private final Logger logger = Logger.getMyLogger(this.getClass().getName()); protected Map facts = new HashMap<>(); protected Hashtable subscriptions = new Hashtable<>(); protected LeaseManager lm; protected int currentReg = 0; protected SubscriptionResponder sr; + int offSetForSubscriptionToReturn = 0; - protected final static int MAX_REGISTER_WITHOUT_CLEAN = 100; + public MemKB(int maxResultLimit) { + super(maxResultLimit); + } - private final Logger logger = Logger.getMyLogger(this.getClass().getName()); + // Helper method to match two Agent Identifiers + public static boolean matchAID(AID template, AID fact) { + + // Match the GUID in the ':name' slot + String templateName = template.getName(); + if (templateName != null) { + String factName = fact.getName(); + if ((factName == null) || (!templateName.equalsIgnoreCase(factName))) + return false; + } + // Match the address sequence. See 'FIPA Agent Management Specification, Sect. 6.4.2.1' + Iterator itTemplate = template.getAllAddresses(); + Iterator itFact = fact.getAllAddresses(); - public MemKB(int maxResultLimit) { - super(maxResultLimit); + // All the elements in the template sequence must appear in the + // fact sequence, in the same order + while (itTemplate.hasNext()) { + String templateAddr = itTemplate.next(); + + // Search 'templateAddr' into the remaining part of the fact sequence + boolean found = false; + while (!found && itFact.hasNext()) { + String factAddr = itFact.next(); + found = templateAddr.equalsIgnoreCase(factAddr); + } + if (!found) // An element of the template does not appear in the fact sequence + return false; + } + + // Match the resolvers sequence. See 'FIPA Agent Management Specification, Sect. 6.4.2.1' + Iterator itTemplate2 = template.getAllResolvers(); + Iterator itFact2 = fact.getAllResolvers(); + //itTemplate = template.getAllResolvers(); + //itFact = fact.getAllResolvers(); + + while (itTemplate2.hasNext()) { + AID templateRes = itTemplate2.next(); + + // Search 'templateRes' into the remaining part of the fact sequence + boolean found = false; + while (!found && itFact2.hasNext()) { + AID factRes = itFact2.next(); + found = matchAID(templateRes, factRes); // Recursive call + } + if (!found) // An element of the template does not appear in the fact sequence + return false; + } + + return true; } protected Object insert(Object name, Object fact) { @@ -75,7 +125,6 @@ protected Object remove(Object name) { // This abstract method has to perform pattern matching protected abstract boolean match(DFAgentDescription template, DFAgentDescription fact); - protected abstract void clean(); public List search(DFAgentDescription template, int maxResults) { @@ -113,31 +162,25 @@ public void subscribe(Object dfd, SubscriptionResponder.Subscription s) throws N } } - public Enumeration getSubscriptionDfAgentDescriptions() { return subscriptions.keys(); } - private SubscriptionResponder.Subscription getSubscription(Object key) { return subscriptions.get(key); } - // RITORNA Lista delle sottoscrizioni public Enumeration getSubscriptions() { return subscriptions.elements(); } - int offSetForSubscriptionToReturn = 0; - // RITORNA Lista delle sottoscrizioni public Enumeration getSubscriptions(int offset) { // FIXME to do if this operation return a lot of subscriptions return null; } - public void unsubscribe(SubscriptionResponder.Subscription sub) { ACLMessage aclSub = sub.getMessage(); @@ -157,57 +200,4 @@ public void unsubscribe(SubscriptionResponder.Subscription sub) { } - // Helper method to match two Agent Identifiers - public static boolean matchAID(AID template, AID fact) { - - // Match the GUID in the ':name' slot - String templateName = template.getName(); - if (templateName != null) { - String factName = fact.getName(); - if ((factName == null) || (!templateName.equalsIgnoreCase(factName))) - return false; - } - - // Match the address sequence. See 'FIPA Agent Management Specification, Sect. 6.4.2.1' - Iterator itTemplate = template.getAllAddresses(); - Iterator itFact = fact.getAllAddresses(); - - // All the elements in the template sequence must appear in the - // fact sequence, in the same order - while (itTemplate.hasNext()) { - String templateAddr = itTemplate.next(); - - // Search 'templateAddr' into the remaining part of the fact sequence - boolean found = false; - while (!found && itFact.hasNext()) { - String factAddr = itFact.next(); - found = templateAddr.equalsIgnoreCase(factAddr); - } - if (!found) // An element of the template does not appear in the fact sequence - return false; - } - - // Match the resolvers sequence. See 'FIPA Agent Management Specification, Sect. 6.4.2.1' - Iterator itTemplate2 = template.getAllResolvers(); - Iterator itFact2 = fact.getAllResolvers(); - //itTemplate = template.getAllResolvers(); - //itFact = fact.getAllResolvers(); - - while (itTemplate2.hasNext()) { - AID templateRes = itTemplate2.next(); - - // Search 'templateRes' into the remaining part of the fact sequence - boolean found = false; - while (!found && itFact2.hasNext()) { - AID factRes = itFact2.next(); - found = matchAID(templateRes, factRes); // Recursive call - } - if (!found) // An element of the template does not appear in the fact sequence - return false; - } - - return true; - } - - } diff --git a/src/jade/domain/KBSubscriptionManager.java b/src/jade/domain/KBSubscriptionManager.java index 400fdfb..6ccbf61 100644 --- a/src/jade/domain/KBSubscriptionManager.java +++ b/src/jade/domain/KBSubscriptionManager.java @@ -46,18 +46,28 @@ */ class KBSubscriptionManager implements SubscriptionResponder.SubscriptionManager { private final Logger myLogger = Logger.getMyLogger(getClass().getName()); - - private Map subscriptionsCache = new HashMap<>(); - private SubscriptionInfo[] subscriptions = null; - KB kBase; ContentManager cm; + private Map subscriptionsCache = new HashMap<>(); + private SubscriptionInfo[] subscriptions = null; public KBSubscriptionManager(KB k) { super(); kBase = k; } + private static SubscriptionInfo[] toArray(Map m) { + Collection c = m.values(); + SubscriptionInfo[] result = new SubscriptionInfo[c.size()]; + Iterator it = c.iterator(); + int i = 0; + while (it.hasNext()) { + result[i] = it.next(); + ++i; + } + return result; + } + public void setContentManager(ContentManager c) { cm = c; } @@ -112,7 +122,6 @@ public boolean register(SubscriptionResponder.Subscription sub) throws RefuseExc return false; } - public boolean deregister(SubscriptionResponder.Subscription sub) throws FailureException { if (myLogger.isLoggable(Logger.CONFIG)) { ACLMessage subMessage = sub.getMessage(); @@ -130,7 +139,6 @@ public boolean deregister(SubscriptionResponder.Subscription sub) throws Failure return false; } - /** * Handle registrations/deregistrations/modifications by notifying * subscribed agents if necessary. @@ -160,7 +168,7 @@ void handleChange(DFAgentDescription dfd, DFAgentDescription oldDfd) { } private Map loadSubscriptionsCache() { - Map m = new HashMap(); + Map m = new HashMap<>(); Enumeration e = kBase.getSubscriptions(); while (e.hasMoreElements()) { SubscriptionResponder.Subscription sub = (SubscriptionResponder.Subscription) e.nextElement(); @@ -200,18 +208,6 @@ private void notify(SubscriptionResponder.Subscription sub, List m) { - Collection c = m.values(); - SubscriptionInfo[] result = new SubscriptionInfo[c.size()]; - Iterator it = c.iterator(); - int i = 0; - while (it.hasNext()) { - result[i] = it.next(); - ++i; - } - return result; - } - /** * Inner class SubscriptionInfo * This class associates a Subscription object with the DFAgentDescription that acts as diff --git a/src/jade/domain/RequestFIPAServiceBehaviour.java b/src/jade/domain/RequestFIPAServiceBehaviour.java index 75b8ab1..c9d0658 100644 --- a/src/jade/domain/RequestFIPAServiceBehaviour.java +++ b/src/jade/domain/RequestFIPAServiceBehaviour.java @@ -58,33 +58,22 @@ public class RequestFIPAServiceBehaviour extends SimpleAchieveREInitiator { /** - * Exception class for timeouts. This exception is thrown when trying - * to obtain an ACLMessage from an Handle - * and no message has been yet received and the timeout limit is not yet - * elapsed. - * - * @see jade.core.behaviours.ReceiverBehaviour.Handle#getMessage() + * @serial */ - public static class NotYetReady extends Exception { - NotYetReady() { - super("Requested message is not ready yet."); - } - } - - + //to set a timeout for the search request: 5 minutes. + private final long timeout = 300000; /** * @serial */ - private ACLMessage lastMsg; + private final FIPAException outcome = null; /** * @serial */ - private boolean notYetReady; + private ACLMessage lastMsg; /** * @serial */ - //to set a timeout for the search request: 5 minutes. - private final long timeout = 300000; + private boolean notYetReady; /** @@ -242,10 +231,6 @@ protected void handleAllResponses(Vector reply) { // This exception object records last outcome. When it is // 'null', all went OK. - /** - * @serial - */ - private final FIPAException outcome = null; /** * This public method allows to get the INFORM message received in the final @@ -265,8 +250,6 @@ public ACLMessage getLastMsg() throws FIPAException, NotYetReady { return lastMsg; } - //#ALL_EXCLUDE_BEGIN - /** * This public method allows to get the results of a search operation. * @@ -283,7 +266,8 @@ public List getSearchResult() throws FIPAException, NotYetReady { Collections.addAll(l, r); return l; } - //#ALL_EXCLUDE_END + + //#ALL_EXCLUDE_BEGIN /** * This public method allows to get the results of a search operation. @@ -312,5 +296,20 @@ public Object[] getSearchResults() throws FIPAException, NotYetReady { return l.toArray(); } + //#ALL_EXCLUDE_END + + /** + * Exception class for timeouts. This exception is thrown when trying + * to obtain an ACLMessage from an Handle + * and no message has been yet received and the timeout limit is not yet + * elapsed. + * + * @see jade.core.behaviours.ReceiverBehaviour.Handle#getMessage() + */ + public static class NotYetReady extends Exception { + NotYetReady() { + super("Requested message is not ready yet."); + } + } } diff --git a/src/jade/domain/RequestManagementBehaviour.java b/src/jade/domain/RequestManagementBehaviour.java index dd2a1a4..4e17fba 100644 --- a/src/jade/domain/RequestManagementBehaviour.java +++ b/src/jade/domain/RequestManagementBehaviour.java @@ -47,8 +47,8 @@ * @author Giovanni Caire - Tilab */ public abstract class RequestManagementBehaviour extends SimpleAchieveREResponder { - private ACLMessage notification; protected Logger myLogger; + private ACLMessage notification; protected RequestManagementBehaviour(Agent a, MessageTemplate mt) { super(a, mt); @@ -84,18 +84,12 @@ protected ACLMessage prepareResponse(ACLMessage request) throws NotUnderstoodExc notification = performAction(slAction, request); // Action OK - } catch (OntologyException oe) { + } catch (OntologyException | CodecException oe) { // Error decoding request --> NOT_UNDERSTOOD response = request.createReply(); response.setPerformative(ACLMessage.NOT_UNDERSTOOD); response.setContent("(" + ExceptionVocabulary.UNRECOGNISEDVALUE + " content)"); t = oe; - } catch (CodecException ce) { - // Error decoding request --> NOT_UNDERSTOOD - response = request.createReply(); - response.setPerformative(ACLMessage.NOT_UNDERSTOOD); - response.setContent("(" + ExceptionVocabulary.UNRECOGNISEDVALUE + " content)"); - t = ce; } catch (RefuseException re) { // RefuseException thrown during action execution --> REFUSE response = request.createReply(); diff --git a/src/jade/domain/ams.java b/src/jade/domain/ams.java index 8706c12..9e4715d 100644 --- a/src/jade/domain/ams.java +++ b/src/jade/domain/ams.java @@ -1083,7 +1083,7 @@ public AMSEventQueueFeeder getQueueFeeder() { return queueFeeder; } // GC-ADD-18022007-START - + /* Put a BornAgent event in the AMS event queue * @@ -1466,4 +1466,4 @@ public void action() { }); } -} +} \ No newline at end of file diff --git a/src/jade/domain/df.java b/src/jade/domain/df.java index 7bf24db..6148c9f 100644 --- a/src/jade/domain/df.java +++ b/src/jade/domain/df.java @@ -227,35 +227,6 @@ public class df extends GuiAgent implements DFGUIAdapter { // FIXME The size of the cache must be read from the Profile private final static int SEARCH_ID_CACHE_SIZE = 16; - private final jade.util.HashCache searchIdCache = new jade.util.HashCache(SEARCH_ID_CACHE_SIZE); - private int searchIdCnt = 0; - - // The DF federated with this DF - private final List children = new ArrayList<>(); - // The DF this DF is federated with - private final List parents = new ArrayList<>(); - // Maps a parent DF to the description used by this DF to federate with that parent - private final HashMap dscDFParentMap = new HashMap<>(); - // Maps an action that is being serviced by a Behaviour to the - // request message that activated the Behaviour and the notification message - // to be sent back (as soon as the Behaviour will complete) to the requester - private final HashMap pendingRequests = new HashMap<>(); - - // The GUI of this DF - private DFGUIInterface gui; - - // Current description of this df - private DFAgentDescription myDescription = null; - - private final Codec codec = new SLCodec(); - - //#PJAVA_EXCLUDE_BEGIN - // This is used in case a pool-size != 0 is specified to serve FIPA requests - private ThreadedBehaviourFactory tbf; - - private AMSSubscriber amsSubscriber; - //#PJAVA_EXCLUDE_END - // Configuration parameter keys private static final String AUTOCLEANUP = "jade_domain_df_autocleanup"; private static final String POOLSIZE = "jade_domain_df_poolsize"; @@ -268,14 +239,35 @@ public class df extends GuiAgent implements DFGUIAdapter { private static final String DB_PASSWORD = "jade_domain_df_db-password"; private static final String KB_FACTORY = "jade_domain_df_kb-factory"; private static final String DB_DEFAULT = "jade_domain_df_db-default"; + //#PJAVA_EXCLUDE_END private static final String DB_CLEANTABLES = "jade_domain_df_db-cleantables"; private static final String DB_ABORTONERROR = "jade_domain_df_db-abortonerror"; - // Limit of searchConstraints.maxresult // FIPA Agent Management Specification doc num: SC00023J (6.1.4 Search Constraints) // a negative value of maxresults indicates that the sender agent is willing to receive // all available results private static final String DEFAULT_MAX_RESULTS = "100"; + private final jade.util.HashCache searchIdCache = new jade.util.HashCache(SEARCH_ID_CACHE_SIZE); + // The DF federated with this DF + private final List children = new ArrayList<>(); + // The DF this DF is federated with + private final List parents = new ArrayList<>(); + // Maps a parent DF to the description used by this DF to federate with that parent + private final HashMap dscDFParentMap = new HashMap<>(); + // Maps an action that is being serviced by a Behaviour to the + // request message that activated the Behaviour and the notification message + // to be sent back (as soon as the Behaviour will complete) to the requester + private final HashMap pendingRequests = new HashMap<>(); + private final Codec codec = new SLCodec(); + private int searchIdCnt = 0; + // The GUI of this DF + private DFGUIInterface gui; + // Current description of this df + private DFAgentDescription myDescription = null; + //#PJAVA_EXCLUDE_BEGIN + // This is used in case a pool-size != 0 is specified to serve FIPA requests + private ThreadedBehaviourFactory tbf; + private AMSSubscriber amsSubscriber; /* * This is the actual value for the limit on the maximum number of results to be * returned in case of an ulimited search. This value is read from the Profile, @@ -747,142 +739,6 @@ private void performRecursiveSearch(List localResults, DFAge addBehaviour(new RecursiveSearchHandler(localResults, dfd, newConstr, action)); } - /** - * Inner class RecursiveSearchHandler. - * This is a behaviour handling recursive searches i.e. searches that - * must be propagated to children (federated) DFs. - */ - private class RecursiveSearchHandler extends AchieveREInitiator { - private static final long DEFAULTTIMEOUT = 300000; // 5 minutes - - private final List results; - private final DFAgentDescription template; - private final SearchConstraints constraints; - private final Search action; - private final int maxExpectedResults; - private int receivedResults; - - /** - * Construct a new RecursiveSearchHandler. - * - * @param results The search results. Initially this includes the items found - * locally. - * @param template The DFAgentDescription used as tamplate for the search. - * @param constraints The constraints for the search to be propagated. - * @param action The original Search action. This is used as a key to retrieve - * the incoming REQUEST message. - */ - private RecursiveSearchHandler(List results, DFAgentDescription template, SearchConstraints constraints, Search action) { - super(df.this, null); - - this.results = results; - this.template = template; - this.constraints = constraints; - this.action = action; - - maxExpectedResults = constraints.getMaxResults().intValue(); - receivedResults = 0; - } - - /** - * We broadcast the search REQUEST to all children (federated) DFs in parallel. - */ - protected Vector prepareRequests(ACLMessage request) { - Vector requests = null; - ACLMessage incomingRequest = pendingRequests.get(action); - if (incomingRequest != null) { - Date deadline = incomingRequest.getReplyByDate(); - if (deadline == null) { - deadline = new Date(System.currentTimeMillis() + DEFAULTTIMEOUT); - } - requests = new Vector<>(children.size()); - for (AID childDF : children) { - ACLMessage msg = DFService.createRequestMessage(myAgent, childDF, FIPAManagementVocabulary.SEARCH, template, constraints); - msg.setReplyByDate(deadline); - requests.addElement(msg); - } - } - return requests; - } - - /** - * As long as we receive the replies we update the results. If we reach the - * max-results we send back the notification to the requester and discard - * successive replies. - */ - protected void handleInform(ACLMessage inform) { - if (logger.isLoggable(Logger.CONFIG)) - logger.log(Logger.CONFIG, "Agent " + getLocalName() + " - Recursive search result received from " + inform.getSender().getName() + "."); - int cnt = 0; - if (receivedResults < maxExpectedResults) { - try { - DFAgentDescription[] dfds = DFService.decodeResult(inform.getContent()); - for (DFAgentDescription dfd : dfds) { - // We add the item only if not already present - if (addResult(dfd)) { - receivedResults++; - cnt++; - if (receivedResults >= maxExpectedResults) { - sendPendingNotification(action, results); - } - } - } - } catch (Exception e) { - if (logger.isLoggable(Logger.SEVERE)) - logger.log(Logger.SEVERE, "Agent " + getLocalName() + " - Error decoding reply from federated DF " + inform.getSender().getName() + " during recursive search [" + e + "]."); - } - } - if (logger.isLoggable(Logger.CONFIG)) - logger.log(Logger.CONFIG, "Agent " + getLocalName() + " - " + cnt + " new items found in recursive search."); - } - - protected void handleRefuse(ACLMessage refuse) { - if (logger.isLoggable(Logger.WARNING)) - logger.log(Logger.WARNING, "Agent " + getLocalName() + " - REFUSE received from federated DF " + refuse.getSender().getName() + " during recursive search."); - } - - protected void handleFailure(ACLMessage failure) { - // FIXME: In general this is due to a federation loop (search-id already used) - // In this case no warning must be printed --> We should use FINE log level in that case - if (logger.isLoggable(Logger.WARNING)) - logger.log(Logger.WARNING, "Agent " + getLocalName() + " - FAILURE received from federated DF " + failure.getSender().getName() + " during recursive search."); - } - - protected void handleNotUnderstood(ACLMessage notUnderstood) { - if (logger.isLoggable(Logger.WARNING)) - logger.log(Logger.WARNING, "Agent " + getLocalName() + " - NOT_UNDERSTOOD received from federated DF " + notUnderstood.getSender().getName() + " during recursive search."); - } - - protected void handleOutOfSequence(ACLMessage msg) { - if (logger.isLoggable(Logger.WARNING)) - logger.log(Logger.WARNING, "Agent " + getLocalName() + " - Out of sequence message " + ACLMessage.getPerformative(msg.getPerformative()) + " received from " + msg.getSender().getName() + " during recursive search."); - } - - public int onEnd() { - // Send back the notification to the originator of the - // search (unless already sent) - if (receivedResults < maxExpectedResults) { - sendPendingNotification(action, results); - } - return super.onEnd(); - } - - private boolean addResult(DFAgentDescription newDfd) { - for (DFAgentDescription result : results) { - if (result.getName().equals(newDfd.getName())) { - return false; - } - } - results.add(newDfd); - return true; - } - } // END of inner class RecursiveSearchHandler - - - ////////////////////////////////////////////////////// - // Methods actually accessing the DF Knowledge base - ////////////////////////////////////////////////////// - protected void DFRegister(DFAgentDescription dfd) throws AlreadyRegistered { //checkMandatorySlots(FIPAAgentManagementOntology.REGISTER, dfd); @@ -910,6 +766,11 @@ protected void DFRegister(DFAgentDescription dfd) throws AlreadyRegistered { } + + ////////////////////////////////////////////////////// + // Methods actually accessing the DF Knowledge base + ////////////////////////////////////////////////////// + //this method is called into the prepareResponse of the DFFipaAgentManagementBehaviour to perform a Deregister action protected void DFDeregister(DFAgentDescription dfd) throws NotRegistered { //checkMandatorySlots(FIPAAgentManagementOntology.DEREGISTER, dfd); @@ -938,7 +799,6 @@ protected void DFDeregister(DFAgentDescription dfd) throws NotRegistered { } } - protected void DFModify(DFAgentDescription dfd) throws NotRegistered { //checkMandatorySlots(FIPAAgentManagementOntology.MODIFY, dfd); Object old = agentDescriptions.register(dfd.getName(), dfd); @@ -966,11 +826,6 @@ protected KBIterator DFIteratedSearch(DFAgentDescription dfd) { return agentDescriptions.iterator(dfd); } - - //////////////////////////////////////////////////////////////// - // Methods serving the actions of the FIPA Management ontology - //////////////////////////////////////////////////////////////// - /** * Serve the Register action of the FIPA management ontology. */ @@ -991,6 +846,11 @@ protected void registerAction(Register r, AID requester) throws FIPAException { DFRegister(dfd); } + + //////////////////////////////////////////////////////////////// + // Methods serving the actions of the FIPA Management ontology + //////////////////////////////////////////////////////////////// + /** * Serve the Deregister action of the FIPA management ontology. */ @@ -1078,10 +938,6 @@ protected KBIterator iteratedSearchAction(Search s, AID requester) throws FIPAEx return DFIteratedSearch(dfd); } - //////////////////////////////////////////////////////////////// - // Methods serving the actions of the JADE Management ontology - //////////////////////////////////////////////////////////////// - /** * Serve the ShowGui action of the JADE management ontology. * Package scoped since it is called by DFJadeAgentManagementBehaviour. @@ -1097,9 +953,9 @@ void showGuiAction(ShowGui sg, AID requester) throws FailureException { } } - ////////////////////////////////////////////////////////// - // Methods serving the actions of the DF-Applet ontology - ////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////// + // Methods serving the actions of the JADE Management ontology + //////////////////////////////////////////////////////////////// /** * Serve the GetParents action of the DF-Applet ontology @@ -1111,6 +967,9 @@ List getParentsAction(GetParents action, AID requester) { return parents; } + ////////////////////////////////////////////////////////// + // Methods serving the actions of the DF-Applet ontology + ////////////////////////////////////////////////////////// /** * Serve the GetDescription action of the DF-Applet ontology @@ -1257,13 +1116,6 @@ public int onEnd() { addBehaviour(b); } - - //#APIDOC_EXCLUDE_BEGIN - - /////////////////////////////////////////////////////////// - // GUI Management: DFGUIAdapter interface implementation - /////////////////////////////////////////////////////////// - protected void onGuiEvent(GuiEvent ev) { try { switch (ev.getType()) { @@ -1422,7 +1274,12 @@ public int onEnd() { } } - //#APIDOC_EXCLUDE_END + + //#APIDOC_EXCLUDE_BEGIN + + /////////////////////////////////////////////////////////// + // GUI Management: DFGUIAdapter interface implementation + /////////////////////////////////////////////////////////// /** * This method returns the description of an agent registered with the DF. @@ -1437,6 +1294,7 @@ public DFAgentDescription getDFAgentDsc(AID name) throws FIPAException { return l.get(0); } + //#APIDOC_EXCLUDE_END /** * This method returns the current description of this DF @@ -1445,6 +1303,20 @@ public DFAgentDescription getDescriptionOfThisDF() { return myDescription; } + /** + * This method set the description of the df according to the DFAgentDescription passed. + * The programmers can call this method to provide a different initialization of the description of the df they are implementing. + * The method is called inside the setup of the agent and set the df description using a default description. + */ + protected void setDescriptionOfThisDF(DFAgentDescription dfd) { + myDescription = dfd; + myDescription.setName(getAID()); + if (!isADF(myDescription)) { + if (logger.isLoggable(Logger.WARNING)) + logger.log(Logger.WARNING, "Agent " + getLocalName() + " - The description set for this DF does not include a \"fipa-df\" service."); + } + } + /** * This method returns the description of this df used to federate with the given parent */ @@ -1514,20 +1386,6 @@ private DFAgentDescription getDefaultDescription() { return out; } - /** - * This method set the description of the df according to the DFAgentDescription passed. - * The programmers can call this method to provide a different initialization of the description of the df they are implementing. - * The method is called inside the setup of the agent and set the df description using a default description. - */ - protected void setDescriptionOfThisDF(DFAgentDescription dfd) { - myDescription = dfd; - myDescription.setName(getAID()); - if (!isADF(myDescription)) { - if (logger.isLoggable(Logger.WARNING)) - logger.log(Logger.WARNING, "Agent " + getLocalName() + " - The description set for this DF does not include a \"fipa-df\" service."); - } - } - /** * This method can be used to add a parent (a DF this DF is federated with). * @@ -1566,7 +1424,6 @@ void removePendingRequest(Object key) { pendingRequests.remove(key); } - /** * Send the notification related to an action that has been processed * by a Behaviour. @@ -1647,11 +1504,142 @@ private void checkSearchId(String searchId) throws FIPAException { private boolean isADF(DFAgentDescription dfd) { try { var l = dfd.getAllServices(); - var sd = l.get(l.size()-1); + var sd = l.get(l.size() - 1); return sd.getType().equalsIgnoreCase("fipa-df"); } catch (Exception e) { return false; } } + + /** + * Inner class RecursiveSearchHandler. + * This is a behaviour handling recursive searches i.e. searches that + * must be propagated to children (federated) DFs. + */ + private class RecursiveSearchHandler extends AchieveREInitiator { + private static final long DEFAULTTIMEOUT = 300000; // 5 minutes + + private final List results; + private final DFAgentDescription template; + private final SearchConstraints constraints; + private final Search action; + private final int maxExpectedResults; + private int receivedResults; + + /** + * Construct a new RecursiveSearchHandler. + * + * @param results The search results. Initially this includes the items found + * locally. + * @param template The DFAgentDescription used as tamplate for the search. + * @param constraints The constraints for the search to be propagated. + * @param action The original Search action. This is used as a key to retrieve + * the incoming REQUEST message. + */ + private RecursiveSearchHandler(List results, DFAgentDescription template, SearchConstraints constraints, Search action) { + super(df.this, null); + + this.results = results; + this.template = template; + this.constraints = constraints; + this.action = action; + + maxExpectedResults = constraints.getMaxResults().intValue(); + receivedResults = 0; + } + + /** + * We broadcast the search REQUEST to all children (federated) DFs in parallel. + */ + protected Vector prepareRequests(ACLMessage request) { + Vector requests = null; + ACLMessage incomingRequest = pendingRequests.get(action); + if (incomingRequest != null) { + Date deadline = incomingRequest.getReplyByDate(); + if (deadline == null) { + deadline = new Date(System.currentTimeMillis() + DEFAULTTIMEOUT); + } + requests = new Vector<>(children.size()); + for (AID childDF : children) { + ACLMessage msg = DFService.createRequestMessage(myAgent, childDF, FIPAManagementVocabulary.SEARCH, template, constraints); + msg.setReplyByDate(deadline); + requests.addElement(msg); + } + } + return requests; + } + + /** + * As long as we receive the replies we update the results. If we reach the + * max-results we send back the notification to the requester and discard + * successive replies. + */ + protected void handleInform(ACLMessage inform) { + if (logger.isLoggable(Logger.CONFIG)) + logger.log(Logger.CONFIG, "Agent " + getLocalName() + " - Recursive search result received from " + inform.getSender().getName() + "."); + int cnt = 0; + if (receivedResults < maxExpectedResults) { + try { + DFAgentDescription[] dfds = DFService.decodeResult(inform.getContent()); + for (DFAgentDescription dfd : dfds) { + // We add the item only if not already present + if (addResult(dfd)) { + receivedResults++; + cnt++; + if (receivedResults >= maxExpectedResults) { + sendPendingNotification(action, results); + } + } + } + } catch (Exception e) { + if (logger.isLoggable(Logger.SEVERE)) + logger.log(Logger.SEVERE, "Agent " + getLocalName() + " - Error decoding reply from federated DF " + inform.getSender().getName() + " during recursive search [" + e + "]."); + } + } + if (logger.isLoggable(Logger.CONFIG)) + logger.log(Logger.CONFIG, "Agent " + getLocalName() + " - " + cnt + " new items found in recursive search."); + } + + protected void handleRefuse(ACLMessage refuse) { + if (logger.isLoggable(Logger.WARNING)) + logger.log(Logger.WARNING, "Agent " + getLocalName() + " - REFUSE received from federated DF " + refuse.getSender().getName() + " during recursive search."); + } + + protected void handleFailure(ACLMessage failure) { + // FIXME: In general this is due to a federation loop (search-id already used) + // In this case no warning must be printed --> We should use FINE log level in that case + if (logger.isLoggable(Logger.WARNING)) + logger.log(Logger.WARNING, "Agent " + getLocalName() + " - FAILURE received from federated DF " + failure.getSender().getName() + " during recursive search."); + } + + protected void handleNotUnderstood(ACLMessage notUnderstood) { + if (logger.isLoggable(Logger.WARNING)) + logger.log(Logger.WARNING, "Agent " + getLocalName() + " - NOT_UNDERSTOOD received from federated DF " + notUnderstood.getSender().getName() + " during recursive search."); + } + + protected void handleOutOfSequence(ACLMessage msg) { + if (logger.isLoggable(Logger.WARNING)) + logger.log(Logger.WARNING, "Agent " + getLocalName() + " - Out of sequence message " + ACLMessage.getPerformative(msg.getPerformative()) + " received from " + msg.getSender().getName() + " during recursive search."); + } + + public int onEnd() { + // Send back the notification to the originator of the + // search (unless already sent) + if (receivedResults < maxExpectedResults) { + sendPendingNotification(action, results); + } + return super.onEnd(); + } + + private boolean addResult(DFAgentDescription newDfd) { + for (DFAgentDescription result : results) { + if (result.getName().equals(newDfd.getName())) { + return false; + } + } + results.add(newDfd); + return true; + } + } // END of inner class RecursiveSearchHandler //#APIDOC_EXCLUDE_END } diff --git a/src/jade/domain/introspection/ACLMessage.java b/src/jade/domain/introspection/ACLMessage.java index 153b854..407f8a1 100644 --- a/src/jade/domain/introspection/ACLMessage.java +++ b/src/jade/domain/introspection/ACLMessage.java @@ -44,16 +44,6 @@ public class ACLMessage implements Concept { public ACLMessage() { } - /** - * Set the message envelope. - * - * @param e The transport-level envelope to attach to this ACL - * message. - */ - public void setEnvelope(Envelope e) { - env = e; - } - /** * Retrieve the message envelope. * @@ -65,14 +55,13 @@ public Envelope getEnvelope() { } /** - * Set the representation of the message payload. + * Set the message envelope. * - * @param r The name of the representation expressing the message - * payload. + * @param e The transport-level envelope to attach to this ACL + * message. */ - public void setAclRepresentation(String r) { - if (env != null) - env.setAclRepresentation(r); + public void setEnvelope(Envelope e) { + env = e; } /** @@ -88,14 +77,14 @@ public String getAclRepresentation() { } /** - * Set the payload (i.e. the speech act level part) of this ACL - * message. + * Set the representation of the message payload. * - * @param p A string containing the encoding of the payload - * according to a concrete ACL representaiton. + * @param r The name of the representation expressing the message + * payload. */ - public void setPayload(String p) { - payload = p; + public void setAclRepresentation(String r) { + if (env != null) + env.setAclRepresentation(r); } /** @@ -109,4 +98,15 @@ public String getPayload() { return payload; } + /** + * Set the payload (i.e. the speech act level part) of this ACL + * message. + * + * @param p A string containing the encoding of the payload + * according to a concrete ACL representaiton. + */ + public void setPayload(String p) { + payload = p; + } + } diff --git a/src/jade/domain/introspection/AMSSubscriber.java b/src/jade/domain/introspection/AMSSubscriber.java index 8f9d8b2..63782f5 100644 --- a/src/jade/domain/introspection/AMSSubscriber.java +++ b/src/jade/domain/introspection/AMSSubscriber.java @@ -48,31 +48,19 @@ public abstract class AMSSubscriber extends SimpleBehaviour { public static final String AMS_SUBSCRIPTION = "tool-subscription"; public static final String AMS_CANCELLATION = "tool-cancellation"; public static final String PLATFORM_EVENTS = "platform-events"; - - private AID ams = null; private final ACLMessage AMSSubscription = new ACLMessage(ACLMessage.SUBSCRIBE); private final ACLMessage AMSCancellation = new ACLMessage(ACLMessage.CANCEL); - - private MessageTemplate listenTemplate; - private boolean active = true; - // Ignore case for event names //#DOTNET_EXCLUDE_BEGIN private final Map handlers = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + private AID ams = null; + private MessageTemplate listenTemplate; + private boolean active = true; //#DOTNET_EXCLUDE_END /*#DOTNET_INCLUDE_BEGIN private Map handlers = new TreeMap(new CaseInsensitiveComparator() ); #DOTNET_INCLUDE_END*/ - /** - * This interface must be implemented by concrete event handlers - * installed by this AMSSubscriber. - */ - public interface EventHandler extends Serializable { - void handle(Event ev); - } - - /** * Construct an AMSSubscriber behaviour to receive notifications about platform events * from the local AMS @@ -94,6 +82,7 @@ public AMSSubscriber() { installHandlers(handlers); } + /** * Construct an AMSSubscriber behaviour to receive notifications about platform events * from the AMS of a remote platform. @@ -205,6 +194,14 @@ public final ACLMessage getSubscribe() { public final ACLMessage getCancel() { return AMSCancellation; } + + /** + * This interface must be implemented by concrete event handlers + * installed by this AMSSubscriber. + */ + public interface EventHandler extends Serializable { + void handle(Event ev); + } /*#DOTNET_INCLUDE_BEGIN //This class is used to obtain a Comparator for compare two strings diff --git a/src/jade/domain/introspection/AddedBehaviour.java b/src/jade/domain/introspection/AddedBehaviour.java index 5c31444..36f885f 100644 --- a/src/jade/domain/introspection/AddedBehaviour.java +++ b/src/jade/domain/introspection/AddedBehaviour.java @@ -53,16 +53,6 @@ public class AddedBehaviour implements Event { public AddedBehaviour() { } - /** - * Set the agent of this event. - * - * @param id The agent identifier of the agent the behaviour was - * added to. - */ - public void setAgent(AID id) { - agent = id; - } - /** * Retrieve the value of the agent slot of this * event, containing the agent identifier of the agent the @@ -76,13 +66,13 @@ public AID getAgent() { } /** - * Set the behaviour of this event. + * Set the agent of this event. * - * @param id The behaviour identifier of the newly added - * behaviour. + * @param id The agent identifier of the agent the behaviour was + * added to. */ - public void setBehaviour(BehaviourID id) { - behaviour = id; + public void setAgent(AID id) { + agent = id; } /** @@ -97,6 +87,16 @@ public BehaviourID getBehaviour() { return behaviour; } + /** + * Set the behaviour of this event. + * + * @param id The behaviour identifier of the newly added + * behaviour. + */ + public void setBehaviour(BehaviourID id) { + behaviour = id; + } + /** * Retrieve the name of this event. * diff --git a/src/jade/domain/introspection/AddedContainer.java b/src/jade/domain/introspection/AddedContainer.java index 11db9ab..6d3e462 100644 --- a/src/jade/domain/introspection/AddedContainer.java +++ b/src/jade/domain/introspection/AddedContainer.java @@ -58,16 +58,6 @@ public String getName() { return NAME; } - /** - * Set the container of this event. - * - * @param id The container identifier of the newly added - * container. - */ - public void setContainer(ContainerID id) { - container = id; - } - /** * Retrieve the value of the container slot of this * event, containing the container identifier of the newly added @@ -81,13 +71,13 @@ public ContainerID getContainer() { } /** - * Set the ownership of this event. + * Set the container of this event. * - * @param o The name of the entity owning the newly added - * container. + * @param id The container identifier of the newly added + * container. */ - public void setOwnership(String o) { - ownership = o; + public void setContainer(ContainerID id) { + container = id; } /** @@ -102,4 +92,14 @@ public String getOwnership() { return ownership; } + /** + * Set the ownership of this event. + * + * @param o The name of the entity owning the newly added + * container. + */ + public void setOwnership(String o) { + ownership = o; + } + } diff --git a/src/jade/domain/introspection/AddedMTP.java b/src/jade/domain/introspection/AddedMTP.java index bb837f4..0ba1e0b 100644 --- a/src/jade/domain/introspection/AddedMTP.java +++ b/src/jade/domain/introspection/AddedMTP.java @@ -59,15 +59,6 @@ public String getName() { return NAME; } - /** - * Set the address of this event. - * - * @param s The address URL exported by the newly added MTP. - */ - public void setAddress(String s) { - address = s; - } - /** * Retrieve the value of the address slot of this * event, containing the address URL of the newly added MTP. @@ -80,12 +71,12 @@ public String getAddress() { } /** - * Set the proto slot of this event. + * Set the address of this event. * - * @param p The protocol name for the newly added MTP. + * @param s The address URL exported by the newly added MTP. */ - public void setProto(String p) { - proto = p; + public void setAddress(String s) { + address = s; } /** @@ -100,13 +91,12 @@ public String getProto() { } /** - * Set the where slot of this event. + * Set the proto slot of this event. * - * @param id The container identifier of the container where the - * newly added MTP was deployed. + * @param p The protocol name for the newly added MTP. */ - public void setWhere(ContainerID id) { - where = id; + public void setProto(String p) { + proto = p; } /** @@ -121,4 +111,14 @@ public ContainerID getWhere() { return where; } + /** + * Set the where slot of this event. + * + * @param id The container identifier of the container where the + * newly added MTP was deployed. + */ + public void setWhere(ContainerID id) { + where = id; + } + } diff --git a/src/jade/domain/introspection/BornAgent.java b/src/jade/domain/introspection/BornAgent.java index c4f99ce..5c3f35b 100644 --- a/src/jade/domain/introspection/BornAgent.java +++ b/src/jade/domain/introspection/BornAgent.java @@ -65,16 +65,6 @@ public String getName() { return NAME; } - /** - * Set the where slot of this event. - * - * @param id The container identifier of the container where the - * newly added agent was born. - */ - public void setWhere(ContainerID id) { - where = id; - } - /** * Retrieve the value of the where slot of this * event, containing the container identifier of the container @@ -88,12 +78,13 @@ public ContainerID getWhere() { } /** - * Set the agent slot of this event. + * Set the where slot of this event. * - * @param id The agent identifier of the newly born agent. + * @param id The container identifier of the container where the + * newly added agent was born. */ - public void setAgent(AID id) { - agent = id; + public void setWhere(ContainerID id) { + where = id; } /** @@ -108,13 +99,12 @@ public AID getAgent() { } /** - * Set the state slot of this event. + * Set the agent slot of this event. * - * @param as The name of the initial state of the newly born - * agent. + * @param id The agent identifier of the newly born agent. */ - public void setState(String as) { - state = as; + public void setAgent(AID id) { + agent = id; } /** @@ -129,12 +119,13 @@ public String getState() { } /** - * Set the ownership slot of this event. + * Set the state slot of this event. * - * @param o The name of the entity owning the newly born agent. + * @param as The name of the initial state of the newly born + * agent. */ - public void setOwnership(String o) { - ownership = o; + public void setState(String as) { + state = as; } /** @@ -147,12 +138,12 @@ public String getOwnership() { } /** - * Set the className slot of this event. + * Set the ownership slot of this event. * - * @param c The class name of the newly born agent. + * @param o The name of the entity owning the newly born agent. */ - public void setClassName(String c) { - className = c; + public void setOwnership(String o) { + ownership = o; } /** @@ -163,4 +154,13 @@ public void setClassName(String c) { public String getClassName() { return className; } + + /** + * Set the className slot of this event. + * + * @param c The class name of the newly born agent. + */ + public void setClassName(String c) { + className = c; + } } diff --git a/src/jade/domain/introspection/ChangedAgentOwnership.java b/src/jade/domain/introspection/ChangedAgentOwnership.java index 4aa8af9..b192b8e 100644 --- a/src/jade/domain/introspection/ChangedAgentOwnership.java +++ b/src/jade/domain/introspection/ChangedAgentOwnership.java @@ -56,16 +56,6 @@ public class ChangedAgentOwnership implements Event { public ChangedAgentOwnership() { } - /** - * Set the where slot of this event. - * - * @param id The container identifier of the container where the - * agent is deployed. - */ - public void setWhere(ContainerID id) { - where = id; - } - /** * Retrieve the value of the where slot of this * event, containing the container identifier of the container @@ -79,13 +69,13 @@ public ContainerID getWhere() { } /** - * Set the agent slot of this event. + * Set the where slot of this event. * - * @param id The agent identifier of the agent whose ownership - * changed. + * @param id The container identifier of the container where the + * agent is deployed. */ - public void setAgent(AID id) { - agent = id; + public void setWhere(ContainerID id) { + where = id; } /** @@ -101,13 +91,13 @@ public AID getAgent() { } /** - * Set the from slot of this event. + * Set the agent slot of this event. * - * @param o The name of the entity that owned the agent before - * this event occurred. + * @param id The agent identifier of the agent whose ownership + * changed. */ - public void setFrom(String o) { - from = o; + public void setAgent(AID id) { + agent = id; } /** @@ -123,13 +113,13 @@ public String getFrom() { } /** - * Set the to slot of this event. + * Set the from slot of this event. * - * @param o The name of the entity owning the agent after this - * event occurred. + * @param o The name of the entity that owned the agent before + * this event occurred. */ - public void setTo(String o) { - to = o; + public void setFrom(String o) { + from = o; } /** @@ -144,6 +134,16 @@ public String getTo() { return to; } + /** + * Set the to slot of this event. + * + * @param o The name of the entity owning the agent after this + * event occurred. + */ + public void setTo(String o) { + to = o; + } + /** * Retrieve the name of this event. * diff --git a/src/jade/domain/introspection/ChangedAgentState.java b/src/jade/domain/introspection/ChangedAgentState.java index add28fc..e35a676 100644 --- a/src/jade/domain/introspection/ChangedAgentState.java +++ b/src/jade/domain/introspection/ChangedAgentState.java @@ -65,16 +65,6 @@ public String getName() { return NAME; } - /** - * Set the agent slot of this event. - * - * @param id The agent identifier of the agent whose state - * changed. - */ - public void setAgent(AID id) { - agent = id; - } - /** * Retrieve the value of the agent slot of this * event, containing the agent identifier of the agent whose @@ -88,13 +78,13 @@ public AID getAgent() { } /** - * Set the from slot of this event. + * Set the agent slot of this event. * - * @param as The name of the entity the state the agent was in - * before this event occurred. + * @param id The agent identifier of the agent whose state + * changed. */ - public void setFrom(AgentState as) { - from = as; + public void setAgent(AID id) { + agent = id; } /** @@ -110,13 +100,13 @@ public AgentState getFrom() { } /** - * Set the to slot of this event. + * Set the from slot of this event. * - * @param as The name of the state the agent was in after this - * event occurred. + * @param as The name of the entity the state the agent was in + * before this event occurred. */ - public void setTo(AgentState as) { - to = as; + public void setFrom(AgentState as) { + from = as; } /** @@ -131,4 +121,14 @@ public AgentState getTo() { return to; } + /** + * Set the to slot of this event. + * + * @param as The name of the state the agent was in after this + * event occurred. + */ + public void setTo(AgentState as) { + to = as; + } + } diff --git a/src/jade/domain/introspection/ChangedBehaviourState.java b/src/jade/domain/introspection/ChangedBehaviourState.java index 82b94f9..c6d24f4 100644 --- a/src/jade/domain/introspection/ChangedBehaviourState.java +++ b/src/jade/domain/introspection/ChangedBehaviourState.java @@ -57,16 +57,6 @@ public class ChangedBehaviourState implements Event { public ChangedBehaviourState() { } - /** - * Set the agent slot of this event. - * - * @param id The agent identifier of the agent whose behaviour - * state changed. - */ - public void setAgent(AID id) { - agent = id; - } - /** * Retrieve the value of the agent slot of this * event, containing the agent identifier of the agent whose @@ -80,13 +70,13 @@ public AID getAgent() { } /** - * Set the behaviour slot of this event. + * Set the agent slot of this event. * - * @param id The behaviour identifier of the behaviour whose state - * changed. + * @param id The agent identifier of the agent whose behaviour + * state changed. */ - public void setBehaviour(BehaviourID id) { - behaviour = id; + public void setAgent(AID id) { + agent = id; } /** @@ -102,13 +92,13 @@ public BehaviourID getBehaviour() { } /** - * Set the from slot of this event. + * Set the behaviour slot of this event. * - * @param s The name of the state the behaviour was in before this - * event occurred. + * @param id The behaviour identifier of the behaviour whose state + * changed. */ - public void setFrom(String s) { - from = s; + public void setBehaviour(BehaviourID id) { + behaviour = id; } /** @@ -124,13 +114,13 @@ public String getFrom() { } /** - * Set the to slot of this event. + * Set the from slot of this event. * - * @param s The name of the state the behaviour was in after this + * @param s The name of the state the behaviour was in before this * event occurred. */ - public void setTo(String s) { - to = s; + public void setFrom(String s) { + from = s; } /** @@ -145,6 +135,16 @@ public String getTo() { return to; } + /** + * Set the to slot of this event. + * + * @param s The name of the state the behaviour was in after this + * event occurred. + */ + public void setTo(String s) { + to = s; + } + /** * Retrieve the name of this event. * diff --git a/src/jade/domain/introspection/DeadAgent.java b/src/jade/domain/introspection/DeadAgent.java index 4762eba..4e03ef9 100644 --- a/src/jade/domain/introspection/DeadAgent.java +++ b/src/jade/domain/introspection/DeadAgent.java @@ -64,16 +64,6 @@ public String getName() { return NAME; } - /** - * Set the where slot of this event. - * - * @param id The container identifier of the container where the - * newly dead agent was deployed. - */ - public void setWhere(ContainerID id) { - where = id; - } - /** * Retrieve the value of the where slot of this * event, containing the container identifier of the container @@ -87,12 +77,13 @@ public ContainerID getWhere() { } /** - * Set the agent slot of this event. + * Set the where slot of this event. * - * @param id The agent identifier of the newly dead agent. + * @param id The container identifier of the container where the + * newly dead agent was deployed. */ - public void setAgent(AID id) { - agent = id; + public void setWhere(ContainerID id) { + where = id; } /** @@ -106,6 +97,15 @@ public AID getAgent() { return agent; } + /** + * Set the agent slot of this event. + * + * @param id The agent identifier of the newly dead agent. + */ + public void setAgent(AID id) { + agent = id; + } + public Boolean getContainerRemoved() { return containerRemoved; } diff --git a/src/jade/domain/introspection/EventRecord.java b/src/jade/domain/introspection/EventRecord.java index 7c9df3d..e1bbf75 100644 --- a/src/jade/domain/introspection/EventRecord.java +++ b/src/jade/domain/introspection/EventRecord.java @@ -63,15 +63,6 @@ public EventRecord(Event evt, Location l) { where = l; } - /** - * Set the what slot of this event. - * - * @param evt The occurred event. - */ - public void setWhat(Event evt) { - what = evt; - } - /** * Retrieve the value of the what slot of this * event, containing the occurred event. @@ -84,12 +75,12 @@ public Event getWhat() { } /** - * Set the when slot of this event. + * Set the what slot of this event. * - * @param d The time instant when the event occurred. + * @param evt The occurred event. */ - public void setWhen(Date d) { - when = d; + public void setWhat(Event evt) { + what = evt; } /** @@ -104,12 +95,12 @@ public Date getWhen() { } /** - * Set the where slot of this event. + * Set the when slot of this event. * - * @param l The location where the event occurred. + * @param d The time instant when the event occurred. */ - public void setWhere(Location l) { - where = l; + public void setWhen(Date d) { + when = d; } /** @@ -123,4 +114,13 @@ public Location getWhere() { return where; } + /** + * Set the where slot of this event. + * + * @param l The location where the event occurred. + */ + public void setWhere(Location l) { + where = l; + } + } diff --git a/src/jade/domain/introspection/FrozenAgent.java b/src/jade/domain/introspection/FrozenAgent.java index 92c81ef..bd40048 100644 --- a/src/jade/domain/introspection/FrozenAgent.java +++ b/src/jade/domain/introspection/FrozenAgent.java @@ -64,15 +64,6 @@ public String getName() { return NAME; } - /** - * Set the agent slot of this event. - * - * @param id The agent identifier of the newly suspended agent. - */ - public void setAgent(AID id) { - agent = id; - } - /** * Retrieve the value of the agent slot of this * event, containing the agent identifier of the newly suspended @@ -86,13 +77,12 @@ public AID getAgent() { } /** - * Set the where slot of this event. + * Set the agent slot of this event. * - * @param id The container identifier of the container where the - * newly frozen agent was deployed. + * @param id The agent identifier of the newly suspended agent. */ - public void setWhere(ContainerID id) { - where = id; + public void setAgent(AID id) { + agent = id; } /** @@ -108,14 +98,13 @@ public ContainerID getWhere() { } /** - * Set the buffer-container slot of this event. + * Set the where slot of this event. * * @param id The container identifier of the container where the - * frozen agent will appear to reside (and where ACL messages for - * that agent will be redirected and buffered). + * newly frozen agent was deployed. */ - public void setBufferContainer(ContainerID id) { - bufferContainer = id; + public void setWhere(ContainerID id) { + where = id; } /** @@ -132,4 +121,15 @@ public ContainerID getBufferContainer() { return bufferContainer; } + /** + * Set the buffer-container slot of this event. + * + * @param id The container identifier of the container where the + * frozen agent will appear to reside (and where ACL messages for + * that agent will be redirected and buffered). + */ + public void setBufferContainer(ContainerID id) { + bufferContainer = id; + } + } diff --git a/src/jade/domain/introspection/GetValue.java b/src/jade/domain/introspection/GetValue.java index 472b433..9a0cac4 100644 --- a/src/jade/domain/introspection/GetValue.java +++ b/src/jade/domain/introspection/GetValue.java @@ -44,11 +44,11 @@ public GetValue(String key) { this.key = key; } - public void setKey(String key) { - this.key = key; - } - public String getKey() { return key; } + + public void setKey(String key) { + this.key = key; + } } diff --git a/src/jade/domain/introspection/IntrospectionOntology.java b/src/jade/domain/introspection/IntrospectionOntology.java index c5e149e..4e39095 100644 --- a/src/jade/domain/introspection/IntrospectionOntology.java +++ b/src/jade/domain/introspection/IntrospectionOntology.java @@ -57,17 +57,6 @@ public class IntrospectionOntology extends Ontology implements IntrospectionVoca private static final Ontology theInstance = new IntrospectionOntology(); - /** - * This method grants access to the unique instance of the - * ontology. - * - * @return An Ontology object, containing the concepts - * of the ontology. - */ - public static Ontology getInstance() { - return theInstance; - } - private IntrospectionOntology() { super(NAME, new Ontology[]{BasicOntology.getInstance(), SerializableOntology.getInstance()}, new BCReflectiveIntrospector()); @@ -295,6 +284,17 @@ private IntrospectionOntology() { } } //end of initInstance + /** + * This method grants access to the unique instance of the + * ontology. + * + * @return An Ontology object, containing the concepts + * of the ontology. + */ + public static Ontology getInstance() { + return theInstance; + } + //#APIDOC_EXCLUDE_BEGIN // Used for debug diff --git a/src/jade/domain/introspection/IntrospectionServer.java b/src/jade/domain/introspection/IntrospectionServer.java index 1e49d83..7786c24 100644 --- a/src/jade/domain/introspection/IntrospectionServer.java +++ b/src/jade/domain/introspection/IntrospectionServer.java @@ -19,10 +19,6 @@ import java.util.List; public class IntrospectionServer extends CyclicBehaviour { - private Codec codec; - private Ontology onto; - private MessageTemplate template; - private static Class serializableClass; static { @@ -32,6 +28,10 @@ public class IntrospectionServer extends CyclicBehaviour { } } + private Codec codec; + private Ontology onto; + private MessageTemplate template; + public IntrospectionServer(Agent a) { super(a); } diff --git a/src/jade/domain/introspection/KillContainerRequested.java b/src/jade/domain/introspection/KillContainerRequested.java index 03b8c87..16bdf03 100644 --- a/src/jade/domain/introspection/KillContainerRequested.java +++ b/src/jade/domain/introspection/KillContainerRequested.java @@ -56,15 +56,6 @@ public String getName() { return NAME; } - /** - * Set the container of this event. - * - * @param id The container identifier of the container that is requested to be killed. - */ - public void setContainer(ContainerID id) { - container = id; - } - /** * Retrieve the value of the container slot of this * event, containing the identifier of the container that is requested @@ -76,4 +67,13 @@ public void setContainer(ContainerID id) { public ContainerID getContainer() { return container; } + + /** + * Set the container of this event. + * + * @param id The container identifier of the container that is requested to be killed. + */ + public void setContainer(ContainerID id) { + container = id; + } } diff --git a/src/jade/domain/introspection/MovedAgent.java b/src/jade/domain/introspection/MovedAgent.java index a97359e..fea492a 100644 --- a/src/jade/domain/introspection/MovedAgent.java +++ b/src/jade/domain/introspection/MovedAgent.java @@ -63,15 +63,6 @@ public String getName() { return NAME; } - /** - * Set the agent slot of this event. - * - * @param id The agent identifier of the newly moved agent. - */ - public void setAgent(AID id) { - agent = id; - } - /** * Retrieve the value of the agent slot of this * event, containing the agent identifier of the newly moved agent. @@ -83,15 +74,13 @@ public AID getAgent() { return agent; } - /** - * Set the from slot of this event. + * Set the agent slot of this event. * - * @param id The container identifier of the container from where - * the agent migrated. + * @param id The agent identifier of the newly moved agent. */ - public void setFrom(ContainerID id) { - from = id; + public void setAgent(AID id) { + agent = id; } /** @@ -107,13 +96,13 @@ public ContainerID getFrom() { } /** - * Set the to slot of this event. + * Set the from slot of this event. * - * @param id The container identifier of the container where the - * agent migrated. + * @param id The container identifier of the container from where + * the agent migrated. */ - public void setTo(ContainerID id) { - to = id; + public void setFrom(ContainerID id) { + from = id; } /** @@ -128,5 +117,15 @@ public ContainerID getTo() { return to; } + /** + * Set the to slot of this event. + * + * @param id The container identifier of the container where the + * agent migrated. + */ + public void setTo(ContainerID id) { + to = id; + } + } diff --git a/src/jade/domain/introspection/Occurred.java b/src/jade/domain/introspection/Occurred.java index 140114a..c5617d1 100644 --- a/src/jade/domain/introspection/Occurred.java +++ b/src/jade/domain/introspection/Occurred.java @@ -45,16 +45,6 @@ public class Occurred implements Predicate { public Occurred() { } - /** - * Set the what slot of this event. - * - * @param er The record of the occurred event, along with location - * and timestamp information. - */ - public void setWhat(EventRecord er) { - arg = er; - } - /** * Retrieve the value of the what slot of this event, * containing the record of the occurred event, along with @@ -67,5 +57,15 @@ public EventRecord getWhat() { return arg; } + /** + * Set the what slot of this event. + * + * @param er The record of the occurred event, along with location + * and timestamp information. + */ + public void setWhat(EventRecord er) { + arg = er; + } + } diff --git a/src/jade/domain/introspection/PlatformDescription.java b/src/jade/domain/introspection/PlatformDescription.java index 49e1690..9ff40a3 100644 --- a/src/jade/domain/introspection/PlatformDescription.java +++ b/src/jade/domain/introspection/PlatformDescription.java @@ -59,16 +59,6 @@ public String getName() { return NAME; } - /** - * Set the platform slot of this event. - * - * @param p The ap-description this notification - * refers to. - */ - public void setPlatform(APDescription p) { - platform = p; - } - /** * Retrieve the value of the platform slot of this * event, containing the ap-description this @@ -81,5 +71,15 @@ public APDescription getPlatform() { return platform; } + /** + * Set the platform slot of this event. + * + * @param p The ap-description this notification + * refers to. + */ + public void setPlatform(APDescription p) { + platform = p; + } + } diff --git a/src/jade/domain/introspection/PostedMessage.java b/src/jade/domain/introspection/PostedMessage.java index 9d5c5b1..816f799 100644 --- a/src/jade/domain/introspection/PostedMessage.java +++ b/src/jade/domain/introspection/PostedMessage.java @@ -63,16 +63,6 @@ public String getName() { return NAME; } - /** - * Set the sender slot of this event. - * - * @param id The agent identifier of the agent that sent the - * message. - */ - public void setSender(AID id) { - sender = id; - } - /** * Retrieve the value of the sender slot of this * event, containing the agent identifier of the agent that sent @@ -86,13 +76,13 @@ public AID getSender() { } /** - * Set the message slot of this event. + * Set the sender slot of this event. * - * @param msg The ACL message that was posted to the receiver - * agent message queue. + * @param id The agent identifier of the agent that sent the + * message. */ - public void setMessage(ACLMessage msg) { - message = msg; + public void setSender(AID id) { + sender = id; } /** @@ -108,13 +98,13 @@ public ACLMessage getMessage() { } /** - * Set the receiver slot of this event. + * Set the message slot of this event. * - * @param id The agent identifier of the agent owning the message - * queue the message was posted to. + * @param msg The ACL message that was posted to the receiver + * agent message queue. */ - public void setReceiver(AID id) { - receiver = id; + public void setMessage(ACLMessage msg) { + message = msg; } /** @@ -129,4 +119,14 @@ public AID getReceiver() { return receiver; } + /** + * Set the receiver slot of this event. + * + * @param id The agent identifier of the agent owning the message + * queue the message was posted to. + */ + public void setReceiver(AID id) { + receiver = id; + } + } diff --git a/src/jade/domain/introspection/ReceivedMessage.java b/src/jade/domain/introspection/ReceivedMessage.java index 82634b9..aae28dd 100644 --- a/src/jade/domain/introspection/ReceivedMessage.java +++ b/src/jade/domain/introspection/ReceivedMessage.java @@ -63,17 +63,6 @@ public String getName() { return NAME; } - - /** - * Set the sender slot of this event. - * - * @param id The agent identifier of the agent that sent the - * message. - */ - public void setSender(AID id) { - sender = id; - } - /** * Retrieve the value of the sender slot of this * event, containing the agent identifier of the agent that sent @@ -87,13 +76,13 @@ public AID getSender() { } /** - * Set the message slot of this event. + * Set the sender slot of this event. * - * @param msg The ACL message that was extracted from the receiver - * agent message queue. + * @param id The agent identifier of the agent that sent the + * message. */ - public void setMessage(ACLMessage msg) { - message = msg; + public void setSender(AID id) { + sender = id; } /** @@ -109,13 +98,13 @@ public ACLMessage getMessage() { } /** - * Set the receiver slot of this event. + * Set the message slot of this event. * - * @param id The agent identifier of the agent owning the message - * queue the message was extracted from. + * @param msg The ACL message that was extracted from the receiver + * agent message queue. */ - public void setReceiver(AID id) { - receiver = id; + public void setMessage(ACLMessage msg) { + message = msg; } /** @@ -130,4 +119,14 @@ public AID getReceiver() { return receiver; } + /** + * Set the receiver slot of this event. + * + * @param id The agent identifier of the agent owning the message + * queue the message was extracted from. + */ + public void setReceiver(AID id) { + receiver = id; + } + } diff --git a/src/jade/domain/introspection/RemovedBehaviour.java b/src/jade/domain/introspection/RemovedBehaviour.java index dab0e1b..e6642ec 100644 --- a/src/jade/domain/introspection/RemovedBehaviour.java +++ b/src/jade/domain/introspection/RemovedBehaviour.java @@ -53,15 +53,6 @@ public class RemovedBehaviour implements Event { public RemovedBehaviour() { } - /** - * Set the agent slot of this event. - * - * @param id The agent identifier of the agent owning the newly removed behaviour. - */ - public void setAgent(AID id) { - agent = id; - } - /** * Retrieve the value of the agent slot of this * event, containing the agent identifier of the agent owning the @@ -75,13 +66,12 @@ public AID getAgent() { } /** - * Set the behaviour slot of this event. + * Set the agent slot of this event. * - * @param id The behaviour identifier of the newly removed - * behaviour. + * @param id The agent identifier of the agent owning the newly removed behaviour. */ - public void setBehaviour(BehaviourID id) { - behaviour = id; + public void setAgent(AID id) { + agent = id; } /** @@ -96,6 +86,16 @@ public BehaviourID getBehaviour() { return behaviour; } + /** + * Set the behaviour slot of this event. + * + * @param id The behaviour identifier of the newly removed + * behaviour. + */ + public void setBehaviour(BehaviourID id) { + behaviour = id; + } + /** * Retrieve the name of this event. * diff --git a/src/jade/domain/introspection/RemovedContainer.java b/src/jade/domain/introspection/RemovedContainer.java index 891e7b5..1ebaa97 100644 --- a/src/jade/domain/introspection/RemovedContainer.java +++ b/src/jade/domain/introspection/RemovedContainer.java @@ -59,16 +59,6 @@ public String getName() { return NAME; } - /** - * Set the container slot of this event. - * - * @param id The container identifier of the newly removed - * container. - */ - public void setContainer(ContainerID id) { - container = id; - } - /** * Retrieve the value of the container slot of this * event, containing the container identifier of the newly removed @@ -81,4 +71,14 @@ public ContainerID getContainer() { return container; } + /** + * Set the container slot of this event. + * + * @param id The container identifier of the newly removed + * container. + */ + public void setContainer(ContainerID id) { + container = id; + } + } diff --git a/src/jade/domain/introspection/RemovedMTP.java b/src/jade/domain/introspection/RemovedMTP.java index 531af60..8f6dd30 100644 --- a/src/jade/domain/introspection/RemovedMTP.java +++ b/src/jade/domain/introspection/RemovedMTP.java @@ -59,15 +59,6 @@ public String getName() { return NAME; } - /** - * Set the address slot of this event. - * - * @param s The address URL of the newly removed MTP. - */ - public void setAddress(String s) { - address = s; - } - /** * Retrieve the value of the address slot of this * event, containing the address URL of the newly removed MTP. @@ -80,12 +71,12 @@ public String getAddress() { } /** - * Set the proto slot of this event. + * Set the address slot of this event. * - * @param p The protocol name for the newly removed MTP. + * @param s The address URL of the newly removed MTP. */ - public void setProto(String p) { - proto = p; + public void setAddress(String s) { + address = s; } /** @@ -100,13 +91,12 @@ public String getProto() { } /** - * Set the where slot of this event. + * Set the proto slot of this event. * - * @param id The container identifier of the container where the - * newly removed MTP was deployed. + * @param p The protocol name for the newly removed MTP. */ - public void setWhere(ContainerID id) { - where = id; + public void setProto(String p) { + proto = p; } /** @@ -121,4 +111,14 @@ public ContainerID getWhere() { return where; } + /** + * Set the where slot of this event. + * + * @param id The container identifier of the container where the + * newly removed MTP was deployed. + */ + public void setWhere(ContainerID id) { + where = id; + } + } diff --git a/src/jade/domain/introspection/ResumedAgent.java b/src/jade/domain/introspection/ResumedAgent.java index 5002de2..a16490a 100644 --- a/src/jade/domain/introspection/ResumedAgent.java +++ b/src/jade/domain/introspection/ResumedAgent.java @@ -63,15 +63,6 @@ public String getName() { return NAME; } - /** - * Set the agent slot of this event. - * - * @param id The agent identifier of the newly resumed agent. - */ - public void setAgent(AID id) { - agent = id; - } - /** * Retrieve the value of the agent slot of this * event, containing the agent identifier of the newly resumed @@ -85,13 +76,12 @@ public AID getAgent() { } /** - * Set the where slot of this event. + * Set the agent slot of this event. * - * @param id The container identifier of the container where the - * newly resumed agent was deployed. + * @param id The agent identifier of the newly resumed agent. */ - public void setWhere(ContainerID id) { - where = id; + public void setAgent(AID id) { + agent = id; } /** @@ -106,5 +96,15 @@ public ContainerID getWhere() { return where; } + /** + * Set the where slot of this event. + * + * @param id The container identifier of the container where the + * newly resumed agent was deployed. + */ + public void setWhere(ContainerID id) { + where = id; + } + } diff --git a/src/jade/domain/introspection/RoutedMessage.java b/src/jade/domain/introspection/RoutedMessage.java index 9442248..975ba49 100644 --- a/src/jade/domain/introspection/RoutedMessage.java +++ b/src/jade/domain/introspection/RoutedMessage.java @@ -40,28 +40,28 @@ public class RoutedMessage implements Concept { private Channel to; private ACLMessage message; - public void setFrom(Channel c) { - from = c; - } - public Channel getFrom() { return from; } - public void setTo(Channel c) { - to = c; + public void setFrom(Channel c) { + from = c; } public Channel getTo() { return to; } - public void setMessage(ACLMessage msg) { - message = msg; + public void setTo(Channel c) { + to = c; } public ACLMessage getMessage() { return message; } + public void setMessage(ACLMessage msg) { + message = msg; + } + } diff --git a/src/jade/domain/introspection/SentMessage.java b/src/jade/domain/introspection/SentMessage.java index 0d4d06e..949747f 100644 --- a/src/jade/domain/introspection/SentMessage.java +++ b/src/jade/domain/introspection/SentMessage.java @@ -63,16 +63,6 @@ public String getName() { return NAME; } - /** - * Set the sender slot of this event. - * - * @param id The agent identifier of the agent that sent the - * message. - */ - public void setSender(AID id) { - sender = id; - } - /** * Retrieve the value of the sender slot of this * event, containing the agent identifier of the agent that sent @@ -86,13 +76,13 @@ public AID getSender() { } /** - * Set the unicast receiver slot of this event. + * Set the sender slot of this event. * - * @param id The agent identifier of the unicast receiver of the - * sent message. + * @param id The agent identifier of the agent that sent the + * message. */ - public void setReceiver(AID id) { - receiver = id; + public void setSender(AID id) { + sender = id; } /** @@ -107,12 +97,13 @@ public AID getReceiver() { } /** - * Set the message slot of this event. + * Set the unicast receiver slot of this event. * - * @param msg The ACL message that was sent. + * @param id The agent identifier of the unicast receiver of the + * sent message. */ - public void setMessage(ACLMessage msg) { - message = msg; + public void setReceiver(AID id) { + receiver = id; } /** @@ -126,4 +117,13 @@ public ACLMessage getMessage() { return message; } + /** + * Set the message slot of this event. + * + * @param msg The ACL message that was sent. + */ + public void setMessage(ACLMessage msg) { + message = msg; + } + } diff --git a/src/jade/domain/introspection/StartNotify.java b/src/jade/domain/introspection/StartNotify.java index a1ad3bc..80be0e6 100644 --- a/src/jade/domain/introspection/StartNotify.java +++ b/src/jade/domain/introspection/StartNotify.java @@ -40,8 +40,8 @@ */ public class StartNotify implements AgentAction { - private AID observed; private final List events = new ArrayList<>(); + private AID observed; /** * Default constructor. A default constructor is necessary for @@ -50,16 +50,6 @@ public class StartNotify implements AgentAction { public StartNotify() { } - /** - * Set the observed slot of this action. - * - * @param id The agent identifier of the agent whose events will - * be notified from now on. - */ - public void setObserved(AID id) { - observed = id; - } - /** * Retrieve the value of the observed slot of this * event, containing the agent identifier of the agent whose @@ -72,6 +62,16 @@ public AID getObserved() { return observed; } + /** + * Set the observed slot of this action. + * + * @param id The agent identifier of the agent whose events will + * be notified from now on. + */ + public void setObserved(AID id) { + observed = id; + } + /** * Add an event name to the events slot collection of * this object. diff --git a/src/jade/domain/introspection/StopNotify.java b/src/jade/domain/introspection/StopNotify.java index 36e47c1..25c5551 100644 --- a/src/jade/domain/introspection/StopNotify.java +++ b/src/jade/domain/introspection/StopNotify.java @@ -40,8 +40,8 @@ */ public class StopNotify implements AgentAction { - private AID observed; private final List events = new ArrayList<>(); + private AID observed; /** @@ -51,16 +51,6 @@ public class StopNotify implements AgentAction { public StopNotify() { } - /** - * Set the observed slot of this action. - * - * @param id The agent identifier of the agent whose events were - * being notified so far. - */ - public void setObserved(AID id) { - observed = id; - } - /** * Retrieve the value of the observed slot of this * event, containing the agent identifier of the agent whose @@ -73,6 +63,16 @@ public AID getObserved() { return observed; } + /** + * Set the observed slot of this action. + * + * @param id The agent identifier of the agent whose events were + * being notified so far. + */ + public void setObserved(AID id) { + observed = id; + } + /** * Add an event name to the events slot collection of * this object. diff --git a/src/jade/domain/introspection/SuspendedAgent.java b/src/jade/domain/introspection/SuspendedAgent.java index ddc3143..668ca3a 100644 --- a/src/jade/domain/introspection/SuspendedAgent.java +++ b/src/jade/domain/introspection/SuspendedAgent.java @@ -62,15 +62,6 @@ public String getName() { return NAME; } - /** - * Set the agent slot of this event. - * - * @param id The agent identifier of the newly suspended agent. - */ - public void setAgent(AID id) { - agent = id; - } - /** * Retrieve the value of the agent slot of this * event, containing the agent identifier of the newly suspended @@ -84,13 +75,12 @@ public AID getAgent() { } /** - * Set the where slot of this event. + * Set the agent slot of this event. * - * @param id The container identifier of the container where the - * newly suspended agent was deployed. + * @param id The agent identifier of the newly suspended agent. */ - public void setWhere(ContainerID id) { - where = id; + public void setAgent(AID id) { + agent = id; } /** @@ -105,5 +95,15 @@ public ContainerID getWhere() { return where; } + /** + * Set the where slot of this event. + * + * @param id The container identifier of the container where the + * newly suspended agent was deployed. + */ + public void setWhere(ContainerID id) { + where = id; + } + } diff --git a/src/jade/domain/introspection/ThawedAgent.java b/src/jade/domain/introspection/ThawedAgent.java index 6b435a6..133e3b4 100644 --- a/src/jade/domain/introspection/ThawedAgent.java +++ b/src/jade/domain/introspection/ThawedAgent.java @@ -64,15 +64,6 @@ public String getName() { return NAME; } - /** - * Set the agent slot of this event. - * - * @param id The agent identifier of the newly suspended agent. - */ - public void setAgent(AID id) { - agent = id; - } - /** * Retrieve the value of the agent slot of this * event, containing the agent identifier of the newly suspended @@ -86,13 +77,12 @@ public AID getAgent() { } /** - * Set the where slot of this event. + * Set the agent slot of this event. * - * @param id The container identifier of the container where the - * newly frozen agent was deployed. + * @param id The agent identifier of the newly suspended agent. */ - public void setWhere(ContainerID id) { - where = id; + public void setAgent(AID id) { + agent = id; } /** @@ -108,14 +98,13 @@ public ContainerID getWhere() { } /** - * Set the buffer-container slot of this event. + * Set the where slot of this event. * * @param id The container identifier of the container where the - * frozen agent will appear to reside (and where ACL messages for - * that agent will be redirected and buffered). + * newly frozen agent was deployed. */ - public void setBufferContainer(ContainerID id) { - bufferContainer = id; + public void setWhere(ContainerID id) { + where = id; } /** @@ -132,4 +121,15 @@ public ContainerID getBufferContainer() { return bufferContainer; } + /** + * Set the buffer-container slot of this event. + * + * @param id The container identifier of the container where the + * frozen agent will appear to reside (and where ACL messages for + * that agent will be redirected and buffered). + */ + public void setBufferContainer(ContainerID id) { + bufferContainer = id; + } + } diff --git a/src/jade/domain/mobility/BehaviourLoadingOntology.java b/src/jade/domain/mobility/BehaviourLoadingOntology.java index 491a77c..0c6ac48 100644 --- a/src/jade/domain/mobility/BehaviourLoadingOntology.java +++ b/src/jade/domain/mobility/BehaviourLoadingOntology.java @@ -40,17 +40,6 @@ public class BehaviourLoadingOntology extends Ontology implements BehaviourLoadi private static final Ontology theInstance = new BehaviourLoadingOntology(); - /** - * This method returns the singleton instance of the - * Behaviour-Loading ontology. - * - * @return The singleton Ontology object, containing the - * schemas for the elements of the Behaviour-Loading ontology. - */ - public static Ontology getInstance() { - return theInstance; - } - private BehaviourLoadingOntology() { super(NAME, new Ontology[]{ExceptionOntology.getInstance(), SerializableOntology.getInstance()}, new ReflectiveIntrospector()); @@ -72,4 +61,15 @@ private BehaviourLoadingOntology() { oe.printStackTrace(); } } + + /** + * This method returns the singleton instance of the + * Behaviour-Loading ontology. + * + * @return The singleton Ontology object, containing the + * schemas for the elements of the Behaviour-Loading ontology. + */ + public static Ontology getInstance() { + return theInstance; + } } diff --git a/src/jade/domain/mobility/CloneAction.java b/src/jade/domain/mobility/CloneAction.java index 2083552..1593720 100644 --- a/src/jade/domain/mobility/CloneAction.java +++ b/src/jade/domain/mobility/CloneAction.java @@ -42,16 +42,6 @@ public class CloneAction extends MoveAction { public CloneAction() { } - /** - * Set the new-name slot of this action. - * - * @param nn The new local name (i.e. without the platform ID) for the - * new, cloned agent. - */ - public void setNewName(String nn) { - newName = nn; - } - /** * Retrieve the value of the new-name slot of this * event, containing the new local name (i.e. without the platform ID) @@ -64,4 +54,14 @@ public String getNewName() { return newName; } + /** + * Set the new-name slot of this action. + * + * @param nn The new local name (i.e. without the platform ID) for the + * new, cloned agent. + */ + public void setNewName(String nn) { + newName = nn; + } + } diff --git a/src/jade/domain/mobility/LoadBehaviour.java b/src/jade/domain/mobility/LoadBehaviour.java index 986b08b..d7f72e1 100644 --- a/src/jade/domain/mobility/LoadBehaviour.java +++ b/src/jade/domain/mobility/LoadBehaviour.java @@ -44,6 +44,13 @@ public class LoadBehaviour implements AgentAction { public LoadBehaviour() { } + /** + * @return the name of the class of the behaviour to load + */ + public String getClassName() { + return className; + } + /** * Sets the name of the class of the behaviour to load */ @@ -52,10 +59,10 @@ public void setClassName(String className) { } /** - * @return the name of the class of the behaviour to load + * @return the code of the class of the behaviour to load. */ - public String getClassName() { - return className; + public byte[] getCode() { + return code; } /** @@ -70,10 +77,11 @@ public void setCode(byte[] code) { } /** - * @return the code of the class of the behaviour to load. + * @return the code of the behaviour to load as the content of a zip + * file. */ - public byte[] getCode() { - return code; + public byte[] getZip() { + return zip; } /** @@ -85,11 +93,10 @@ public void setZip(byte[] zip) { } /** - * @return the code of the behaviour to load as the content of a zip - * file. + * @return the list of parameters to be passed to the behaviour. */ - public byte[] getZip() { - return zip; + public List getParameters() { + return parameters; } /** @@ -100,11 +107,4 @@ public byte[] getZip() { public void setParameters(List parameters) { this.parameters = parameters; } - - /** - * @return the list of parameters to be passed to the behaviour. - */ - public List getParameters() { - return parameters; - } } \ No newline at end of file diff --git a/src/jade/domain/mobility/MobileAgentDescription.java b/src/jade/domain/mobility/MobileAgentDescription.java index 13a66de..a507728 100644 --- a/src/jade/domain/mobility/MobileAgentDescription.java +++ b/src/jade/domain/mobility/MobileAgentDescription.java @@ -50,15 +50,6 @@ public class MobileAgentDescription implements Concept { public MobileAgentDescription() { } - /** - * Set the name slot of this action. - * - * @param id The agent identifier of the described agent. - */ - public void setName(AID id) { - name = id; - } - /** * Retrieve the value of the name slot of this event, * containing the agent identifier of the described agent. @@ -71,13 +62,12 @@ public AID getName() { } /** - * Set the destination slot of this action. + * Set the name slot of this action. * - * @param d The destination of the mobility operation performed by - * the described agent. + * @param id The agent identifier of the described agent. */ - public void setDestination(Location d) { - destination = d; + public void setName(AID id) { + name = id; } /** @@ -93,12 +83,13 @@ public Location getDestination() { } /** - * Set the agent-profile slot of this action. + * Set the destination slot of this action. * - * @param ap The profile for the described agent. + * @param d The destination of the mobility operation performed by + * the described agent. */ - public void setAgentProfile(MobileAgentProfile ap) { - agentProfile = ap; + public void setDestination(Location d) { + destination = d; } /** @@ -113,12 +104,12 @@ public MobileAgentProfile getAgentProfile() { } /** - * Set the agent-version slot of this action. + * Set the agent-profile slot of this action. * - * @param v The version string for the described agent. + * @param ap The profile for the described agent. */ - public void setAgentVersion(String v) { - agentVersion = v; + public void setAgentProfile(MobileAgentProfile ap) { + agentProfile = ap; } /** @@ -134,12 +125,12 @@ public String getAgentVersion() { } /** - * Set the signature slot of this action. + * Set the agent-version slot of this action. * - * @param s The signature string for the described agent. + * @param v The version string for the described agent. */ - public void setSignature(String s) { - signature = s; + public void setAgentVersion(String v) { + agentVersion = v; } /** @@ -153,4 +144,13 @@ public String getSignature() { return signature; } + /** + * Set the signature slot of this action. + * + * @param s The signature string for the described agent. + */ + public void setSignature(String s) { + signature = s; + } + } diff --git a/src/jade/domain/mobility/MobileAgentLanguage.java b/src/jade/domain/mobility/MobileAgentLanguage.java index 336dcba..08855a9 100644 --- a/src/jade/domain/mobility/MobileAgentLanguage.java +++ b/src/jade/domain/mobility/MobileAgentLanguage.java @@ -47,15 +47,6 @@ public class MobileAgentLanguage implements Concept { public MobileAgentLanguage() { } - /** - * Set the name slot of this action. - * - * @param n The language of the described agent. - */ - public void setName(String n) { - name = n; - } - /** * Retrieve the value of the name slot of this action, * containing the language of the described agent. @@ -68,13 +59,12 @@ public String getName() { } /** - * Set the major-version slot of this action. + * Set the name slot of this action. * - * @param v The major version number of the language of the - * described agent. + * @param n The language of the described agent. */ - public void setMajorVersion(Long v) { - majorVersion = v; + public void setName(String n) { + name = n; } /** @@ -90,13 +80,13 @@ public Long getMajorVersion() { } /** - * Set the minor-version slot of this action. + * Set the major-version slot of this action. * - * @param v The minor version number of the language of the + * @param v The major version number of the language of the * described agent. */ - public void setMinorVersion(Long v) { - minorVersion = v; + public void setMajorVersion(Long v) { + majorVersion = v; } /** @@ -112,12 +102,13 @@ public Long getMinorVersion() { } /** - * Set the dependencies slot of this action. + * Set the minor-version slot of this action. * - * @param d The language dependencies of the described agent. + * @param v The minor version number of the language of the + * described agent. */ - public void setDependencies(String d) { - dependencies = d; + public void setMinorVersion(Long v) { + minorVersion = v; } /** @@ -132,4 +123,13 @@ public String getDependencies() { return dependencies; } + /** + * Set the dependencies slot of this action. + * + * @param d The language dependencies of the described agent. + */ + public void setDependencies(String d) { + dependencies = d; + } + } diff --git a/src/jade/domain/mobility/MobileAgentOS.java b/src/jade/domain/mobility/MobileAgentOS.java index fa89898..70626a2 100644 --- a/src/jade/domain/mobility/MobileAgentOS.java +++ b/src/jade/domain/mobility/MobileAgentOS.java @@ -45,15 +45,6 @@ public class MobileAgentOS implements Concept { public MobileAgentOS() { } - /** - * Set the name slot of this action. - * - * @param n The OS of the described agent. - */ - public void setName(String n) { - name = n; - } - /** * Retrieve the value of the name slot of this * action, containing the OS of the described agent. @@ -66,13 +57,12 @@ public String getName() { } /** - * Set the major-version slot of this action. + * Set the name slot of this action. * - * @param v The major version number of the OS of the described - * agent. + * @param n The OS of the described agent. */ - public void setMajorVersion(Long v) { - majorVersion = v; + public void setName(String n) { + name = n; } /** @@ -88,13 +78,13 @@ public Long getMajorVersion() { } /** - * Set the minor-version slot of this action. + * Set the major-version slot of this action. * - * @param v The minor version number of the OS of the described + * @param v The major version number of the OS of the described * agent. */ - public void setMinorVersion(Long v) { - minorVersion = v; + public void setMajorVersion(Long v) { + majorVersion = v; } /** @@ -110,12 +100,13 @@ public Long getMinorVersion() { } /** - * Set the dependencies slot of this action. + * Set the minor-version slot of this action. * - * @param d The OS dependencies of the described agent. + * @param v The minor version number of the OS of the described + * agent. */ - public void setDependencies(String d) { - dependencies = d; + public void setMinorVersion(Long v) { + minorVersion = v; } /** @@ -130,4 +121,13 @@ public String getDependencies() { return dependencies; } + /** + * Set the dependencies slot of this action. + * + * @param d The OS dependencies of the described agent. + */ + public void setDependencies(String d) { + dependencies = d; + } + } diff --git a/src/jade/domain/mobility/MobileAgentProfile.java b/src/jade/domain/mobility/MobileAgentProfile.java index 8523398..f522fb9 100644 --- a/src/jade/domain/mobility/MobileAgentProfile.java +++ b/src/jade/domain/mobility/MobileAgentProfile.java @@ -45,15 +45,6 @@ public class MobileAgentProfile implements Concept { public MobileAgentProfile() { } - /** - * Set the system slot of this action. - * - * @param s The runtime system of the described agent. - */ - public void setSystem(MobileAgentSystem s) { - system = s; - } - /** * Retrieve the value of the system slot of this * action, containing the runtime system of the described agent. @@ -66,12 +57,12 @@ public MobileAgentSystem getSystem() { } /** - * Set the language slot of this action. + * Set the system slot of this action. * - * @param l The language of the described agent. + * @param s The runtime system of the described agent. */ - public void setLanguage(MobileAgentLanguage l) { - language = l; + public void setSystem(MobileAgentSystem s) { + system = s; } /** @@ -86,12 +77,12 @@ public MobileAgentLanguage getLanguage() { } /** - * Set the os slot of this action. + * Set the language slot of this action. * - * @param o The OS of the described agent. + * @param l The language of the described agent. */ - public void setOS(MobileAgentOS o) { - os = o; + public void setLanguage(MobileAgentLanguage l) { + language = l; } /** @@ -105,4 +96,13 @@ public MobileAgentOS getOS() { return os; } + /** + * Set the os slot of this action. + * + * @param o The OS of the described agent. + */ + public void setOS(MobileAgentOS o) { + os = o; + } + } diff --git a/src/jade/domain/mobility/MobileAgentSystem.java b/src/jade/domain/mobility/MobileAgentSystem.java index 3fc011c..d9f53af 100644 --- a/src/jade/domain/mobility/MobileAgentSystem.java +++ b/src/jade/domain/mobility/MobileAgentSystem.java @@ -46,15 +46,6 @@ public class MobileAgentSystem implements Concept { public MobileAgentSystem() { } - /** - * Set the name slot of this action. - * - * @param n The runtime system of the described agent. - */ - public void setName(String n) { - name = n; - } - /** * Retrieve the value of the name slot of this * action, containing the runtime system of the described agent. @@ -67,13 +58,12 @@ public String getName() { } /** - * Set the major-version slot of this action. + * Set the name slot of this action. * - * @param v The major version number of the runtime system of the - * described agent. + * @param n The runtime system of the described agent. */ - public void setMajorVersion(Long v) { - majorVersion = v; + public void setName(String n) { + name = n; } /** @@ -89,13 +79,13 @@ public Long getMajorVersion() { } /** - * Set the minor-version slot of this action. + * Set the major-version slot of this action. * - * @param v The minor version number of the runtime system of the + * @param v The major version number of the runtime system of the * described agent. */ - public void setMinorVersion(Long v) { - minorVersion = v; + public void setMajorVersion(Long v) { + majorVersion = v; } /** @@ -111,13 +101,13 @@ public Long getMinorVersion() { } /** - * Set the dependencies slot of this action. + * Set the minor-version slot of this action. * - * @param d The runtime system dependencies of the described - * agent. + * @param v The minor version number of the runtime system of the + * described agent. */ - public void setDependencies(String d) { - dependencies = d; + public void setMinorVersion(Long v) { + minorVersion = v; } /** @@ -132,4 +122,14 @@ public String getDependencies() { return dependencies; } + /** + * Set the dependencies slot of this action. + * + * @param d The runtime system dependencies of the described + * agent. + */ + public void setDependencies(String d) { + dependencies = d; + } + } diff --git a/src/jade/domain/mobility/MobilityOntology.java b/src/jade/domain/mobility/MobilityOntology.java index 6e63388..56105e4 100644 --- a/src/jade/domain/mobility/MobilityOntology.java +++ b/src/jade/domain/mobility/MobilityOntology.java @@ -41,9 +41,10 @@ */ /** - This class represents the ontology used for JADE mobility. There is - only a single instance of this class. - @see MobilityOntology#getInstance() + * This class represents the ontology used for JADE mobility. There is + * only a single instance of this class. + * + * @see MobilityOntology#getInstance() */ public class MobilityOntology extends Ontology implements MobilityVocabulary { @@ -51,10 +52,6 @@ public class MobilityOntology extends Ontology implements MobilityVocabulary { private static final Ontology theInstance = new MobilityOntology(); - public static Ontology getInstance() { - return theInstance; - } - private MobilityOntology() { super(NAME, JADEManagementOntology.getInstance()); @@ -115,4 +112,8 @@ private MobilityOntology() { } } + public static Ontology getInstance() { + return theInstance; + } + } diff --git a/src/jade/domain/mobility/MoveAction.java b/src/jade/domain/mobility/MoveAction.java index 43387e4..0d2737d 100644 --- a/src/jade/domain/mobility/MoveAction.java +++ b/src/jade/domain/mobility/MoveAction.java @@ -44,16 +44,6 @@ public class MoveAction implements AgentAction { public MoveAction() { } - /** - * Set the mobile-agent-description slot of this - * action. - * - * @param desc The description of the agent to migrate. - */ - public void setMobileAgentDescription(MobileAgentDescription desc) { - agentToMove = desc; - } - /** * Retrieve the value of the mobile-agent-description * slot of this event, containing the description of the agent to @@ -66,4 +56,14 @@ public MobileAgentDescription getMobileAgentDescription() { return agentToMove; } + /** + * Set the mobile-agent-description slot of this + * action. + * + * @param desc The description of the agent to migrate. + */ + public void setMobileAgentDescription(MobileAgentDescription desc) { + agentToMove = desc; + } + } diff --git a/src/jade/domain/mobility/Parameter.java b/src/jade/domain/mobility/Parameter.java index 29c83d2..b09185d 100644 --- a/src/jade/domain/mobility/Parameter.java +++ b/src/jade/domain/mobility/Parameter.java @@ -59,6 +59,13 @@ public Parameter(String name, Object value, int mode) { this.mode = mode; } + /** + * @return the name of this parameter. + */ + public String getName() { + return name; + } + /** * Sets the name of this parameter. This will be used as * the key in the dinamically loaded behaviour HashMap @@ -69,10 +76,10 @@ public void setName(String name) { } /** - * @return the name of this parameter. + * @return the value of this parameter. */ - public String getName() { - return name; + public Object getValue() { + return value; } /** @@ -85,10 +92,10 @@ public void setValue(Object value) { } /** - * @return the value of this parameter. + * @return the IO mode of this parameter. */ - public Object getValue() { - return value; + public int getMode() { + return mode; } /** @@ -99,11 +106,4 @@ public Object getValue() { public void setMode(int mode) { this.mode = mode; } - - /** - * @return the IO mode of this parameter. - */ - public int getMode() { - return mode; - } } \ No newline at end of file diff --git a/src/jade/domain/persistence/DeleteAgent.java b/src/jade/domain/persistence/DeleteAgent.java index a7753d3..e44196d 100644 --- a/src/jade/domain/persistence/DeleteAgent.java +++ b/src/jade/domain/persistence/DeleteAgent.java @@ -40,36 +40,35 @@ */ public class DeleteAgent implements AgentAction { - public DeleteAgent() { - } + private AID agent; + private String repository; + private ContainerID where; - public void setAgent(AID id) { - agent = id; + public DeleteAgent() { } public AID getAgent() { return agent; } - public void setRepository(String r) { - repository = r; + public void setAgent(AID id) { + agent = id; } public String getRepository() { return repository; } - public void setWhere(ContainerID cid) { - where = cid; + public void setRepository(String r) { + repository = r; } public ContainerID getWhere() { return where; } - - private AID agent; - private String repository; - private ContainerID where; + public void setWhere(ContainerID cid) { + where = cid; + } } diff --git a/src/jade/domain/persistence/DeleteAgentGroup.java b/src/jade/domain/persistence/DeleteAgentGroup.java index cf517aa..8eeb59a 100644 --- a/src/jade/domain/persistence/DeleteAgentGroup.java +++ b/src/jade/domain/persistence/DeleteAgentGroup.java @@ -38,27 +38,26 @@ */ public class DeleteAgentGroup implements AgentAction { - public DeleteAgentGroup() { - } + private AgentGroup group; + private String repository; - public void setGroup(AgentGroup ag) { - group = ag; + public DeleteAgentGroup() { } public AgentGroup getGroup() { return group; } - public void setRepository(String r) { - repository = r; + public void setGroup(AgentGroup ag) { + group = ag; } public String getRepository() { return repository; } - - private AgentGroup group; - private String repository; + public void setRepository(String r) { + repository = r; + } } diff --git a/src/jade/domain/persistence/DeleteContainer.java b/src/jade/domain/persistence/DeleteContainer.java index 55605c0..c1a89ea 100644 --- a/src/jade/domain/persistence/DeleteContainer.java +++ b/src/jade/domain/persistence/DeleteContainer.java @@ -39,36 +39,35 @@ */ public class DeleteContainer implements AgentAction { - public DeleteContainer() { - } + private ContainerID container; + private ContainerID where; + private String repository; - public void setContainer(ContainerID id) { - container = id; + public DeleteContainer() { } public ContainerID getContainer() { return container; } - public void setWhere(ContainerID id) { - where = id; + public void setContainer(ContainerID id) { + container = id; } public ContainerID getWhere() { return where; } - public void setRepository(String r) { - repository = r; + public void setWhere(ContainerID id) { + where = id; } public String getRepository() { return repository; } - - private ContainerID container; - private ContainerID where; - private String repository; + public void setRepository(String r) { + repository = r; + } } diff --git a/src/jade/domain/persistence/FreezeAgent.java b/src/jade/domain/persistence/FreezeAgent.java index 2acc22e..5b29c86 100644 --- a/src/jade/domain/persistence/FreezeAgent.java +++ b/src/jade/domain/persistence/FreezeAgent.java @@ -41,35 +41,35 @@ */ public class FreezeAgent implements AgentAction { - public FreezeAgent() { - } + private AID agent; + private String repository; + private ContainerID bufferContainer; - public void setAgent(AID id) { - agent = id; + public FreezeAgent() { } public AID getAgent() { return agent; } - public void setRepository(String r) { - repository = r; + public void setAgent(AID id) { + agent = id; } public String getRepository() { return repository; } - public void setBufferContainer(ContainerID cid) { - bufferContainer = cid; + public void setRepository(String r) { + repository = r; } public ContainerID getBufferContainer() { return bufferContainer; } - private AID agent; - private String repository; - private ContainerID bufferContainer; + public void setBufferContainer(ContainerID cid) { + bufferContainer = cid; + } } diff --git a/src/jade/domain/persistence/LoadAgent.java b/src/jade/domain/persistence/LoadAgent.java index 8eef78d..2276fea 100644 --- a/src/jade/domain/persistence/LoadAgent.java +++ b/src/jade/domain/persistence/LoadAgent.java @@ -40,36 +40,35 @@ */ public class LoadAgent implements AgentAction { - public LoadAgent() { - } + private AID agent; + private String repository; + private ContainerID where; - public void setAgent(AID id) { - agent = id; + public LoadAgent() { } public AID getAgent() { return agent; } - public void setRepository(String r) { - repository = r; + public void setAgent(AID id) { + agent = id; } public String getRepository() { return repository; } - public void setWhere(ContainerID cid) { - where = cid; + public void setRepository(String r) { + repository = r; } public ContainerID getWhere() { return where; } - - private AID agent; - private String repository; - private ContainerID where; + public void setWhere(ContainerID cid) { + where = cid; + } } diff --git a/src/jade/domain/persistence/LoadAgentGroup.java b/src/jade/domain/persistence/LoadAgentGroup.java index 5e96a50..b897065 100644 --- a/src/jade/domain/persistence/LoadAgentGroup.java +++ b/src/jade/domain/persistence/LoadAgentGroup.java @@ -38,27 +38,26 @@ */ public class LoadAgentGroup implements AgentAction { - public LoadAgentGroup() { - } + private AgentGroup group; + private String repository; - public void setGroup(AgentGroup ag) { - group = ag; + public LoadAgentGroup() { } public AgentGroup getGroup() { return group; } - public void setRepository(String r) { - repository = r; + public void setGroup(AgentGroup ag) { + group = ag; } public String getRepository() { return repository; } - - private AgentGroup group; - private String repository; + public void setRepository(String r) { + repository = r; + } } diff --git a/src/jade/domain/persistence/LoadContainer.java b/src/jade/domain/persistence/LoadContainer.java index e04e8b9..ceafa8b 100644 --- a/src/jade/domain/persistence/LoadContainer.java +++ b/src/jade/domain/persistence/LoadContainer.java @@ -39,26 +39,26 @@ */ public class LoadContainer implements AgentAction { - public LoadContainer() { - } + private ContainerID container; + private String repository; - public void setContainer(ContainerID id) { - container = id; + public LoadContainer() { } public ContainerID getContainer() { return container; } - public void setRepository(String r) { - repository = r; + public void setContainer(ContainerID id) { + container = id; } public String getRepository() { return repository; } - private ContainerID container; - private String repository; + public void setRepository(String r) { + repository = r; + } } diff --git a/src/jade/domain/persistence/PersistenceOntology.java b/src/jade/domain/persistence/PersistenceOntology.java index 7b3085e..7f73d4c 100644 --- a/src/jade/domain/persistence/PersistenceOntology.java +++ b/src/jade/domain/persistence/PersistenceOntology.java @@ -51,23 +51,12 @@ public class PersistenceOntology extends Ontology implements PersistenceVocabula // The singleton instance of this ontology private static final Ontology theInstance = new PersistenceOntology(); - /** - * This method returns the unique instance (according to the singleton - * pattern) of the JADE-Persistence ontology. - * - * @return The singleton Ontology object, containing the - * schemas for the elements of the JADE-Persistence ontology. - */ - public static Ontology getInstance() { - return theInstance; - } - private PersistenceOntology() { //#MIDP_EXCLUDE_BEGIN super(NAME, ExceptionOntology.getInstance(), new BCReflectiveIntrospector()); //#MIDP_EXCLUDE_END - - /*#MIDP_INCLUDE_BEGIN + + /*#MIDP_INCLUDE_BEGIN super(NAME, BasicOntology.getInstance(), null); #MIDP_INCLUDE_END*/ @@ -96,8 +85,8 @@ private PersistenceOntology() { // Predicates definitions //#MIDP_EXCLUDE_END - - /*#MIDP_INCLUDE_BEGIN + + /*#MIDP_INCLUDE_BEGIN // Concepts definitions add(new ConceptSchema(AGENTGROUP)); add(new ConceptSchema(CONTAINERID)); @@ -193,4 +182,15 @@ private PersistenceOntology() { oe.printStackTrace(); } } + + /** + * This method returns the unique instance (according to the singleton + * pattern) of the JADE-Persistence ontology. + * + * @return The singleton Ontology object, containing the + * schemas for the elements of the JADE-Persistence ontology. + */ + public static Ontology getInstance() { + return theInstance; + } } diff --git a/src/jade/domain/persistence/ReloadAgent.java b/src/jade/domain/persistence/ReloadAgent.java index 817a52d..76417b5 100644 --- a/src/jade/domain/persistence/ReloadAgent.java +++ b/src/jade/domain/persistence/ReloadAgent.java @@ -38,27 +38,26 @@ */ public class ReloadAgent implements AgentAction { - public ReloadAgent() { - } + private AID agent; + private String repository; - public void setAgent(AID id) { - agent = id; + public ReloadAgent() { } public AID getAgent() { return agent; } - public void setRepository(String r) { - repository = r; + public void setAgent(AID id) { + agent = id; } public String getRepository() { return repository; } - - private AID agent; - private String repository; + public void setRepository(String r) { + repository = r; + } } diff --git a/src/jade/domain/persistence/SaveAgent.java b/src/jade/domain/persistence/SaveAgent.java index 16126ef..ec6cc15 100644 --- a/src/jade/domain/persistence/SaveAgent.java +++ b/src/jade/domain/persistence/SaveAgent.java @@ -38,27 +38,26 @@ */ public class SaveAgent implements AgentAction { - public SaveAgent() { - } + private AID agent; + private String repository; - public void setAgent(AID id) { - agent = id; + public SaveAgent() { } public AID getAgent() { return agent; } - public void setRepository(String r) { - repository = r; + public void setAgent(AID id) { + agent = id; } public String getRepository() { return repository; } - - private AID agent; - private String repository; + public void setRepository(String r) { + repository = r; + } } diff --git a/src/jade/domain/persistence/SaveAgentGroup.java b/src/jade/domain/persistence/SaveAgentGroup.java index d840780..c25d81c 100644 --- a/src/jade/domain/persistence/SaveAgentGroup.java +++ b/src/jade/domain/persistence/SaveAgentGroup.java @@ -38,27 +38,26 @@ */ public class SaveAgentGroup implements AgentAction { - public SaveAgentGroup() { - } + private AgentGroup group; + private String repository; - public void setGroup(AgentGroup ag) { - group = ag; + public SaveAgentGroup() { } public AgentGroup getGroup() { return group; } - public void setRepository(String r) { - repository = r; + public void setGroup(AgentGroup ag) { + group = ag; } public String getRepository() { return repository; } - - private AgentGroup group; - private String repository; + public void setRepository(String r) { + repository = r; + } } diff --git a/src/jade/domain/persistence/SaveContainer.java b/src/jade/domain/persistence/SaveContainer.java index 34a27a6..609428d 100644 --- a/src/jade/domain/persistence/SaveContainer.java +++ b/src/jade/domain/persistence/SaveContainer.java @@ -39,27 +39,26 @@ */ public class SaveContainer implements AgentAction { - public SaveContainer() { - } + private ContainerID container; + private String repository; - public void setContainer(ContainerID id) { - container = id; + public SaveContainer() { } public ContainerID getContainer() { return container; } - public void setRepository(String r) { - repository = r; + public void setContainer(ContainerID id) { + container = id; } public String getRepository() { return repository; } - - private ContainerID container; - private String repository; + public void setRepository(String r) { + repository = r; + } } diff --git a/src/jade/domain/persistence/ThawAgent.java b/src/jade/domain/persistence/ThawAgent.java index d17d42b..fd105fe 100644 --- a/src/jade/domain/persistence/ThawAgent.java +++ b/src/jade/domain/persistence/ThawAgent.java @@ -41,35 +41,35 @@ */ public class ThawAgent implements AgentAction { - public ThawAgent() { - } + private AID agent; + private String repository; + private ContainerID newContainer; - public void setAgent(AID id) { - agent = id; + public ThawAgent() { } public AID getAgent() { return agent; } - public void setRepository(String r) { - repository = r; + public void setAgent(AID id) { + agent = id; } public String getRepository() { return repository; } - public void setNewContainer(ContainerID cid) { - newContainer = cid; + public void setRepository(String r) { + repository = r; } public ContainerID getNewContainer() { return newContainer; } - private AID agent; - private String repository; - private ContainerID newContainer; + public void setNewContainer(ContainerID cid) { + newContainer = cid; + } } diff --git a/src/jade/gui/AIDGui.java b/src/jade/gui/AIDGui.java index d8d9a7a..feb57be 100644 --- a/src/jade/gui/AIDGui.java +++ b/src/jade/gui/AIDGui.java @@ -28,6 +28,7 @@ import javax.swing.*; import java.awt.*; import java.util.Enumeration; +import java.util.Objects; import java.util.Properties; /** @@ -39,6 +40,7 @@ */ public class AIDGui extends JDialog { + private final Component parentGUI; private boolean editable, checkSlots; private AID agentAID; private JTextField nameText; @@ -48,8 +50,6 @@ public class AIDGui extends JDialog { private VisualPropertiesList propertiesListPanel; private AID out; - private final Component parentGUI; - /** * Create a dialog with the given parent. @@ -81,10 +81,7 @@ public AID ShowAIDGui(AID agentIdentifier, boolean ed, boolean checkMandatorySlo this.editable = ed; this.checkSlots = checkMandatorySlots; - if (agentIdentifier == null) - this.agentAID = new AID(); - else - this.agentAID = agentIdentifier; + this.agentAID = Objects.requireNonNullElseGet(agentIdentifier, AID::new); JLabel label; diff --git a/src/jade/gui/APDescriptionPanel.java b/src/jade/gui/APDescriptionPanel.java index 18b642c..a059eef 100644 --- a/src/jade/gui/APDescriptionPanel.java +++ b/src/jade/gui/APDescriptionPanel.java @@ -101,24 +101,6 @@ public APDescriptionPanel(Component owner) { add(profilePanel); } - /** - * To set the field with the valued of a given APDescription. - */ - public void setAPDescription(APDescription desc) { - - try { - platformName_Field.setText(desc.getName()); - - //#DOTNET_EXCLUDE_BEGIN - MTPs_List.resetContent(desc.getAllAPServices()); - //#DOTNET_EXCLUDE_END - - } catch (Exception e) { - e.printStackTrace(); - } - - } - /** * To show an APDescription in a JDialog */ @@ -154,4 +136,22 @@ public static void showAPDescriptionInDialog(APDescription desc, Frame parent, S tempDlg.setVisible(true); } + /** + * To set the field with the valued of a given APDescription. + */ + public void setAPDescription(APDescription desc) { + + try { + platformName_Field.setText(desc.getName()); + + //#DOTNET_EXCLUDE_BEGIN + MTPs_List.resetContent(desc.getAllAPServices()); + //#DOTNET_EXCLUDE_END + + } catch (Exception e) { + e.printStackTrace(); + } + + } + } diff --git a/src/jade/gui/APServicePanel.java b/src/jade/gui/APServicePanel.java index 7742c6f..29b16c9 100644 --- a/src/jade/gui/APServicePanel.java +++ b/src/jade/gui/APServicePanel.java @@ -121,20 +121,6 @@ public class APServicePanel extends JPanel { } - /** - * Set the field of the gui. - */ - private void setAPService(APService ap) { - - if (ap != null) { - name_Field.setText(ap.getName()); - type_Field.setText(ap.getType()); - //#DOTNET_EXCLUDE_BEGIN - address_List.resetContent(ap.getAllAddresses()); - //#DOTNET_EXCLUDE_END - } - } - /** * To show an APService in A JDialog. */ @@ -171,5 +157,19 @@ public static void viewAPServiceDialog(APService ap, Dialog parent, String title } + /** + * Set the field of the gui. + */ + private void setAPService(APService ap) { + + if (ap != null) { + name_Field.setText(ap.getName()); + type_Field.setText(ap.getType()); + //#DOTNET_EXCLUDE_BEGIN + address_List.resetContent(ap.getAllAddresses()); + //#DOTNET_EXCLUDE_END + } + } + } diff --git a/src/jade/gui/AboutJadeAction.java b/src/jade/gui/AboutJadeAction.java index dd6d1e4..729e888 100644 --- a/src/jade/gui/AboutJadeAction.java +++ b/src/jade/gui/AboutJadeAction.java @@ -44,28 +44,23 @@ public class AboutJadeAction extends AbstractAction { * @serial */ private final JFrame gui; - - /** - * @serial - */ - private JLabel label; - /** * @serial */ Color dark_blue = new Color(0, 0, 160); - /** * @serial */ String logojade = "images/jadelogo.jpg"; - String check = "images/tick_blue.gif"; - /** * @serial */ String logocselt = "images/logotelecomlab.jpg"; + /** + * @serial + */ + private JLabel label; public AboutJadeAction(JFrame gui) { super("About JADE"); diff --git a/src/jade/gui/AclGui.java b/src/jade/gui/AclGui.java index 4d113c3..5235280 100644 --- a/src/jade/gui/AclGui.java +++ b/src/jade/gui/AclGui.java @@ -110,24 +110,36 @@ * @see ACLMessage */ public class AclGui extends JPanel { + private static final int TEXT_SIZE = 30; + private static final int N_FIPA_PROTOCOLS = 8; + private static final String[] fipaProtocols = {FIPANames.InteractionProtocol.FIPA_ENGLISH_AUCTION, + FIPANames.InteractionProtocol.FIPA_DUTCH_AUCTION, + FIPANames.InteractionProtocol.FIPA_CONTRACT_NET, + FIPANames.InteractionProtocol.FIPA_ITERATED_CONTRACT_NET, + FIPANames.InteractionProtocol.FIPA_QUERY, + FIPANames.InteractionProtocol.FIPA_REQUEST, + FIPANames.InteractionProtocol.FIPA_REQUEST_WHEN, + FIPANames.InteractionProtocol.FIPA_PROPOSE}; + private static final String LABEL_TO_ADD_PROT = "ADD USER-DEF PROTOCOL"; // Controls for ACL message parameter editing static String ADD_NEW_RECEIVER = "Insert receiver"; - + // Other data used + private static ACLMessage editedMsg; //the owner of the panel. private final Component ownerGui; - //the logger private final Logger logger = Logger.getMyLogger(this.getClass().getName()); - AID SenderAID = new AID(); AID newAIDSender = null; AID fromAID = new AID(); AID newAIDFrom = null; - VisualAIDList receiverListPanel; VisualAIDList replyToListPanel; VisualPropertiesList propertiesListPanel; - + // Data for panel layout definition + GridBagLayout lm = new GridBagLayout(); + GridBagConstraints constraint = new GridBagConstraints(); + SLFormatter slFormatter; private boolean guiEnabledFlag; private JTextField sender; private boolean senderEnabledFlag; @@ -145,43 +157,19 @@ public class AclGui extends JPanel { private Date replyByDate; private Date dateDate; private Date dateRecDate; - - // Data for panel layout definition - GridBagLayout lm = new GridBagLayout(); - GridBagConstraints constraint = new GridBagConstraints(); private int leftBorder, rightBorder, topBorder, bottomBorder; private int xSpacing, ySpacing; private int gridNCol, gridNRow; private int[] colWidth; - private static final int TEXT_SIZE = 30; - private Vector fipaActVector; - - private static final int N_FIPA_PROTOCOLS = 8; - private static final String[] fipaProtocols = {FIPANames.InteractionProtocol.FIPA_ENGLISH_AUCTION, - FIPANames.InteractionProtocol.FIPA_DUTCH_AUCTION, - FIPANames.InteractionProtocol.FIPA_CONTRACT_NET, - FIPANames.InteractionProtocol.FIPA_ITERATED_CONTRACT_NET, - FIPANames.InteractionProtocol.FIPA_QUERY, - FIPANames.InteractionProtocol.FIPA_REQUEST, - FIPANames.InteractionProtocol.FIPA_REQUEST_WHEN, - FIPANames.InteractionProtocol.FIPA_PROPOSE}; - private ArrayList fipaProtocolArrayList; - - // Data for the editing of user defined iteration protocols private int lastSelectedIndex; private String lastSelectedItem; - private static final String LABEL_TO_ADD_PROT = "ADD USER-DEF PROTOCOL"; - // These data are used to correctly handle the resizing of the AclGui panel private JPanel aclPanel; private Dimension minDim; private boolean firstPaintFlag; - - // Other data used - private static ACLMessage editedMsg; private JButton senderButton; private VisualAIDList toPanel; private JTextField from; @@ -201,681 +189,138 @@ public class AclGui extends JPanel { private JTextField via; private JTextField id; + /** + * Ordinary AclGui constructor. + * + * @see ACLMessage#ACLMessage(int) + */ - private class AclMessagePanel extends JPanel - //#DOTNET_EXCLUDE_BEGIN - implements DropTargetListener - //#DOTNET_EXCLUDE_END - { - AclMessagePanel() { + public AclGui(Component owner) { - JLabel l; - int i; + firstPaintFlag = true; + guiEnabledFlag = true; + minDim = new Dimension(); + ownerGui = owner; - // Initialize the Vector of interaction protocols - fipaProtocolArrayList = new ArrayList<>(); + JTabbedPane tabbed = new JTabbedPane(); + AclMessagePanel aclPane = new AclMessagePanel(); + EnvelopePanel envelope = new EnvelopePanel(); + tabbed.addTab("ACLMessage", aclPane); + tabbed.addTab("Envelope", envelope); + //to enable the textfields if needed. + updateEnabled(); + add(tabbed); - for (i = 0; i < N_FIPA_PROTOCOLS; ++i) - fipaProtocolArrayList.add(fipaProtocols[i]); + // Try inserting formatted SL content. + // any Exception is catched in order to remove unwished dependency + // on the jade.tools.sl package from this package at run-time. + try { + slFormatter = new SLFormatter(); + } catch (Exception ignored) { + } + } - aclPanel = new JPanel(); - //#DOTNET_EXCLUDE_BEGIN - new DropTarget(aclPanel, this); - //#DOTNET_EXCLUDE_END + ///////////////// + // CONSTRUCTOR + ///////////////// - aclPanel.setLayout(lm); + /** + * Pops up a dialog window including an editing-disabled AclGui panel and displays the specified + * ACL message in it. + * + * @param msg The ACL message to be displayed + * @param parent The parent window of the dialog window + * @see AclGui#editMsgInDialog(ACLMessage msg, Frame parent) + */ + public static void showMsgInDialog(ACLMessage msg, Frame parent) { + final JDialog tempAclDlg = new JDialog(parent, "ACL Message", true); - formatGrid(20, // N of rows - 3, // N of columns - 5, // Right border - 5, // Left border - 5, // Top boredr - 5, // Bottom border - 2, // Space between columns - 2); // Space between rows - setGridColumnWidth(0, 115); - setGridColumnWidth(1, 40); - setGridColumnWidth(2, 170); + AclGui aclPanel = new AclGui(parent); + //aclPanel.setBorder(new BevelBorder(BevelBorder.RAISED)); + aclPanel.setEnabled(false); + aclPanel.setMsg(msg); + JButton okButton = new JButton("OK"); + JPanel buttonPanel = new JPanel(); + // Use default (FlowLayout) layout manager to dispose the OK button + buttonPanel.add(okButton); - // Sender (line # 0) - l = new JLabel("Sender:"); - //#DOTNET_EXCLUDE_BEGIN - new DropTarget(l, this); - //#DOTNET_EXCLUDE_END - put(aclPanel, l, 0, 0, 1, 1, false); - senderEnabledFlag = true; // The sender field is enabled by default, but can be disabled with the setSenderEnabled() method. - sender = new JTextField(); - sender.setPreferredSize(new Dimension(80, 26)); - sender.setMinimumSize(new Dimension(80, 26)); - sender.setMaximumSize(new Dimension(80, 26)); - sender.setEditable(false); - sender.setBackground(Color.white); - senderButton = new JButton("Set"); - senderButton.setMargin(new Insets(2, 3, 2, 3)); + tempAclDlg.getContentPane().setLayout(new BorderLayout()); + tempAclDlg.getContentPane().add("Center", aclPanel); + tempAclDlg.getContentPane().add("South", buttonPanel); - put(aclPanel, senderButton, 1, 0, 1, 1, false); - put(aclPanel, sender, 2, 0, 1, 1, false); + okButton.addActionListener(e -> tempAclDlg.dispose()); - senderButton.addActionListener(e -> { - String command = e.getActionCommand(); - AIDGui guiSender = new AIDGui(getChildrenOwner()); + tempAclDlg.pack(); + tempAclDlg.setResizable(false); + if (parent != null) { + int locx = parent.getX() + (parent.getWidth() - tempAclDlg.getWidth()) / 2; + if (locx < 0) + locx = 0; + int locy = parent.getY() + (parent.getHeight() - tempAclDlg.getHeight()) / 2; + if (locy < 0) + locy = 0; + tempAclDlg.setLocation(locx, locy); + } + tempAclDlg.setVisible(true); + } - if (command.equals("Set")) { - AID senderToView = SenderAID; - //another sender was already inserted. - if (newAIDSender != null) - senderToView = newAIDSender; - senderToView = guiSender.ShowAIDGui(senderToView, true, true); - //if the cancel button was clicked --> maintain the old value inserted. - if (senderToView != null) { - newAIDSender = senderToView; - //the name can be different - sender.setText(newAIDSender.getName()); - } - } else if (command.equals("View")) - guiSender.ShowAIDGui(SenderAID, false, false); + /** + * Pops up a dialog window including an editing-enabled AclGui panel and displays the specified + * ACL message in it. The dialog window also includes an OK and a Cancel button to accept or + * discard the performed editing. + * + * @param msg The ACL message to be initially displayed + * @param parent The parent window of the dialog window + * @return The ACL message displayed in the dialog window or null depending on whether the user close the window + * by clicking the OK or Cancel button + * @see AclGui#showMsgInDialog(ACLMessage msg, Frame parent) + */ + public static ACLMessage editMsgInDialog(ACLMessage msg, Frame parent) { + final JDialog tempAclDlg = new JDialog(parent, "ACL Message", true); + final AclGui aclPanel = new AclGui(parent); + aclPanel.setBorder(new BevelBorder(BevelBorder.RAISED)); + aclPanel.setSenderEnabled(true); + aclPanel.setMsg(msg); - }); + JButton okButton = new JButton("OK"); + JButton cancelButton = new JButton("Cancel"); + okButton.setPreferredSize(cancelButton.getPreferredSize()); + JPanel buttonPanel = new JPanel(); + // Use default (FlowLayout) layout manager to dispose the OK and Cancel buttons + buttonPanel.add(okButton); + buttonPanel.add(cancelButton); - // Receiver (line # 1) - l = new JLabel("Receivers:"); - //#DOTNET_EXCLUDE_BEGIN - new DropTarget(l, this); - //#DOTNET_EXCLUDE_END - put(aclPanel, l, 0, 1, 1, 1, false); - receiverListPanel = new VisualAIDList(Collections.emptyIterator(), getChildrenOwner()); - receiverListPanel.setDimension(new Dimension(205, 37)); - put(aclPanel, receiverListPanel, 1, 1, 2, 1, false); + tempAclDlg.getContentPane().setLayout(new BorderLayout()); + tempAclDlg.getContentPane().add("Center", aclPanel); + tempAclDlg.getContentPane().add("South", buttonPanel); + okButton.addActionListener(e -> { + editedMsg = aclPanel.getMsg(); + tempAclDlg.dispose(); + }); + cancelButton.addActionListener(e -> { + editedMsg = null; + tempAclDlg.dispose(); + }); - //Reply-to (line #2) - l = new JLabel("Reply-to:"); - //#DOTNET_EXCLUDE_BEGIN - new DropTarget(l, this); - //#DOTNET_EXCLUDE_END - put(aclPanel, l, 0, 2, 1, 1, false); - replyToListPanel = new VisualAIDList(Collections.emptyIterator(), getChildrenOwner()); - replyToListPanel.setDimension(new Dimension(205, 37)); - put(aclPanel, replyToListPanel, 1, 2, 2, 1, false); + tempAclDlg.pack(); + tempAclDlg.setResizable(false); - // Communicative act (line # 3) - l = new JLabel("Communicative act:"); - //#DOTNET_EXCLUDE_BEGIN - new DropTarget(l, this); - //#DOTNET_EXCLUDE_END - put(aclPanel, l, 0, 3, 1, 1, false); - communicativeAct = new JComboBox<>(); + if (parent != null) { + int x = parent.getX() + (parent.getWidth() - tempAclDlg.getWidth()) / 2; + int y = parent.getY() + (parent.getHeight() - tempAclDlg.getHeight()) / 2; + tempAclDlg.setLocation(Math.max(x, 0), Math.max(y, 0)); + } - String[] comm_Act = ACLMessage.getAllPerformativeNames(); - for (String s : comm_Act) - communicativeAct.addItem(s.toLowerCase()); + tempAclDlg.setVisible(true); - communicativeAct.setSelectedIndex(0); - put(aclPanel, communicativeAct, 1, 3, 2, 1, true); + ACLMessage m = null; + if (editedMsg != null) + m = (ACLMessage) editedMsg.clone(); - // Content (line # 4-8) - l = new JLabel("Content:"); - //#DOTNET_EXCLUDE_BEGIN - new DropTarget(l, this); - //#DOTNET_EXCLUDE_END - put(aclPanel, l, 0, 4, 3, 1, false); - content = new JTextArea(5, TEXT_SIZE); - JScrollPane contentPane = new JScrollPane(); - contentPane.getViewport().setView(content); - put(aclPanel, contentPane, 0, 5, 3, 4, false); - contentPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); - contentPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); - - // Language (line # 9) - l = new JLabel("Language:"); - //#DOTNET_EXCLUDE_BEGIN - new DropTarget(l, this); - //#DOTNET_EXCLUDE_END - put(aclPanel, l, 0, 9, 1, 1, false); - language = new JTextField(); - language.setBackground(Color.white); - put(aclPanel, language, 1, 9, 2, 1, false); - - //Encoding (line # 10) - l = new JLabel("Encoding:"); - //#DOTNET_EXCLUDE_BEGIN - new DropTarget(l, this); - //#DOTNET_EXCLUDE_END - put(aclPanel, l, 0, 10, 1, 1, false); - encoding = new JTextField(); - encoding.setBackground(Color.white); - put(aclPanel, encoding, 1, 10, 2, 1, false); - - // Ontology (line # 11) - l = new JLabel("Ontology:"); - //#DOTNET_EXCLUDE_BEGIN - new DropTarget(l, this); - //#DOTNET_EXCLUDE_END - put(aclPanel, l, 0, 11, 1, 1, false); - ontology = new JTextField(); - ontology.setBackground(Color.white); - put(aclPanel, ontology, 1, 11, 2, 1, false); - - // Protocol (line # 12) - l = new JLabel("Protocol:"); - //#DOTNET_EXCLUDE_BEGIN - new DropTarget(l, this); - //#DOTNET_EXCLUDE_END - put(aclPanel, l, 0, 12, 1, 1, false); - protocol = new JComboBox<>(); - for (i = 0; i < fipaProtocolArrayList.size(); ++i) - protocol.addItem(fipaProtocolArrayList.get(i)); - protocol.addItem(LABEL_TO_ADD_PROT); - protocol.addItem("Null"); - protocol.setSelectedItem("Null"); - lastSelectedIndex = protocol.getSelectedIndex(); - lastSelectedItem = (String) protocol.getSelectedItem(); - put(aclPanel, protocol, 1, 12, 2, 1, true); - protocol.addActionListener(e -> { - String param = (String) protocol.getSelectedItem(); - - // BEFORE THE CURRENT SELECTION THE JComboBox WAS NON EDITABLE (a FIPA protocol or null was selected) - if (!protocol.isEditable()) { - // If a user defined protocol has just been selected --> set editable to true - if (!fipaProtocolArrayList.contains(param) && !Objects.equals(param, "Null")) { - protocol.setEditable(true); - } - } - // BEFORE THE CURRENT SELECTION THE JComboBox WAS EDITABLE (an editable protocol was selected) - else { - // The user selected a FIPA protocol or null (he didn't perform any editing operation) - if (fipaProtocolArrayList.contains(param) || Objects.equals(param, "Null")) { - protocol.setEditable(false); - protocol.setSelectedItem(param); - } - // The user selected the label to add a new protocol (he didn't perform any editing operation) - else if (param.equals(LABEL_TO_ADD_PROT)) { - protocol.setSelectedItem(param); - } - // The user added a new protocol - else if (lastSelectedItem.equals(LABEL_TO_ADD_PROT)) { - // The new protocol is actually added only if it is != "" and is not already present - if (!param.equals("")) { - protocol.addItem(param); - int cnt = protocol.getItemCount(); - protocol.setSelectedItem(param); - int n = protocol.getSelectedIndex(); - if (n != cnt - 1) - protocol.removeItemAt(cnt - 1); - } else { - protocol.setEditable(false); - protocol.setSelectedItem("Null"); - } - } - // The user modified/deleted a previously added user defined protocol - else if (!lastSelectedItem.equals(LABEL_TO_ADD_PROT)) { - protocol.removeItemAt(lastSelectedIndex); // The old protocol is removed - if (param.equals("")) // Deletion - { - protocol.setEditable(false); - protocol.setSelectedItem("Null"); - } else // Modification - { - protocol.addItem(param); - protocol.setSelectedItem(param); - } - } - } - - lastSelectedIndex = protocol.getSelectedIndex(); - lastSelectedItem = (String) protocol.getSelectedItem(); - }); - - // Conversation-id (line # 13) - l = new JLabel("Conversation-id:"); - //#DOTNET_EXCLUDE_BEGIN - new DropTarget(l, this); - //#DOTNET_EXCLUDE_END - put(aclPanel, l, 0, 13, 1, 1, false); - conversationId = new JTextField(); - conversationId.setBackground(Color.white); - put(aclPanel, conversationId, 1, 13, 2, 1, false); - - // In-reply-to (line # 14) - l = new JLabel("In-reply-to:"); - //#DOTNET_EXCLUDE_BEGIN - new DropTarget(l, this); - //#DOTNET_EXCLUDE_END - put(aclPanel, l, 0, 14, 1, 1, false); - inReplyTo = new JTextField(); - inReplyTo.setBackground(Color.white); - put(aclPanel, inReplyTo, 1, 14, 2, 1, false); - - // Reply-with (line # 15) - l = new JLabel("Reply-with:"); - //#DOTNET_EXCLUDE_BEGIN - new DropTarget(l, this); - //#DOTNET_EXCLUDE_END - put(aclPanel, l, 0, 15, 1, 1, false); - replyWith = new JTextField(); - replyWith.setBackground(Color.white); - put(aclPanel, replyWith, 1, 15, 2, 1, false); - - // Reply-by (line # 16) - replyByDate = null; - l = new JLabel("Reply-by:"); - //#DOTNET_EXCLUDE_BEGIN - new DropTarget(l, this); - //#DOTNET_EXCLUDE_END - put(aclPanel, l, 0, 16, 1, 1, false); - replyBySet = new JButton("Set"); - replyBySet.setMargin(new Insets(2, 3, 2, 3)); - replyBy = new JTextField(); - replyBy.setBackground(Color.white); - put(aclPanel, replyBySet, 1, 16, 1, 1, false); - put(aclPanel, replyBy, 2, 16, 1, 1, false); - // BEGIN anonumous class -// END actionPerformed(ActionEvent e) - replyBySet.addActionListener(e -> { - String command = e.getActionCommand(); - //TimeChooser t = new TimeChooser(replyByDate); - TimeChooser t = new TimeChooser(); - String d = replyBy.getText(); - if (!d.equals("")) { - try { - t.setDate(ISO8601.toDate(d)); - } catch (Exception ee) { - if (logger.isLoggable(Logger.SEVERE)) - logger.log(Logger.WARNING, "Incorrect date format"); - } - } - if (command.equals("Set")) { - if (t.showEditTimeDlg(null) == TimeChooser.OK) { - replyByDate = t.getDate(); - if (replyByDate == null) - replyBy.setText(""); - else - replyBy.setText(ISO8601.toString(replyByDate)); - } - } else if (command.equals("View")) { - t.showViewTimeDlg(null); - } - } // END anonymous class - ); - - - //Properties (line #17) - l = new JLabel("User Properties:"); - //#DOTNET_EXCLUDE_BEGIN - new DropTarget(l, this); - //#DOTNET_EXCLUDE_END - put(aclPanel, l, 0, 17, 1, 1, false); - propertiesListPanel = new VisualPropertiesList(new Properties(), getChildrenOwner()); - propertiesListPanel.setDimension(new Dimension(205, 37)); - put(aclPanel, propertiesListPanel, 1, 17, 2, 1, false); - - setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); - add(aclPanel); - - } // END AclMessagePanel() - - //#DOTNET_EXCLUDE_BEGIN - public void dragOver(DropTargetDragEvent p1) { - if (logger.isLoggable(Logger.FINEST)) - logger.log(Logger.FINEST, "dragOver"); - } - - public void dropActionChanged(DropTargetDragEvent p1) { - if (logger.isLoggable(Logger.FINEST)) - logger.log(Logger.FINEST, "dropActionChanged"); - } - - public void dragEnter(DropTargetDragEvent dragEvent) { - if (logger.isLoggable(Logger.FINEST)) - logger.log(Logger.FINEST, "dragEnter"); - } - - public void dragExit(DropTargetEvent p1) { - if (logger.isLoggable(Logger.FINEST)) - logger.log(Logger.FINEST, "dragExit"); - } - - public void drop(DropTargetDropEvent dropEvent) { - boolean completionStatus = false; - List fileList = null; - - try { - dropEvent.acceptDrop(DnDConstants.ACTION_COPY); - - Transferable xferInfo = dropEvent.getTransferable(); - fileList = (List) xferInfo.getTransferData(DataFlavor.javaFileListFlavor); - completionStatus = true; - } catch (UnsupportedFlavorException exc) { - completionStatus = false; - } catch (IOException exc) { - if (logger.isLoggable(Logger.WARNING)) - logger.log(Logger.WARNING, "DragAndDrop operation failed: " + exc); - completionStatus = false; - } finally { - dropEvent.dropComplete(completionStatus); - } - - if (fileList != null) { - Iterator fileItor = fileList.iterator(); - ACLParser aclParser = ACLParser.create(); - while (fileItor.hasNext()) { - try { - File f = (File) (fileItor.next()); - FileReader aclMsgFile = new FileReader(f); - Enumeration receivers = receiverListPanel.getContent(); - setMsg(aclParser.parse(aclMsgFile)); - if (receivers.hasMoreElements()) { - if (logger.isLoggable(Logger.FINE)) - logger.log(Logger.FINE, "revert to saved list"); - ArrayList list = new ArrayList<>(); - while (receivers.hasMoreElements()) { - list.add(receivers.nextElement()); - } - receiverListPanel.resetContent(list.iterator()); - } - } catch (Throwable exc) { - if (logger.isLoggable(Logger.WARNING)) - logger.log(Logger.WARNING, "DragAndDrop operation failed: " + exc); - } - } //~ while (fileItor.hasNext()) - } //~ if (selectedItems != null) - - } // END drop(dropEvent) - //#DOTNET_EXCLUDE_END - - } // END class AclMessagePanel - - //this private class build a panel to show the envelope field of an ACLMessage - private class EnvelopePanel extends JPanel { - EnvelopePanel() { - - JLabel l; - int i; - - //minDim = new Dimension(); - aclPanel = new JPanel(); - //aclPanel.setBackground(Color.lightGray); - aclPanel.setLayout(lm); - - formatGrid(20, // N of rows - 3, // N of columns - 5, // Right border - 5, // Left border - 5, // Top boredr - 5, // Bottom border - 2, // Space between columns - 2); // Space between rows - setGridColumnWidth(0, 115); - setGridColumnWidth(1, 40); - setGridColumnWidth(2, 170); - - // To (line # 0) - l = new JLabel("To:"); - put(aclPanel, l, 0, 0, 1, 1, false); - toPanel = new VisualAIDList(Collections.emptyIterator(), getChildrenOwner()); - toPanel.setDimension(new Dimension(205, 37)); - put(aclPanel, toPanel, 1, 0, 2, 1, false); - - //From (line #1) - l = new JLabel("From:"); - put(aclPanel, l, 0, 1, 1, 1, false); - fromButton = new JButton("Set"); - fromButton.setMargin(new Insets(2, 3, 2, 3)); - put(aclPanel, fromButton, 1, 1, 1, 1, false); - from = new JTextField(); - from.setEditable(false); - from.setBackground(Color.white); - put(aclPanel, from, 2, 1, 1, 1, false); - fromButton.addActionListener(e -> { - String command = e.getActionCommand(); - AIDGui guiFrom = new AIDGui(ownerGui); - if (command.equals("Set")) { - AID fromToView = fromAID; - if (newAIDFrom != null) - fromToView = newAIDFrom; - fromToView = guiFrom.ShowAIDGui(fromToView, true, true); - if (fromToView != null) { - newAIDFrom = fromToView; - from.setText(newAIDFrom.getName()); - } - } else { - if (command.equals("View")) - guiFrom.ShowAIDGui(fromAID, false, false); - } - }); - - //Comments (line # 2-6) - l = new JLabel("Comments:"); - put(aclPanel, l, 0, 2, 1, 1, false); - comments = new JTextArea(4, TEXT_SIZE); - JScrollPane commentsPane = new JScrollPane(); - commentsPane.getViewport().setView(comments); - put(aclPanel, commentsPane, 0, 3, 3, 4, false); - commentsPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); - commentsPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); - - //aclRappresentation (line # 7) - l = new JLabel("ACLRepresentation:"); - put(aclPanel, l, 0, 7, 1, 1, false); - representation = new JTextField(); - representation.setBackground(Color.white); - put(aclPanel, representation, 1, 7, 2, 1, false); - - //payloadLength (line # 8) - l = new JLabel("Payload Length:"); - put(aclPanel, l, 0, 8, 1, 1, false); - payloadLength = new JTextField(); - payloadLength.setBackground(Color.white); - put(aclPanel, payloadLength, 1, 8, 2, 1, false); - - //payloadEncoding (line # 9) - l = new JLabel("Payload Encoding:"); - put(aclPanel, l, 0, 9, 1, 1, false); - payloadEncoding = new JTextField(); - payloadEncoding.setBackground(Color.white); - put(aclPanel, payloadEncoding, 1, 9, 2, 1, false); - - //Date (line # 10) - dateDate = null; - l = new JLabel("Date:"); - put(aclPanel, l, 0, 10, 1, 1, false); - dateButton = new JButton("Set"); - dateButton.setMargin(new Insets(2, 3, 2, 3)); - date = new JTextField(); - date.setBackground(Color.white); - put(aclPanel, dateButton, 1, 10, 1, 1, false); - put(aclPanel, date, 2, 10, 1, 1, false); - dateButton.addActionListener(e -> { - String command = e.getActionCommand(); - //TimeChooser t = new TimeChooser(replyByDate); - TimeChooser t = new TimeChooser(); - String d = date.getText(); - if (!d.equals("")) { - try { - t.setDate(ISO8601.toDate(d)); - } catch (Exception ee) { - if (logger.isLoggable(Logger.WARNING)) - logger.log(Logger.WARNING, "Incorrect date format"); - } - } - if (command.equals("Set")) { - if (t.showEditTimeDlg(null) == TimeChooser.OK) { - dateDate = t.getDate(); - if (dateDate == null) - date.setText(""); - else - date.setText(ISO8601.toString(dateDate)); - } - } else if (command.equals("View")) { - t.showViewTimeDlg(null); - } - }); - - //intendedReceiver (line #11) - l = new JLabel("Intended Receiver:"); - put(aclPanel, l, 0, 11, 1, 1, false); - intendedReceiverPanel = new VisualAIDList(Collections.emptyIterator(), getChildrenOwner()); - intendedReceiverPanel.setDimension(new Dimension(205, 37)); - put(aclPanel, intendedReceiverPanel, 1, 11, 2, 1, false); - - //ReceivedObject (line #12-15) - JPanel recPanel = new JPanel(); - recPanel.setLayout(new BoxLayout(recPanel, BoxLayout.Y_AXIS)); - JPanel tempPane = new JPanel(); - tempPane.setLayout(new BoxLayout(tempPane, BoxLayout.X_AXIS)); - recPanel.setBorder(new TitledBorder("Received Object")); - l = new JLabel("By:"); - l.setPreferredSize(new Dimension(115, 24)); - l.setMinimumSize(new Dimension(115, 24)); - l.setMaximumSize(new Dimension(115, 24)); - tempPane.add(l); - by = new JTextField(); - by.setBackground(Color.white); - tempPane.add(by); - recPanel.add(tempPane); - tempPane = new JPanel(); - tempPane.setLayout(new BoxLayout(tempPane, BoxLayout.X_AXIS)); - - l = new JLabel("From:"); - l.setPreferredSize(new Dimension(115, 24)); - l.setMinimumSize(new Dimension(115, 24)); - l.setMaximumSize(new Dimension(115, 24)); - tempPane.add(l); - fromRec = new JTextField(); - fromRec.setBackground(Color.white); - tempPane.add(fromRec); - recPanel.add(tempPane); - - tempPane = new JPanel(); - tempPane.setLayout(new BoxLayout(tempPane, BoxLayout.X_AXIS)); - - dateRecDate = null; - l = new JLabel("Date:"); - l.setPreferredSize(new Dimension(115, 24)); - l.setMinimumSize(new Dimension(115, 24)); - l.setMaximumSize(new Dimension(115, 24)); - tempPane.add(l); - dateRecButton = new JButton("Set"); - tempPane.add(dateRecButton); - dateRecButton.addActionListener(e -> { - String command = e.getActionCommand(); - //TimeChooser t = new TimeChooser(replyByDate); - TimeChooser t = new TimeChooser(); - String d = dateRec.getText(); - if (!d.equals("")) { - try { - t.setDate(ISO8601.toDate(d)); - } catch (Exception ee) { - if (logger.isLoggable(Logger.WARNING)) - logger.log(Logger.WARNING, "Incorrect date format"); - } - } - if (command.equals("Set")) { - if (t.showEditTimeDlg(null) == TimeChooser.OK) { - dateRecDate = t.getDate(); - if (dateRecDate == null) - dateRec.setText(""); - else - dateRec.setText(ISO8601.toString(dateRecDate)); - } - } else if (command.equals("View")) { - t.showViewTimeDlg(null); - } - }); - - dateRec = new JTextField(); - dateRec.setBackground(Color.white); - tempPane.add(dateRec); - recPanel.add(tempPane); - - tempPane = new JPanel(); - tempPane.setLayout(new BoxLayout(tempPane, BoxLayout.X_AXIS)); - - l = new JLabel("ID:"); - l.setPreferredSize(new Dimension(115, 24)); - l.setMinimumSize(new Dimension(115, 24)); - l.setMaximumSize(new Dimension(115, 24)); - tempPane.add(l); - id = new JTextField(); - id.setBackground(Color.white); - tempPane.add(id); - recPanel.add(tempPane); - - tempPane = new JPanel(); - tempPane.setLayout(new BoxLayout(tempPane, BoxLayout.X_AXIS)); - - l = new JLabel("Via:"); - l.setPreferredSize(new Dimension(115, 24)); - l.setMinimumSize(new Dimension(115, 24)); - l.setMaximumSize(new Dimension(115, 24)); - tempPane.add(l); - via = new JTextField(); - via.setBackground(Color.white); - tempPane.add(via); - recPanel.add(tempPane); - - put(aclPanel, recPanel, 0, 12, 3, 1, false); - - //(line 17) - JPanel tmpPanel = new JPanel(); - //tmpPanel.setBackground(Color.lightGray); - defaultEnvelopeButton = new JButton("Set Default Envelope"); - tmpPanel.add(defaultEnvelopeButton); - - defaultEnvelopeButton.addActionListener(e -> { - String command = e.getActionCommand(); - if (command.equals("Set Default Envelope")) { - ACLMessage tmp = getMsg(); - tmp.setDefaultEnvelope(); - Envelope envtmp = tmp.getEnvelope(); - showEnvelope(envtmp); - } - }); - put(aclPanel, tmpPanel, 0, 17, 3, 1, false); - //setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); - add(aclPanel); - - - } - - } - - - ///////////////// - // CONSTRUCTOR - ///////////////// - - /** - * Ordinary AclGui constructor. - * - * @see ACLMessage#ACLMessage(int) - */ - - public AclGui(Component owner) { - - firstPaintFlag = true; - guiEnabledFlag = true; - minDim = new Dimension(); - ownerGui = owner; - - JTabbedPane tabbed = new JTabbedPane(); - AclMessagePanel aclPane = new AclMessagePanel(); - EnvelopePanel envelope = new EnvelopePanel(); - tabbed.addTab("ACLMessage", aclPane); - tabbed.addTab("Envelope", envelope); - //to enable the textfields if needed. - updateEnabled(); - add(tabbed); - - // Try inserting formatted SL content. - // any Exception is catched in order to remove unwished dependency - // on the jade.tools.sl package from this package at run-time. - try { - slFormatter = new SLFormatter(); - } catch (Exception ignored) { - } + return m; } private Component getChildrenOwner() { @@ -883,8 +328,6 @@ private Component getChildrenOwner() { return ownerGui != null ? ownerGui : this; } - SLFormatter slFormatter; - //////////////////// // PRIVATE METHODS //////////////////// @@ -1003,84 +446,246 @@ private void showEnvelope(Envelope envelope) { } from.setText(param); - try { - param = envelope.getComments(); - } catch (NullPointerException e1) { - param = ""; - } - comments.setText(param); + try { + param = envelope.getComments(); + } catch (NullPointerException e1) { + param = ""; + } + comments.setText(param); + + try { + param = envelope.getAclRepresentation(); + } catch (NullPointerException e1) { + param = ""; + } + representation.setText(param); + + try { + param = envelope.getPayloadLength().toString(); + } catch (NullPointerException e1) { + param = "-1"; + } + payloadLength.setText(param); + + try { + param = envelope.getPayloadEncoding(); + } catch (NullPointerException e1) { + param = ""; + } + payloadEncoding.setText(param); + + //Date + dateDate = envelope.getDate(); + if (dateDate != null) + date.setText(ISO8601.toString(dateDate)); + else + date.setText(""); + + //#DOTNET_EXCLUDE_BEGIN + intendedReceiverPanel.resetContent(envelope.getAllIntendedReceiver()); + //#DOTNET_EXCLUDE_END + + ReceivedObject recObject = envelope.getReceived(); + try { + param = recObject.getBy(); + } catch (NullPointerException e) { + param = ""; + } + by.setText(param); + try { + param = recObject.getFrom(); + } catch (NullPointerException e) { + param = ""; + } + fromRec.setText(param); + + try { + dateRecDate = recObject.getDate(); + param = ISO8601.toString(dateRecDate); + } catch (NullPointerException e) { + param = ""; + } + dateRec.setText(param); + + try { + param = recObject.getId(); + } catch (NullPointerException e) { + param = ""; + } + id.setText(param); + try { + param = recObject.getVia(); + } catch (NullPointerException e) { + param = ""; + } + via.setText(param); + } + + ///////////////////////////////////////////// + // MESSAGE GETTING and SETTING PUBLIC METHODS + ///////////////////////////////////////////// + + /** + * Get the ACL message currently displayed by the AclGui panel + * + * @return The ACL message currently displayed by the AclGui panel as an ACLMessage object + * @see AclGui#setMsg(ACLMessage msg) + */ + public ACLMessage getMsg() { + String param; + param = (String) communicativeAct.getSelectedItem(); + int perf = ACLMessage.getInteger(param); + ACLMessage msg = new ACLMessage(perf); + + if (newAIDSender != null) + SenderAID = newAIDSender; + + /*if ( ((param = sender.getText()).trim()).length() > 0 ) + SenderAID.setName(param);*/ + // check if SenderAID has a guid. SenderAID is surely not null here + if (SenderAID.getName().length() > 0) + msg.setSender(SenderAID); + + Enumeration rec_Enum = receiverListPanel.getContent(); + while (rec_Enum.hasMoreElements()) + msg.addReceiver((AID) rec_Enum.nextElement()); + + Enumeration replyTo_Enum = replyToListPanel.getContent(); + while (replyTo_Enum.hasMoreElements()) + msg.addReplyTo((AID) replyTo_Enum.nextElement()); + + Properties user_Prop = propertiesListPanel.getContentProperties(); + Enumeration keys = user_Prop.propertyNames(); + while (keys.hasMoreElements()) { + String k = (String) keys.nextElement(); + msg.addUserDefinedParameter(k, user_Prop.getProperty(k)); + } + + param = replyWith.getText().trim(); + if (param.length() > 0) + msg.setReplyWith(param); + + param = inReplyTo.getText().trim(); + if (param.length() > 0) + msg.setInReplyTo(param); + + param = conversationId.getText().trim(); + if (param.length() > 0) + msg.setConversationId(param); + + param = replyBy.getText().trim(); + try { + msg.setReplyByDate(ISO8601.toDate(param)); + } catch (Exception ignored) { + } + + if (!Objects.equals(param = (String) protocol.getSelectedItem(), "Null")) + msg.setProtocol(param); + + param = language.getText().trim(); + if (param.length() > 0) + msg.setLanguage(param); + + param = ontology.getText().trim(); + if (param.length() > 0) + msg.setOntology(param); + + param = content.getText().trim(); + if (param.length() > 0) + msg.setContent(param); + + param = (encoding.getText()).trim(); + if (param.length() > 0) + msg.setEncoding(param); + + Envelope env = new Envelope(); + + Enumeration to_Enum = toPanel.getContent(); + while (to_Enum.hasMoreElements()) + env.addTo((AID) to_Enum.nextElement()); + + if (newAIDFrom != null) + fromAID = newAIDFrom; + if (fromAID.getName().length() > 0) + env.setFrom(fromAID); + + param = comments.getText().trim(); + if (param.length() > 0) + env.setComments(param); - try { - param = envelope.getAclRepresentation(); - } catch (NullPointerException e1) { - param = ""; - } - representation.setText(param); + param = representation.getText().trim(); + if (param.length() > 0) + env.setAclRepresentation(param); try { - param = envelope.getPayloadLength().toString(); - } catch (NullPointerException e1) { - param = "-1"; + param = payloadLength.getText().trim(); + env.setPayloadLength(Long.parseLong(param)); + } catch (Exception e) { + //System.err.println("Incorrect int format. payloadLength must be an integer. Automatic reset to -1."); + //env.setPayloadLength(new Long(-1)); + //payloadLength.setText("-1"); } - payloadLength.setText(param); - try { - param = envelope.getPayloadEncoding(); - } catch (NullPointerException e1) { - param = ""; - } - payloadEncoding.setText(param); + param = payloadEncoding.getText().trim(); + if (param.length() > 0) + env.setPayloadEncoding(param); - //Date - dateDate = envelope.getDate(); + //setDate require a Date not a String if (dateDate != null) - date.setText(ISO8601.toString(dateDate)); - else - date.setText(""); + env.setDate(dateDate); - //#DOTNET_EXCLUDE_BEGIN - intendedReceiverPanel.resetContent(envelope.getAllIntendedReceiver()); - //#DOTNET_EXCLUDE_END + Enumeration int_Enum = intendedReceiverPanel.getContent(); + while (int_Enum.hasMoreElements()) + env.addIntendedReceiver((AID) int_Enum.nextElement()); - ReceivedObject recObject = envelope.getReceived(); - try { - param = recObject.getBy(); - } catch (NullPointerException e) { - param = ""; - } - by.setText(param); - try { - param = recObject.getFrom(); - } catch (NullPointerException e) { - param = ""; - } - fromRec.setText(param); - try { - dateRecDate = recObject.getDate(); - param = ISO8601.toString(dateRecDate); - } catch (NullPointerException e) { - param = ""; - } - dateRec.setText(param); + param = language.getText().trim(); + if (param.length() > 0) + msg.setLanguage(param); - try { - param = recObject.getId(); - } catch (NullPointerException e) { - param = ""; - } - id.setText(param); - try { - param = recObject.getVia(); - } catch (NullPointerException e) { - param = ""; - } - via.setText(param); + + /* ReceivedObject recObject = new ReceivedObject(); + boolean filled = false; + param = by.getText().trim(); + + if(param.length()>0) + { + filled = true; + recObject.setBy(param); + } + param = fromRec.getText().trim(); + if(param.length()>0) + { + filled = true; + recObject.setFrom(param); } - ///////////////////////////////////////////// - // MESSAGE GETTING and SETTING PUBLIC METHODS - ///////////////////////////////////////////// + if (dateRecDate != null) + { + filled = true; + recObject.setDate(dateRecDate); + } + + param = id.getText().trim(); + if(param.length()>0) + { + filled = true; + recObject.setId(param); + } + + param = via.getText().trim(); + if(param.length()>0) + { + filled = true; + recObject.setVia(param); + } + + if(filled) + env.setReceived(recObject); + */ + msg.setEnvelope(env); + return msg; + } /** * Displays the specified ACL message into the AclGui panel @@ -1177,322 +782,701 @@ else if (param.equals("") || param.equalsIgnoreCase("Null")) showEnvelope(envelope); - } + } + + + ///////////////////////// + // UTILITY PUBLIC METHODS + ///////////////////////// + + /** + * Enables/disables the editability of all the controls in an AclGui panel (default is enabled) + * + * @param enabledFlag If true enables editability + * @see AclGui#setSenderEnabled(boolean enabledFlag) + */ + public void setEnabled(boolean enabledFlag) { + guiEnabledFlag = enabledFlag; + updateEnabled(); + } + + /** + * Enables/disables the editability of the sender field of an AclGui panel (default is enabled) + * + * @param enabledFlag If true enables editability + * @see AclGui#setEnabled(boolean enabledFlag) + */ + public void setSenderEnabled(boolean enabledFlag) { + senderEnabledFlag = enabledFlag; + updateEnabled(); + } + + /** + Set the specified border to the AclGui panel + @param b Specifies the type of border + */ + /*public void setBorder(Border b) + { + if (aclPanel != null) + aclPanel.setBorder(b); + }*/ + + /** + * Paint the AclGui panel + */ + public void paint(Graphics g) { + if (firstPaintFlag) { + firstPaintFlag = false; + minDim = aclPanel.getSize(); + } else + aclPanel.setMinimumSize(minDim); + + super.paint(g); + } + + + ////////////////// + // STATIC METHODS + ////////////////// + + private class AclMessagePanel extends JPanel + //#DOTNET_EXCLUDE_BEGIN + implements DropTargetListener + //#DOTNET_EXCLUDE_END + { + AclMessagePanel() { + + JLabel l; + int i; + + // Initialize the Vector of interaction protocols + fipaProtocolArrayList = new ArrayList<>(); + + for (i = 0; i < N_FIPA_PROTOCOLS; ++i) + fipaProtocolArrayList.add(fipaProtocols[i]); + + aclPanel = new JPanel(); + + //#DOTNET_EXCLUDE_BEGIN + new DropTarget(aclPanel, this); + //#DOTNET_EXCLUDE_END + + aclPanel.setLayout(lm); + + formatGrid(20, // N of rows + 3, // N of columns + 5, // Right border + 5, // Left border + 5, // Top boredr + 5, // Bottom border + 2, // Space between columns + 2); // Space between rows + setGridColumnWidth(0, 115); + setGridColumnWidth(1, 40); + setGridColumnWidth(2, 170); + + + // Sender (line # 0) + l = new JLabel("Sender:"); + //#DOTNET_EXCLUDE_BEGIN + new DropTarget(l, this); + //#DOTNET_EXCLUDE_END + put(aclPanel, l, 0, 0, 1, 1, false); + senderEnabledFlag = true; // The sender field is enabled by default, but can be disabled with the setSenderEnabled() method. + sender = new JTextField(); + sender.setPreferredSize(new Dimension(80, 26)); + sender.setMinimumSize(new Dimension(80, 26)); + sender.setMaximumSize(new Dimension(80, 26)); + sender.setEditable(false); + sender.setBackground(Color.white); + senderButton = new JButton("Set"); + senderButton.setMargin(new Insets(2, 3, 2, 3)); + + put(aclPanel, senderButton, 1, 0, 1, 1, false); + put(aclPanel, sender, 2, 0, 1, 1, false); + + senderButton.addActionListener(e -> { + String command = e.getActionCommand(); + AIDGui guiSender = new AIDGui(getChildrenOwner()); + + if (command.equals("Set")) { + AID senderToView = SenderAID; + //another sender was already inserted. + if (newAIDSender != null) + senderToView = newAIDSender; + senderToView = guiSender.ShowAIDGui(senderToView, true, true); + //if the cancel button was clicked --> maintain the old value inserted. + if (senderToView != null) { + newAIDSender = senderToView; + //the name can be different + sender.setText(newAIDSender.getName()); + } + } else if (command.equals("View")) + guiSender.ShowAIDGui(SenderAID, false, false); + + }); + // Receiver (line # 1) + l = new JLabel("Receivers:"); + //#DOTNET_EXCLUDE_BEGIN + new DropTarget(l, this); + //#DOTNET_EXCLUDE_END + put(aclPanel, l, 0, 1, 1, 1, false); + receiverListPanel = new VisualAIDList(Collections.emptyIterator(), getChildrenOwner()); + receiverListPanel.setDimension(new Dimension(205, 37)); + put(aclPanel, receiverListPanel, 1, 1, 2, 1, false); - /** - * Get the ACL message currently displayed by the AclGui panel - * - * @return The ACL message currently displayed by the AclGui panel as an ACLMessage object - * @see AclGui#setMsg(ACLMessage msg) - */ - public ACLMessage getMsg() { - String param; - param = (String) communicativeAct.getSelectedItem(); - int perf = ACLMessage.getInteger(param); - ACLMessage msg = new ACLMessage(perf); - if (newAIDSender != null) - SenderAID = newAIDSender; + //Reply-to (line #2) + l = new JLabel("Reply-to:"); + //#DOTNET_EXCLUDE_BEGIN + new DropTarget(l, this); + //#DOTNET_EXCLUDE_END + put(aclPanel, l, 0, 2, 1, 1, false); + replyToListPanel = new VisualAIDList(Collections.emptyIterator(), getChildrenOwner()); + replyToListPanel.setDimension(new Dimension(205, 37)); + put(aclPanel, replyToListPanel, 1, 2, 2, 1, false); - /*if ( ((param = sender.getText()).trim()).length() > 0 ) - SenderAID.setName(param);*/ - // check if SenderAID has a guid. SenderAID is surely not null here - if (SenderAID.getName().length() > 0) - msg.setSender(SenderAID); + // Communicative act (line # 3) + l = new JLabel("Communicative act:"); + //#DOTNET_EXCLUDE_BEGIN + new DropTarget(l, this); + //#DOTNET_EXCLUDE_END + put(aclPanel, l, 0, 3, 1, 1, false); + communicativeAct = new JComboBox<>(); - Enumeration rec_Enum = receiverListPanel.getContent(); - while (rec_Enum.hasMoreElements()) - msg.addReceiver((AID) rec_Enum.nextElement()); + String[] comm_Act = ACLMessage.getAllPerformativeNames(); + for (String s : comm_Act) + communicativeAct.addItem(s.toLowerCase()); - Enumeration replyTo_Enum = replyToListPanel.getContent(); - while (replyTo_Enum.hasMoreElements()) - msg.addReplyTo((AID) replyTo_Enum.nextElement()); + communicativeAct.setSelectedIndex(0); + put(aclPanel, communicativeAct, 1, 3, 2, 1, true); - Properties user_Prop = propertiesListPanel.getContentProperties(); - Enumeration keys = user_Prop.propertyNames(); - while (keys.hasMoreElements()) { - String k = (String) keys.nextElement(); - msg.addUserDefinedParameter(k, user_Prop.getProperty(k)); - } + // Content (line # 4-8) + l = new JLabel("Content:"); + //#DOTNET_EXCLUDE_BEGIN + new DropTarget(l, this); + //#DOTNET_EXCLUDE_END + put(aclPanel, l, 0, 4, 3, 1, false); + content = new JTextArea(5, TEXT_SIZE); + JScrollPane contentPane = new JScrollPane(); + contentPane.getViewport().setView(content); + put(aclPanel, contentPane, 0, 5, 3, 4, false); + contentPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); + contentPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); - param = replyWith.getText().trim(); - if (param.length() > 0) - msg.setReplyWith(param); + // Language (line # 9) + l = new JLabel("Language:"); + //#DOTNET_EXCLUDE_BEGIN + new DropTarget(l, this); + //#DOTNET_EXCLUDE_END + put(aclPanel, l, 0, 9, 1, 1, false); + language = new JTextField(); + language.setBackground(Color.white); + put(aclPanel, language, 1, 9, 2, 1, false); - param = inReplyTo.getText().trim(); - if (param.length() > 0) - msg.setInReplyTo(param); + //Encoding (line # 10) + l = new JLabel("Encoding:"); + //#DOTNET_EXCLUDE_BEGIN + new DropTarget(l, this); + //#DOTNET_EXCLUDE_END + put(aclPanel, l, 0, 10, 1, 1, false); + encoding = new JTextField(); + encoding.setBackground(Color.white); + put(aclPanel, encoding, 1, 10, 2, 1, false); - param = conversationId.getText().trim(); - if (param.length() > 0) - msg.setConversationId(param); + // Ontology (line # 11) + l = new JLabel("Ontology:"); + //#DOTNET_EXCLUDE_BEGIN + new DropTarget(l, this); + //#DOTNET_EXCLUDE_END + put(aclPanel, l, 0, 11, 1, 1, false); + ontology = new JTextField(); + ontology.setBackground(Color.white); + put(aclPanel, ontology, 1, 11, 2, 1, false); - param = replyBy.getText().trim(); - try { - msg.setReplyByDate(ISO8601.toDate(param)); - } catch (Exception ignored) { - } + // Protocol (line # 12) + l = new JLabel("Protocol:"); + //#DOTNET_EXCLUDE_BEGIN + new DropTarget(l, this); + //#DOTNET_EXCLUDE_END + put(aclPanel, l, 0, 12, 1, 1, false); + protocol = new JComboBox<>(); + for (i = 0; i < fipaProtocolArrayList.size(); ++i) + protocol.addItem(fipaProtocolArrayList.get(i)); + protocol.addItem(LABEL_TO_ADD_PROT); + protocol.addItem("Null"); + protocol.setSelectedItem("Null"); + lastSelectedIndex = protocol.getSelectedIndex(); + lastSelectedItem = (String) protocol.getSelectedItem(); + put(aclPanel, protocol, 1, 12, 2, 1, true); + protocol.addActionListener(e -> { + String param = (String) protocol.getSelectedItem(); - if (!Objects.equals(param = (String) protocol.getSelectedItem(), "Null")) - msg.setProtocol(param); + // BEFORE THE CURRENT SELECTION THE JComboBox WAS NON EDITABLE (a FIPA protocol or null was selected) + if (!protocol.isEditable()) { + // If a user defined protocol has just been selected --> set editable to true + if (!fipaProtocolArrayList.contains(param) && !Objects.equals(param, "Null")) { + protocol.setEditable(true); + } + } + // BEFORE THE CURRENT SELECTION THE JComboBox WAS EDITABLE (an editable protocol was selected) + else { + // The user selected a FIPA protocol or null (he didn't perform any editing operation) + if (fipaProtocolArrayList.contains(param) || Objects.equals(param, "Null")) { + protocol.setEditable(false); + protocol.setSelectedItem(param); + } + // The user selected the label to add a new protocol (he didn't perform any editing operation) + else if (param.equals(LABEL_TO_ADD_PROT)) { + protocol.setSelectedItem(param); + } + // The user added a new protocol + else if (lastSelectedItem.equals(LABEL_TO_ADD_PROT)) { + // The new protocol is actually added only if it is != "" and is not already present + if (!param.equals("")) { + protocol.addItem(param); + int cnt = protocol.getItemCount(); + protocol.setSelectedItem(param); + int n = protocol.getSelectedIndex(); + if (n != cnt - 1) + protocol.removeItemAt(cnt - 1); + } else { + protocol.setEditable(false); + protocol.setSelectedItem("Null"); + } + } + // The user modified/deleted a previously added user defined protocol + else if (!lastSelectedItem.equals(LABEL_TO_ADD_PROT)) { + protocol.removeItemAt(lastSelectedIndex); // The old protocol is removed + if (param.equals("")) // Deletion + { + protocol.setEditable(false); + protocol.setSelectedItem("Null"); + } else // Modification + { + protocol.addItem(param); + protocol.setSelectedItem(param); + } + } + } - param = language.getText().trim(); - if (param.length() > 0) - msg.setLanguage(param); + lastSelectedIndex = protocol.getSelectedIndex(); + lastSelectedItem = (String) protocol.getSelectedItem(); + }); - param = ontology.getText().trim(); - if (param.length() > 0) - msg.setOntology(param); + // Conversation-id (line # 13) + l = new JLabel("Conversation-id:"); + //#DOTNET_EXCLUDE_BEGIN + new DropTarget(l, this); + //#DOTNET_EXCLUDE_END + put(aclPanel, l, 0, 13, 1, 1, false); + conversationId = new JTextField(); + conversationId.setBackground(Color.white); + put(aclPanel, conversationId, 1, 13, 2, 1, false); - param = content.getText().trim(); - if (param.length() > 0) - msg.setContent(param); + // In-reply-to (line # 14) + l = new JLabel("In-reply-to:"); + //#DOTNET_EXCLUDE_BEGIN + new DropTarget(l, this); + //#DOTNET_EXCLUDE_END + put(aclPanel, l, 0, 14, 1, 1, false); + inReplyTo = new JTextField(); + inReplyTo.setBackground(Color.white); + put(aclPanel, inReplyTo, 1, 14, 2, 1, false); - param = (encoding.getText()).trim(); - if (param.length() > 0) - msg.setEncoding(param); + // Reply-with (line # 15) + l = new JLabel("Reply-with:"); + //#DOTNET_EXCLUDE_BEGIN + new DropTarget(l, this); + //#DOTNET_EXCLUDE_END + put(aclPanel, l, 0, 15, 1, 1, false); + replyWith = new JTextField(); + replyWith.setBackground(Color.white); + put(aclPanel, replyWith, 1, 15, 2, 1, false); - Envelope env = new Envelope(); + // Reply-by (line # 16) + replyByDate = null; + l = new JLabel("Reply-by:"); + //#DOTNET_EXCLUDE_BEGIN + new DropTarget(l, this); + //#DOTNET_EXCLUDE_END + put(aclPanel, l, 0, 16, 1, 1, false); + replyBySet = new JButton("Set"); + replyBySet.setMargin(new Insets(2, 3, 2, 3)); + replyBy = new JTextField(); + replyBy.setBackground(Color.white); + put(aclPanel, replyBySet, 1, 16, 1, 1, false); + put(aclPanel, replyBy, 2, 16, 1, 1, false); + // BEGIN anonumous class +// END actionPerformed(ActionEvent e) + replyBySet.addActionListener(e -> { + String command = e.getActionCommand(); + //TimeChooser t = new TimeChooser(replyByDate); + TimeChooser t = new TimeChooser(); + String d = replyBy.getText(); + if (!d.equals("")) { + try { + t.setDate(ISO8601.toDate(d)); + } catch (Exception ee) { + if (logger.isLoggable(Logger.SEVERE)) + logger.log(Logger.WARNING, "Incorrect date format"); + } + } + if (command.equals("Set")) { + if (t.showEditTimeDlg(null) == TimeChooser.OK) { + replyByDate = t.getDate(); + if (replyByDate == null) + replyBy.setText(""); + else + replyBy.setText(ISO8601.toString(replyByDate)); + } + } else if (command.equals("View")) { + t.showViewTimeDlg(null); + } + } // END anonymous class + ); - Enumeration to_Enum = toPanel.getContent(); - while (to_Enum.hasMoreElements()) - env.addTo((AID) to_Enum.nextElement()); - if (newAIDFrom != null) - fromAID = newAIDFrom; - if (fromAID.getName().length() > 0) - env.setFrom(fromAID); + //Properties (line #17) + l = new JLabel("User Properties:"); + //#DOTNET_EXCLUDE_BEGIN + new DropTarget(l, this); + //#DOTNET_EXCLUDE_END + put(aclPanel, l, 0, 17, 1, 1, false); + propertiesListPanel = new VisualPropertiesList(new Properties(), getChildrenOwner()); + propertiesListPanel.setDimension(new Dimension(205, 37)); + put(aclPanel, propertiesListPanel, 1, 17, 2, 1, false); - param = comments.getText().trim(); - if (param.length() > 0) - env.setComments(param); + setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); + add(aclPanel); - param = representation.getText().trim(); - if (param.length() > 0) - env.setAclRepresentation(param); + } // END AclMessagePanel() - try { - param = payloadLength.getText().trim(); - env.setPayloadLength(Long.parseLong(param)); - } catch (Exception e) { - //System.err.println("Incorrect int format. payloadLength must be an integer. Automatic reset to -1."); - //env.setPayloadLength(new Long(-1)); - //payloadLength.setText("-1"); + //#DOTNET_EXCLUDE_BEGIN + public void dragOver(DropTargetDragEvent p1) { + if (logger.isLoggable(Logger.FINEST)) + logger.log(Logger.FINEST, "dragOver"); } - param = payloadEncoding.getText().trim(); - if (param.length() > 0) - env.setPayloadEncoding(param); + public void dropActionChanged(DropTargetDragEvent p1) { + if (logger.isLoggable(Logger.FINEST)) + logger.log(Logger.FINEST, "dropActionChanged"); + } - //setDate require a Date not a String - if (dateDate != null) - env.setDate(dateDate); + public void dragEnter(DropTargetDragEvent dragEvent) { + if (logger.isLoggable(Logger.FINEST)) + logger.log(Logger.FINEST, "dragEnter"); + } - Enumeration int_Enum = intendedReceiverPanel.getContent(); - while (int_Enum.hasMoreElements()) - env.addIntendedReceiver((AID) int_Enum.nextElement()); + public void dragExit(DropTargetEvent p1) { + if (logger.isLoggable(Logger.FINEST)) + logger.log(Logger.FINEST, "dragExit"); + } + public void drop(DropTargetDropEvent dropEvent) { + boolean completionStatus = false; + List fileList = null; - param = language.getText().trim(); - if (param.length() > 0) - msg.setLanguage(param); + try { + dropEvent.acceptDrop(DnDConstants.ACTION_COPY); + Transferable xferInfo = dropEvent.getTransferable(); + fileList = (List) xferInfo.getTransferData(DataFlavor.javaFileListFlavor); + completionStatus = true; + } catch (UnsupportedFlavorException exc) { + completionStatus = false; + } catch (IOException exc) { + if (logger.isLoggable(Logger.WARNING)) + logger.log(Logger.WARNING, "DragAndDrop operation failed: " + exc); + completionStatus = false; + } finally { + dropEvent.dropComplete(completionStatus); + } - /* ReceivedObject recObject = new ReceivedObject(); - boolean filled = false; - param = by.getText().trim(); + if (fileList != null) { + Iterator fileItor = fileList.iterator(); + ACLParser aclParser = ACLParser.create(); + while (fileItor.hasNext()) { + try { + File f = (File) (fileItor.next()); + FileReader aclMsgFile = new FileReader(f); + Enumeration receivers = receiverListPanel.getContent(); + setMsg(aclParser.parse(aclMsgFile)); + if (receivers.hasMoreElements()) { + if (logger.isLoggable(Logger.FINE)) + logger.log(Logger.FINE, "revert to saved list"); + ArrayList list = new ArrayList<>(); + while (receivers.hasMoreElements()) { + list.add(receivers.nextElement()); + } + receiverListPanel.resetContent(list.iterator()); + } + } catch (Throwable exc) { + if (logger.isLoggable(Logger.WARNING)) + logger.log(Logger.WARNING, "DragAndDrop operation failed: " + exc); + } + } //~ while (fileItor.hasNext()) + } //~ if (selectedItems != null) - if(param.length()>0) - { - filled = true; - recObject.setBy(param); - } - param = fromRec.getText().trim(); - if(param.length()>0) - { - filled = true; - recObject.setFrom(param); - } + } // END drop(dropEvent) + //#DOTNET_EXCLUDE_END - if (dateRecDate != null) - { - filled = true; - recObject.setDate(dateRecDate); - } + } // END class AclMessagePanel - param = id.getText().trim(); - if(param.length()>0) - { - filled = true; - recObject.setId(param); - } + //this private class build a panel to show the envelope field of an ACLMessage + private class EnvelopePanel extends JPanel { + EnvelopePanel() { - param = via.getText().trim(); - if(param.length()>0) - { - filled = true; - recObject.setVia(param); - } + JLabel l; + int i; - if(filled) - env.setReceived(recObject); - */ - msg.setEnvelope(env); - return msg; - } + //minDim = new Dimension(); + aclPanel = new JPanel(); + //aclPanel.setBackground(Color.lightGray); + aclPanel.setLayout(lm); + formatGrid(20, // N of rows + 3, // N of columns + 5, // Right border + 5, // Left border + 5, // Top boredr + 5, // Bottom border + 2, // Space between columns + 2); // Space between rows + setGridColumnWidth(0, 115); + setGridColumnWidth(1, 40); + setGridColumnWidth(2, 170); - ///////////////////////// - // UTILITY PUBLIC METHODS - ///////////////////////// + // To (line # 0) + l = new JLabel("To:"); + put(aclPanel, l, 0, 0, 1, 1, false); + toPanel = new VisualAIDList(Collections.emptyIterator(), getChildrenOwner()); + toPanel.setDimension(new Dimension(205, 37)); + put(aclPanel, toPanel, 1, 0, 2, 1, false); - /** - * Enables/disables the editability of all the controls in an AclGui panel (default is enabled) - * - * @param enabledFlag If true enables editability - * @see AclGui#setSenderEnabled(boolean enabledFlag) - */ - public void setEnabled(boolean enabledFlag) { - guiEnabledFlag = enabledFlag; - updateEnabled(); - } + //From (line #1) + l = new JLabel("From:"); + put(aclPanel, l, 0, 1, 1, 1, false); + fromButton = new JButton("Set"); + fromButton.setMargin(new Insets(2, 3, 2, 3)); + put(aclPanel, fromButton, 1, 1, 1, 1, false); + from = new JTextField(); + from.setEditable(false); + from.setBackground(Color.white); + put(aclPanel, from, 2, 1, 1, 1, false); + fromButton.addActionListener(e -> { + String command = e.getActionCommand(); + AIDGui guiFrom = new AIDGui(ownerGui); + if (command.equals("Set")) { + AID fromToView = fromAID; + if (newAIDFrom != null) + fromToView = newAIDFrom; + fromToView = guiFrom.ShowAIDGui(fromToView, true, true); + if (fromToView != null) { + newAIDFrom = fromToView; + from.setText(newAIDFrom.getName()); + } + } else { + if (command.equals("View")) + guiFrom.ShowAIDGui(fromAID, false, false); + } + }); - /** - * Enables/disables the editability of the sender field of an AclGui panel (default is enabled) - * - * @param enabledFlag If true enables editability - * @see AclGui#setEnabled(boolean enabledFlag) - */ - public void setSenderEnabled(boolean enabledFlag) { - senderEnabledFlag = enabledFlag; - updateEnabled(); - } + //Comments (line # 2-6) + l = new JLabel("Comments:"); + put(aclPanel, l, 0, 2, 1, 1, false); + comments = new JTextArea(4, TEXT_SIZE); + JScrollPane commentsPane = new JScrollPane(); + commentsPane.getViewport().setView(comments); + put(aclPanel, commentsPane, 0, 3, 3, 4, false); + commentsPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); + commentsPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); - /** - Set the specified border to the AclGui panel - @param b Specifies the type of border - */ - /*public void setBorder(Border b) - { - if (aclPanel != null) - aclPanel.setBorder(b); - }*/ + //aclRappresentation (line # 7) + l = new JLabel("ACLRepresentation:"); + put(aclPanel, l, 0, 7, 1, 1, false); + representation = new JTextField(); + representation.setBackground(Color.white); + put(aclPanel, representation, 1, 7, 2, 1, false); - /** - * Paint the AclGui panel - */ - public void paint(Graphics g) { - if (firstPaintFlag) { - firstPaintFlag = false; - minDim = aclPanel.getSize(); - } else - aclPanel.setMinimumSize(minDim); + //payloadLength (line # 8) + l = new JLabel("Payload Length:"); + put(aclPanel, l, 0, 8, 1, 1, false); + payloadLength = new JTextField(); + payloadLength.setBackground(Color.white); + put(aclPanel, payloadLength, 1, 8, 2, 1, false); - super.paint(g); - } + //payloadEncoding (line # 9) + l = new JLabel("Payload Encoding:"); + put(aclPanel, l, 0, 9, 1, 1, false); + payloadEncoding = new JTextField(); + payloadEncoding.setBackground(Color.white); + put(aclPanel, payloadEncoding, 1, 9, 2, 1, false); + //Date (line # 10) + dateDate = null; + l = new JLabel("Date:"); + put(aclPanel, l, 0, 10, 1, 1, false); + dateButton = new JButton("Set"); + dateButton.setMargin(new Insets(2, 3, 2, 3)); + date = new JTextField(); + date.setBackground(Color.white); + put(aclPanel, dateButton, 1, 10, 1, 1, false); + put(aclPanel, date, 2, 10, 1, 1, false); + dateButton.addActionListener(e -> { + String command = e.getActionCommand(); + //TimeChooser t = new TimeChooser(replyByDate); + TimeChooser t = new TimeChooser(); + String d = date.getText(); + if (!d.equals("")) { + try { + t.setDate(ISO8601.toDate(d)); + } catch (Exception ee) { + if (logger.isLoggable(Logger.WARNING)) + logger.log(Logger.WARNING, "Incorrect date format"); + } + } + if (command.equals("Set")) { + if (t.showEditTimeDlg(null) == TimeChooser.OK) { + dateDate = t.getDate(); + if (dateDate == null) + date.setText(""); + else + date.setText(ISO8601.toString(dateDate)); + } + } else if (command.equals("View")) { + t.showViewTimeDlg(null); + } + }); - ////////////////// - // STATIC METHODS - ////////////////// + //intendedReceiver (line #11) + l = new JLabel("Intended Receiver:"); + put(aclPanel, l, 0, 11, 1, 1, false); + intendedReceiverPanel = new VisualAIDList(Collections.emptyIterator(), getChildrenOwner()); + intendedReceiverPanel.setDimension(new Dimension(205, 37)); + put(aclPanel, intendedReceiverPanel, 1, 11, 2, 1, false); - /** - * Pops up a dialog window including an editing-disabled AclGui panel and displays the specified - * ACL message in it. - * - * @param msg The ACL message to be displayed - * @param parent The parent window of the dialog window - * @see AclGui#editMsgInDialog(ACLMessage msg, Frame parent) - */ - public static void showMsgInDialog(ACLMessage msg, Frame parent) { - final JDialog tempAclDlg = new JDialog(parent, "ACL Message", true); + //ReceivedObject (line #12-15) + JPanel recPanel = new JPanel(); + recPanel.setLayout(new BoxLayout(recPanel, BoxLayout.Y_AXIS)); + JPanel tempPane = new JPanel(); + tempPane.setLayout(new BoxLayout(tempPane, BoxLayout.X_AXIS)); + recPanel.setBorder(new TitledBorder("Received Object")); + l = new JLabel("By:"); + l.setPreferredSize(new Dimension(115, 24)); + l.setMinimumSize(new Dimension(115, 24)); + l.setMaximumSize(new Dimension(115, 24)); + tempPane.add(l); + by = new JTextField(); + by.setBackground(Color.white); + tempPane.add(by); + recPanel.add(tempPane); + tempPane = new JPanel(); + tempPane.setLayout(new BoxLayout(tempPane, BoxLayout.X_AXIS)); - AclGui aclPanel = new AclGui(parent); - //aclPanel.setBorder(new BevelBorder(BevelBorder.RAISED)); - aclPanel.setEnabled(false); - aclPanel.setMsg(msg); + l = new JLabel("From:"); + l.setPreferredSize(new Dimension(115, 24)); + l.setMinimumSize(new Dimension(115, 24)); + l.setMaximumSize(new Dimension(115, 24)); + tempPane.add(l); + fromRec = new JTextField(); + fromRec.setBackground(Color.white); + tempPane.add(fromRec); + recPanel.add(tempPane); - JButton okButton = new JButton("OK"); - JPanel buttonPanel = new JPanel(); - // Use default (FlowLayout) layout manager to dispose the OK button - buttonPanel.add(okButton); + tempPane = new JPanel(); + tempPane.setLayout(new BoxLayout(tempPane, BoxLayout.X_AXIS)); - tempAclDlg.getContentPane().setLayout(new BorderLayout()); - tempAclDlg.getContentPane().add("Center", aclPanel); - tempAclDlg.getContentPane().add("South", buttonPanel); + dateRecDate = null; + l = new JLabel("Date:"); + l.setPreferredSize(new Dimension(115, 24)); + l.setMinimumSize(new Dimension(115, 24)); + l.setMaximumSize(new Dimension(115, 24)); + tempPane.add(l); + dateRecButton = new JButton("Set"); + tempPane.add(dateRecButton); + dateRecButton.addActionListener(e -> { + String command = e.getActionCommand(); + //TimeChooser t = new TimeChooser(replyByDate); + TimeChooser t = new TimeChooser(); + String d = dateRec.getText(); + if (!d.equals("")) { + try { + t.setDate(ISO8601.toDate(d)); + } catch (Exception ee) { + if (logger.isLoggable(Logger.WARNING)) + logger.log(Logger.WARNING, "Incorrect date format"); + } + } + if (command.equals("Set")) { + if (t.showEditTimeDlg(null) == TimeChooser.OK) { + dateRecDate = t.getDate(); + if (dateRecDate == null) + dateRec.setText(""); + else + dateRec.setText(ISO8601.toString(dateRecDate)); + } + } else if (command.equals("View")) { + t.showViewTimeDlg(null); + } + }); - okButton.addActionListener(e -> tempAclDlg.dispose()); + dateRec = new JTextField(); + dateRec.setBackground(Color.white); + tempPane.add(dateRec); + recPanel.add(tempPane); - tempAclDlg.pack(); - tempAclDlg.setResizable(false); - if (parent != null) { - int locx = parent.getX() + (parent.getWidth() - tempAclDlg.getWidth()) / 2; - if (locx < 0) - locx = 0; - int locy = parent.getY() + (parent.getHeight() - tempAclDlg.getHeight()) / 2; - if (locy < 0) - locy = 0; - tempAclDlg.setLocation(locx, locy); - } - tempAclDlg.setVisible(true); - } + tempPane = new JPanel(); + tempPane.setLayout(new BoxLayout(tempPane, BoxLayout.X_AXIS)); - /** - * Pops up a dialog window including an editing-enabled AclGui panel and displays the specified - * ACL message in it. The dialog window also includes an OK and a Cancel button to accept or - * discard the performed editing. - * - * @param msg The ACL message to be initially displayed - * @param parent The parent window of the dialog window - * @return The ACL message displayed in the dialog window or null depending on whether the user close the window - * by clicking the OK or Cancel button - * @see AclGui#showMsgInDialog(ACLMessage msg, Frame parent) - */ - public static ACLMessage editMsgInDialog(ACLMessage msg, Frame parent) { - final JDialog tempAclDlg = new JDialog(parent, "ACL Message", true); - final AclGui aclPanel = new AclGui(parent); - aclPanel.setBorder(new BevelBorder(BevelBorder.RAISED)); - aclPanel.setSenderEnabled(true); - aclPanel.setMsg(msg); + l = new JLabel("ID:"); + l.setPreferredSize(new Dimension(115, 24)); + l.setMinimumSize(new Dimension(115, 24)); + l.setMaximumSize(new Dimension(115, 24)); + tempPane.add(l); + id = new JTextField(); + id.setBackground(Color.white); + tempPane.add(id); + recPanel.add(tempPane); - JButton okButton = new JButton("OK"); - JButton cancelButton = new JButton("Cancel"); - okButton.setPreferredSize(cancelButton.getPreferredSize()); - JPanel buttonPanel = new JPanel(); - // Use default (FlowLayout) layout manager to dispose the OK and Cancel buttons - buttonPanel.add(okButton); - buttonPanel.add(cancelButton); + tempPane = new JPanel(); + tempPane.setLayout(new BoxLayout(tempPane, BoxLayout.X_AXIS)); - tempAclDlg.getContentPane().setLayout(new BorderLayout()); - tempAclDlg.getContentPane().add("Center", aclPanel); - tempAclDlg.getContentPane().add("South", buttonPanel); + l = new JLabel("Via:"); + l.setPreferredSize(new Dimension(115, 24)); + l.setMinimumSize(new Dimension(115, 24)); + l.setMaximumSize(new Dimension(115, 24)); + tempPane.add(l); + via = new JTextField(); + via.setBackground(Color.white); + tempPane.add(via); + recPanel.add(tempPane); - okButton.addActionListener(e -> { - editedMsg = aclPanel.getMsg(); - tempAclDlg.dispose(); - }); - cancelButton.addActionListener(e -> { - editedMsg = null; - tempAclDlg.dispose(); - }); + put(aclPanel, recPanel, 0, 12, 3, 1, false); - tempAclDlg.pack(); - tempAclDlg.setResizable(false); + //(line 17) + JPanel tmpPanel = new JPanel(); + //tmpPanel.setBackground(Color.lightGray); + defaultEnvelopeButton = new JButton("Set Default Envelope"); + tmpPanel.add(defaultEnvelopeButton); - if (parent != null) { - int x = parent.getX() + (parent.getWidth() - tempAclDlg.getWidth()) / 2; - int y = parent.getY() + (parent.getHeight() - tempAclDlg.getHeight()) / 2; - tempAclDlg.setLocation(Math.max(x, 0), Math.max(y, 0)); - } + defaultEnvelopeButton.addActionListener(e -> { + String command = e.getActionCommand(); + if (command.equals("Set Default Envelope")) { + ACLMessage tmp = getMsg(); + tmp.setDefaultEnvelope(); + Envelope envtmp = tmp.getEnvelope(); + showEnvelope(envtmp); + } + }); + put(aclPanel, tmpPanel, 0, 17, 3, 1, false); + //setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); + add(aclPanel); - tempAclDlg.setVisible(true); - ACLMessage m = null; - if (editedMsg != null) - m = (ACLMessage) editedMsg.clone(); + } - return m; } /*public static void main(String[] args) diff --git a/src/jade/gui/AgentTree.java b/src/jade/gui/AgentTree.java index 06fb9de..a375907 100644 --- a/src/jade/gui/AgentTree.java +++ b/src/jade/gui/AgentTree.java @@ -59,448 +59,468 @@ public class AgentTree extends JPanel { public static final String DAFAULT_LOCAL_PLATFORM_NAME = "ThisPlatform"; public static final String REMOTE_PLATFORMS_FOLDER_NAME = "RemotePlatforms"; public static final String FROZEN_AGENTS_FOLDER_NAME = "Frozen Agents"; - - public JTree tree; private final Map mapDescriptor; + public JTree tree; private String localPlatformName = DAFAULT_LOCAL_PLATFORM_NAME; - /** - * Inner class Node - * Common base class for all AgentTree nodes - */ - public abstract class Node extends DefaultMutableTreeNode { - - protected Icon img; - protected String name; - protected String state; - protected String ownership; - protected boolean greyOut = false; - - public Node(String name) { - this.name = name; - } - - public Icon getIcon(String typeAgent) { - Image image = getToolkit().getImage(getClass().getResource(getIconAgent(typeAgent))); - if (greyOut) { - ImageFilter colorfilter = new MyFilterImage(); - Image imageFiltered = createImage(new FilteredImageSource(image.getSource(), colorfilter)); - return new ImageIcon(imageFiltered); - } else - return new ImageIcon(image); - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getState() { - return state != null ? state : ""; - } - - public void setState(String state) { - this.state = state; - } - - public String getOwnership() { - return ownership != null ? ownership : ""; - } - - public void setOwnership(String ownership) { - this.ownership = ownership; - } - - public void changeIcon(String agentState) { - if (agentState.equalsIgnoreCase("suspended")) { - greyOut = true; - setType(AGENT_TYPE); - } else if (agentState.equalsIgnoreCase("active")) { - greyOut = false; - setType(AGENT_TYPE); - } else if (agentState.equalsIgnoreCase("frozen")) { - greyOut = false; - setType(FROZEN_AGENT_TYPE); - } - } - - public abstract String getType(); - - public abstract void setType(String type); - - public abstract String getToolTipText(); - - public String toString() { - return (getType() != null ? getType() + "-" + name : name); - } - - public int compareTo(Node n) { - return name.compareTo(n.getName()); - } - } // END of inner class Node - - - /** - * Inner class AgentNode - */ - public class AgentNode extends Node { - private String agentType; - private String agentAddress; - - public AgentNode(String name) { - super(name); - agentType = AGENT_TYPE; - } - - public String getAddress() { - return agentAddress; - } - - public void setAddress(String address) { - agentAddress = address; - } - - public void setType(String type) { - agentType = type; - } - - public String getType() { - return agentType; - } - - public String getToolTipText() { - return ("Local Agent"); - } - } // END of inner class AgentNode - - - /** - * Inner class ContainerNode - */ - public class ContainerNode extends Node { - private InetAddress addressmachine; - private String containerType; + public AgentTree() { + this(null); + } - public ContainerNode(String name) { - super(name); - containerType = CONTAINER_TYPE; - } - public void setAddress(InetAddress addr) { - addressmachine = addr; - } + public AgentTree(Font f) { + mapDescriptor = new HashMap<>(); + register(TREE_ROOT_TYPE, null, "images/folderyellow.gif"); + register(LOCAL_PLATFORM_TYPE, null, "images/folderyellow.gif"); + register(CONTAINER_TYPE, null, "images/foldergreen.gif"); + register(AGENT_TYPE, null, "images/runtree.gif"); - public void setType(String type) { - containerType = type; - } + register(FROZEN_CONTAINER_TYPE, null, "images/frozenagents.gif"); + register(FROZEN_AGENT_TYPE, null, "images/freezeagent.gif"); - public String getType() { - return containerType; - } + register(REMOTE_PLATFORMS_FOLDER_TYPE, null, "images/folderblue.gif"); + register(REMOTE_PLATFORM_TYPE, null, "images/folderlightblue.gif"); + register(REMOTE_AGENT_TYPE, null, "images/runtree.gif"); - public String getToolTipText() { - if (addressmachine != null) - return name + " " + "[" + addressmachine.getHostAddress() + "]"; - else - return name + " " + "[???:???:???:???]"; + tree = new JTree(); + if (f != null) { + tree.setFont(f); } - } // END of inner class ContainerNode - - - /** - * Inner class SuperContainer - */ - public class SuperContainer extends Node { + tree.setModel(new AgentTreeModel(new SuperContainer(TREE_ROOT_NAME))); + tree.setLargeModel(false); + tree.getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION); - public SuperContainer(String name) { - super(name); - } + // Add localPlatform folder. + AgentTreeModel model = getModel(); + MutableTreeNode root = (MutableTreeNode) model.getRoot(); + LocalPlatformFolderNode localAP = new LocalPlatformFolderNode(localPlatformName); + model.insertNodeInto(localAP, root, root.getChildCount()); - public String getToolTipText() { - return ("Java Agent DEvelopment Framework"); - } + ToolTipManager.sharedInstance().registerComponent(tree); + tree.setShowsRootHandles(true); + tree.setCellRenderer(new TreeIconRenderer()); + tree.setRowHeight(0); - public String getType() { - return TREE_ROOT_TYPE; - } + tree.addMouseListener(new AgentTreePopupManager(this)); + } - public void setType(String noType) { - } - } // END of inner class SuperContainer + public AgentNode createAgentNode(String name) { + return new AgentNode(name); + } + public ContainerNode createContainerNode(String name) { + return new ContainerNode(name); + } /** - * Inner class RemotePlatformsFolderNode + * @deprecated Use createAgentNode() and createContainerNode() instead */ - public class RemotePlatformsFolderNode extends Node { - - public RemotePlatformsFolderNode(String name) { - super(name); - } - - public String getToolTipText() { - return ("List of RemotePlatforms"); - } - - public void setType(String noType) { - } + public Node createNewNode(String name, int i) { + return switch (i) { + case 0 -> new ContainerNode(name); + case 1 -> new AgentNode(name); + default -> null; + }; + } - public String getType() { - return (REMOTE_PLATFORMS_FOLDER_TYPE); + public void refreshLocalPlatformName(String newName) { + String oldName = localPlatformName; + localPlatformName = newName; + AgentTreeModel model = getModel(); + MutableTreeNode root = (MutableTreeNode) model.getRoot(); + Enumeration children = root.children(); + while (children.hasMoreElements()) { + Node node = (Node) children.nextElement(); + String name = node.getName(); + if (name.equalsIgnoreCase(oldName)) { + node.setName(newName); + return; + } } - } // END of inner class RemotePlatformsFolderNode - - - /** - * Inner class localPlatformFolderNode - */ - public class LocalPlatformFolderNode extends Node { + } - public LocalPlatformFolderNode(String name) { - super(name); - } + public void clearLocalPlatform() { + AgentTreeModel model = getModel(); + MutableTreeNode root = (MutableTreeNode) model.getRoot(); + Enumeration folders = root.children(); + while (folders.hasMoreElements()) { + Node folderNode = (Node) folders.nextElement(); + String folderName = folderNode.getName(); + if (folderName.equalsIgnoreCase(localPlatformName)) { + Enumeration containers = folderNode.children(); + List toRemove = new LinkedList<>(); + while (containers.hasMoreElements()) { + Node container = (Node) containers.nextElement(); + toRemove.add(container); + } - public String getToolTipText() { - return ("Local JADE Platform"); + for (MutableTreeNode node : toRemove) { + model.removeNodeFromParent(node); + } + } } + } - public void setType(String noType) { - } + public void addContainerNode(String containerName, InetAddress addr) { + ContainerNode node = new ContainerNode(containerName); + node.setAddress(addr); - public String getType() { - return ("LOCALPLATFORM"); + AgentTreeModel model = getModel(); + MutableTreeNode root = (MutableTreeNode) model.getRoot(); + Enumeration folders = root.children(); + while (folders.hasMoreElements()) { + Node folderNode = (Node) folders.nextElement(); + String folderName = folderNode.getName(); + if (folderName.equalsIgnoreCase(localPlatformName)) { + model.insertNodeInto(node, folderNode, folderNode.getChildCount()); + return; + } } - } // END of inner class LocalPlatformFolderNode - + } /** - * Inner class RemotePlatformNode + * @deprecated Use addContainerNode(String, InetAddress) instead */ - public class RemotePlatformNode extends Node { - - private APDescription AP_Profile; - private AID amsAID; - - public RemotePlatformNode(String name) { - super(name); - } - - public String getToolTipText() { - return ("Remote Platform"); - } - - public void setType(String noType) { - } - - public String getType() { - return ("REMOTEPLATFORM"); - } - - public void setAPDescription(APDescription desc) { - AP_Profile = desc; - } - - public APDescription getAPDescription() { - return AP_Profile; - } - - public void setAmsAID(AID id) { - amsAID = id; - } - - public AID getAmsAID() { - return amsAID; + public void addContainerNode(ContainerNode node, String typeContainer, InetAddress addr) { + AgentTreeModel model = getModel(); + MutableTreeNode root = (MutableTreeNode) model.getRoot(); + node.setType(typeContainer); + Enumeration folders = root.children(); + while (folders.hasMoreElements()) { + Node folderNode = (Node) folders.nextElement(); + String folderName = folderNode.getName(); + if (folderName.equalsIgnoreCase(localPlatformName)) { + model.insertNodeInto(node, folderNode, folderNode.getChildCount()); + break; + } } - } // END of inner class RemotePlatformNode - - - /** - * Inner class RemoteAgentNode - */ - public class RemoteAgentNode extends AgentNode { - - private AMSAgentDescription amsd; + node.setAddress(addr); + } - public RemoteAgentNode(String name) { - super(name); + public void removeContainerNode(String nameNode) { + AgentTreeModel model = getModel(); + MutableTreeNode root = (MutableTreeNode) model.getRoot(); + Enumeration folders = root.children(); + while (folders.hasMoreElements()) { + Node folderNode = (Node) folders.nextElement(); + String folderName = folderNode.getName(); + if (folderName.equalsIgnoreCase(localPlatformName)) {//found the localplatform folder + Enumeration containers = folderNode.children(); + while (containers.hasMoreElements()) { + Node node = (Node) containers.nextElement(); + String nodeName = node.getName(); + if (nodeName.equalsIgnoreCase(nameNode)) { + model.removeNodeFromParent(node); + return; + } + } + } } + } - public String getToolTipText() { - return ("Remote Agent"); - } + //public void listenerTree(TreeSelectionListener panel) { + // tree.addTreeSelectionListener(panel); + //} - public void setType(String noType) { - } + public void addRemotePlatformsFolderNode() { + AgentTreeModel model = getModel(); + MutableTreeNode root = (MutableTreeNode) model.getRoot(); + Enumeration children = root.children(); - public String getType() { - return ("REMOTEAGENT"); - } + boolean existing = false; - public void setAMSDescription(AMSAgentDescription id) { - amsd = id; + while (children.hasMoreElements() & (!existing)) { + Node node = (Node) children.nextElement(); + String nodeName = node.getName(); + if (nodeName.equalsIgnoreCase(REMOTE_PLATFORMS_FOLDER_NAME)) + existing = true; } - public AMSAgentDescription getAMSDescription() { - return amsd; + if (!existing) { + RemotePlatformsFolderNode rpn = new RemotePlatformsFolderNode(REMOTE_PLATFORMS_FOLDER_NAME); + model.insertNodeInto(rpn, root, root.getChildCount()); } - } // END of inner class RemoteAgentNode - - public AgentTree() { - this(null); + return; } - public AgentTree(Font f) { - mapDescriptor = new HashMap<>(); - register(TREE_ROOT_TYPE, null, "images/folderyellow.gif"); - register(LOCAL_PLATFORM_TYPE, null, "images/folderyellow.gif"); - register(CONTAINER_TYPE, null, "images/foldergreen.gif"); - register(AGENT_TYPE, null, "images/runtree.gif"); - - register(FROZEN_CONTAINER_TYPE, null, "images/frozenagents.gif"); - register(FROZEN_AGENT_TYPE, null, "images/freezeagent.gif"); - - register(REMOTE_PLATFORMS_FOLDER_TYPE, null, "images/folderblue.gif"); - register(REMOTE_PLATFORM_TYPE, null, "images/folderlightblue.gif"); - register(REMOTE_AGENT_TYPE, null, "images/runtree.gif"); + public void addAgentNode(String agentName, String agentAddress, String containerName) { + addAgentNode(agentName, agentAddress, containerName, "Running", null); + } - tree = new JTree(); - if (f != null) { - tree.setFont(f); - } - tree.setModel(new AgentTreeModel(new SuperContainer(TREE_ROOT_NAME))); - tree.setLargeModel(false); - tree.getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION); + public void addAgentNode(String agentName, String agentAddress, String containerName, String agentState, String ownership) { + AgentNode node = new AgentNode(agentName); + node.setAddress(agentAddress); + node.setState(agentState); + node.setOwnership(ownership); - // Add localPlatform folder. AgentTreeModel model = getModel(); MutableTreeNode root = (MutableTreeNode) model.getRoot(); - LocalPlatformFolderNode localAP = new LocalPlatformFolderNode(localPlatformName); - model.insertNodeInto(localAP, root, root.getChildCount()); - ToolTipManager.sharedInstance().registerComponent(tree); - tree.setShowsRootHandles(true); - tree.setCellRenderer(new TreeIconRenderer()); - tree.setRowHeight(0); - - tree.addMouseListener(new AgentTreePopupManager(this)); + // Search for the folder of the local Platform + Enumeration folders = root.children(); + while (folders.hasMoreElements()) { + Node folderNode = (Node) folders.nextElement(); + String folderName = folderNode.getName(); + if (folderName.equalsIgnoreCase(localPlatformName)) { + // Search for the agent container 'containerName' + Enumeration containers = folderNode.children(); + while (containers.hasMoreElements()) { + Node containerNode = (Node) containers.nextElement(); + String contName = containerNode.getName(); + if (contName.equalsIgnoreCase(containerName)) { + // Add this new agent to this container and return + int position = getPosition(node, containerNode); + model.insertNodeInto(node, containerNode, position); + return; + } + } + } + } } - //public void listenerTree(TreeSelectionListener panel) { - // tree.addTreeSelectionListener(panel); - //} - - public AgentNode createAgentNode(String name) { - return new AgentNode(name); + private int getPosition(Node node, Node parentNode) { + int size = parentNode.getChildCount(); + if (size == 0) { + // This is the first child + return 0; + } else { + int k = node.compareTo((Node) parentNode.getChildAt(0)); + if (k < 0) { + // Insert new child at the beginning of the list + return 0; + } else { + k = node.compareTo((Node) parentNode.getChildAt(size - 1)); + if (k >= 0) { + // Insert new child at the end of the list + return size; + } else { + // Insert new child "somewhere" in the list + return getPosition(node, parentNode, 0, size - 1); + } + } + } } - public ContainerNode createContainerNode(String name) { - return new ContainerNode(name); + private int getPosition(Node node, Node parentNode, int down, int up) { + if ((up - down) == 1) { + return up; + } else { + int middle = (up + down) / 2; + int k = node.compareTo((Node) parentNode.getChildAt(middle)); + if (k == 0) { + return middle + 1; + } else if (k < 0) { + return getPosition(node, parentNode, down, middle); + } else { + return getPosition(node, parentNode, middle, up); + } + } } /** - * @deprecated Use createAgentNode() and createContainerNode() instead + * @deprecated Use addAgentNode(String, String, String) instead */ - public Node createNewNode(String name, int i) { - return switch (i) { - case 0 -> new ContainerNode(name); - case 1 -> new AgentNode(name); - default -> null; - }; - } - - public void refreshLocalPlatformName(String newName) { - String oldName = localPlatformName; - localPlatformName = newName; + public void addAgentNode(AgentNode node, String containerName, String agentName, String agentAddress, String agentType) { AgentTreeModel model = getModel(); MutableTreeNode root = (MutableTreeNode) model.getRoot(); - Enumeration children = root.children(); - while (children.hasMoreElements()) { - Node node = (Node) children.nextElement(); - String name = node.getName(); - if (name.equalsIgnoreCase(oldName)) { - node.setName(newName); - return; + node.setType(agentType); + node.setAddress(agentAddress); + node.setState("Running"); + //search for the folder of the local Platform + Enumeration folders = root.children(); + while (folders.hasMoreElements()) { + Node folderNode = (Node) folders.nextElement(); + String folderName = folderNode.getName(); + if (folderName.equalsIgnoreCase(localPlatformName)) { + // Search for the agent container 'containerName' + Enumeration containers = folderNode.children(); + while (containers.hasMoreElements()) { + Node container = (Node) containers.nextElement(); + String contName = container.getName(); + if (contName.equalsIgnoreCase(containerName)) { + // Add this new agent to this container and return + model.insertNodeInto(node, container, container.getChildCount()); + return; + } + } } } } - public void clearLocalPlatform() { + public void modifyAgentNode(String containerName, String agentName, String address, String state, String ownership) { AgentTreeModel model = getModel(); MutableTreeNode root = (MutableTreeNode) model.getRoot(); + //search for the folder of the local Platform Enumeration folders = root.children(); while (folders.hasMoreElements()) { Node folderNode = (Node) folders.nextElement(); String folderName = folderNode.getName(); if (folderName.equalsIgnoreCase(localPlatformName)) { + // Search for the agent container 'containerName' Enumeration containers = folderNode.children(); - List toRemove = new LinkedList<>(); while (containers.hasMoreElements()) { Node container = (Node) containers.nextElement(); - toRemove.add(container); + String contName = container.getName(); + if (contName.equalsIgnoreCase(containerName)) { + Enumeration agents = container.children(); + while (agents.hasMoreElements()) { + Node agent = (Node) agents.nextElement(); + + if (agent.getName().equalsIgnoreCase(agentName)) { + if (state != null) + agent.setState(state); + if (ownership != null) + agent.setOwnership(ownership); + agent.changeIcon(state); + model.nodeChanged(agent); + return; + } + } + } } + } + } + } - for (MutableTreeNode node : toRemove) { - model.removeNodeFromParent(node); + public void moveAgentNode(String fromContainerName, String toContainerName, String agentName) { + AgentTreeModel model = getModel(); + Node fromContainer = findContainerNode(fromContainerName); + Node toContainer = findContainerNode(toContainerName); + + // If there is a frozen agent already, do nothing, else move the agent node + Node frozenAgents = findFrozenAgentsFolder(toContainer, FROZEN_AGENTS_FOLDER_NAME); + if (frozenAgents != null) { + Node agent = findAgentNode(frozenAgents, agentName); + if (agent == null) { + // Move the agent node + agent = findAgentNode(fromContainer, agentName); + model.removeNodeFromParent(agent); + model.insertNodeInto(agent, toContainer, toContainer.getChildCount()); + } + } else { + // Move the agent node + Node agent = findAgentNode(fromContainer, agentName); + model.removeNodeFromParent(agent); + model.insertNodeInto(agent, toContainer, toContainer.getChildCount()); + } + } + + public void freezeAgentNode(String oldContainerName, String newContainerName, String agentName) { + AgentTreeModel model = getModel(); + Node oldContainer = findContainerNode(oldContainerName); + Node agent = findAgentNode(oldContainer, agentName); + model.removeNodeFromParent(agent); + + agent.setState("frozen"); + agent.changeIcon("frozen"); + + Node newContainer = findContainerNode(newContainerName); + Node frozenAgents = findFrozenAgentsFolder(newContainer, FROZEN_AGENTS_FOLDER_NAME); + if (frozenAgents == null) { + frozenAgents = createContainerNode(FROZEN_AGENTS_FOLDER_NAME); + frozenAgents.setType(FROZEN_CONTAINER_TYPE); + model.insertNodeInto(frozenAgents, newContainer, 0); + } + model.insertNodeInto(agent, frozenAgents, frozenAgents.getChildCount()); + + } + + public void thawAgentNode(String oldContainerName, String newContainerName, String agentName) { + AgentTreeModel model = getModel(); + Node oldContainer = findContainerNode(oldContainerName); + Node frozenAgents = findFrozenAgentsFolder(oldContainer, FROZEN_AGENTS_FOLDER_NAME); + Node agent = findAgentNode(frozenAgents, agentName); + model.removeNodeFromParent(agent); + if (frozenAgents.isLeaf()) { + model.removeNodeFromParent(frozenAgents); + } + + agent.setState("active"); + agent.changeIcon("active"); + + Node newContainer = findContainerNode(newContainerName); + model.insertNodeInto(agent, newContainer, newContainer.getChildCount()); + + } + + public void removeAgentNode(String containerName, String agentName) { + AgentTreeModel model = getModel(); + Node container = findContainerNode(containerName); + if (container != null) { + Node agent = findAgentNode(container, agentName); + + if (agent != null) { + model.removeNodeFromParent(agent); + } else { + // It can be a frozen agent + Node frozenAgents = findFrozenAgentsFolder(container, FROZEN_AGENTS_FOLDER_NAME); + if (frozenAgents != null) { + agent = findAgentNode(frozenAgents, agentName); + + model.removeNodeFromParent(agent); + if (frozenAgents.isLeaf()) { + model.removeNodeFromParent(frozenAgents); + } } } } } - public void addContainerNode(String containerName, InetAddress addr) { - ContainerNode node = new ContainerNode(containerName); - node.setAddress(addr); + public void addRemotePlatformNode(AID ams, APDescription desc) { AgentTreeModel model = getModel(); MutableTreeNode root = (MutableTreeNode) model.getRoot(); - Enumeration folders = root.children(); - while (folders.hasMoreElements()) { - Node folderNode = (Node) folders.nextElement(); - String folderName = folderNode.getName(); - if (folderName.equalsIgnoreCase(localPlatformName)) { - model.insertNodeInto(node, folderNode, folderNode.getChildCount()); + + // Search for the folder REMOTEPLATFORM + Enumeration containers = root.children(); + while (containers.hasMoreElements()) {//1 + Node container = (Node) containers.nextElement(); + String contName = container.getName(); + if (contName.equalsIgnoreCase(REMOTE_PLATFORMS_FOLDER_NAME)) {//2 + boolean found = false; + Enumeration agents = container.children(); + while (agents.hasMoreElements() && !found) {//3 + RemotePlatformNode platform = (RemotePlatformNode) agents.nextElement(); + String APName = platform.getName(); + if (APName.equalsIgnoreCase(desc.getName())) {//update the APDescription of this node + platform.setAPDescription(desc); + found = true; + } + }//3 + if (!found) { + // Add this new platform to this container and return + RemotePlatformNode node = new RemotePlatformNode(desc.getName()); + node.setAPDescription(desc); + node.setAmsAID(ams); + model.insertNodeInto(node, container, container.getChildCount()); + } return; - } - } + }//2 + }//1 } - /** - * @deprecated Use addContainerNode(String, InetAddress) instead - */ - public void addContainerNode(ContainerNode node, String typeContainer, InetAddress addr) { + public void removeRemotePlatformNode(String name) { AgentTreeModel model = getModel(); MutableTreeNode root = (MutableTreeNode) model.getRoot(); - node.setType(typeContainer); - Enumeration folders = root.children(); - while (folders.hasMoreElements()) { - Node folderNode = (Node) folders.nextElement(); - String folderName = folderNode.getName(); - if (folderName.equalsIgnoreCase(localPlatformName)) { - model.insertNodeInto(node, folderNode, folderNode.getChildCount()); - break; - } - } - node.setAddress(addr); - } - public void removeContainerNode(String nameNode) { - AgentTreeModel model = getModel(); - MutableTreeNode root = (MutableTreeNode) model.getRoot(); - Enumeration folders = root.children(); - while (folders.hasMoreElements()) { - Node folderNode = (Node) folders.nextElement(); - String folderName = folderNode.getName(); - if (folderName.equalsIgnoreCase(localPlatformName)) {//found the localplatform folder - Enumeration containers = folderNode.children(); - while (containers.hasMoreElements()) { - Node node = (Node) containers.nextElement(); - String nodeName = node.getName(); - if (nodeName.equalsIgnoreCase(nameNode)) { - model.removeNodeFromParent(node); + // Search for the RemotePlatforms node + Enumeration containers = root.children(); + while (containers.hasMoreElements()) { + Node container = (Node) containers.nextElement(); + String contName = container.getName(); + if (contName.equalsIgnoreCase(REMOTE_PLATFORMS_FOLDER_NAME)) { + // Search for the ams + Enumeration agents = container.children(); + while (agents.hasMoreElements()) { + Node agent = (Node) agents.nextElement(); + String agName = agent.getName(); + if (agName.equalsIgnoreCase(name)) { + model.removeNodeFromParent(agent); + //if it's the last child remove the folder REMOTEPLATFORMS + if (container.getChildCount() == 0) + model.removeNodeFromParent(container); return; } } @@ -508,133 +528,142 @@ public void removeContainerNode(String nameNode) { } } - public void addRemotePlatformsFolderNode() { + public void addRemoteAgentNode(AMSAgentDescription agent, String HAP) { + AgentTreeModel model = getModel(); MutableTreeNode root = (MutableTreeNode) model.getRoot(); - Enumeration children = root.children(); - boolean existing = false; + //Search for the REMOTEPLATFORMS node + Enumeration containers = root.children(); - while (children.hasMoreElements() & (!existing)) { - Node node = (Node) children.nextElement(); - String nodeName = node.getName(); - if (nodeName.equalsIgnoreCase(REMOTE_PLATFORMS_FOLDER_NAME)) - existing = true; - } + while (containers.hasMoreElements()) { - if (!existing) { - RemotePlatformsFolderNode rpn = new RemotePlatformsFolderNode(REMOTE_PLATFORMS_FOLDER_NAME); - model.insertNodeInto(rpn, root, root.getChildCount()); - } + Node container = (Node) containers.nextElement(); + String contName = container.getName(); - return; - } + if (contName.equalsIgnoreCase(REMOTE_PLATFORMS_FOLDER_NAME)) { + //search the remotePlatform + Enumeration plat_Enum = container.children(); - public void addAgentNode(String agentName, String agentAddress, String containerName) { - addAgentNode(agentName, agentAddress, containerName, "Running", null); + while (plat_Enum.hasMoreElements()) { + Node platformNode = (Node) plat_Enum.nextElement(); + String platformNodeName = platformNode.getName(); + if (platformNodeName.equalsIgnoreCase(HAP)) { + //now add remote agent registered with that ams... + Enumeration remote_agents = platformNode.children(); + boolean found = false; + while (remote_agents.hasMoreElements() && !found) { + + RemoteAgentNode node = (RemoteAgentNode) remote_agents.nextElement(); + String remoteName = node.getName(); + if (remoteName.equalsIgnoreCase(agent.getName().getName())) { + node.setAMSDescription(agent); //update the AMSDescription + found = true; + } + } + if (!found) { + RemoteAgentNode newNode = new RemoteAgentNode(agent.getName().getName()); + newNode.setAMSDescription(agent); + int position = getPosition(newNode, platformNode); + model.insertNodeInto(newNode, platformNode, position); + } + } + } + } + } } - public void addAgentNode(String agentName, String agentAddress, String containerName, String agentState, String ownership) { - AgentNode node = new AgentNode(agentName); - node.setAddress(agentAddress); - node.setState(agentState); - node.setOwnership(ownership); + public void clearRemotePlatformAgents(String HAP) { AgentTreeModel model = getModel(); MutableTreeNode root = (MutableTreeNode) model.getRoot(); - // Search for the folder of the local Platform - Enumeration folders = root.children(); - while (folders.hasMoreElements()) { - Node folderNode = (Node) folders.nextElement(); - String folderName = folderNode.getName(); - if (folderName.equalsIgnoreCase(localPlatformName)) { - // Search for the agent container 'containerName' - Enumeration containers = folderNode.children(); - while (containers.hasMoreElements()) { - Node containerNode = (Node) containers.nextElement(); - String contName = containerNode.getName(); - if (contName.equalsIgnoreCase(containerName)) { - // Add this new agent to this container and return - int position = getPosition(node, containerNode); - model.insertNodeInto(node, containerNode, position); - return; + //Search for the REMOTEPLATFORMS node + Enumeration containers = root.children(); + + while (containers.hasMoreElements()) { + + Node container = (Node) containers.nextElement(); + String contName = container.getName(); + + if (contName.equalsIgnoreCase(REMOTE_PLATFORMS_FOLDER_NAME)) { + //search the remotePlatform + Enumeration plat_Enum = container.children(); + + while (plat_Enum.hasMoreElements()) { + Node platformNode = (Node) plat_Enum.nextElement(); + String platformNodeName = platformNode.getName(); + + if (platformNodeName.equalsIgnoreCase(HAP)) { + Enumeration en = platformNode.children(); + List remoteAgents = new ArrayList<>(); + while (en.hasMoreElements()) { + remoteAgents.add(en.nextElement()); + } + for (TreeNode agent : remoteAgents) { + Node remoteAgent = (Node) agent; + model.removeNodeFromParent(remoteAgent); + } } } } } } - private int getPosition(Node node, Node parentNode) { - int size = parentNode.getChildCount(); - if (size == 0) { - // This is the first child - return 0; + public Node getSelectedNode() { + TreePath path = tree.getSelectionPath(); + if (path != null) { + return (Node) path.getLastPathComponent(); } else { - int k = node.compareTo((Node) parentNode.getChildAt(0)); - if (k < 0) { - // Insert new child at the beginning of the list - return 0; - } else { - k = node.compareTo((Node) parentNode.getChildAt(size - 1)); - if (k >= 0) { - // Insert new child at the end of the list - return size; - } else { - // Insert new child "somewhere" in the list - return getPosition(node, parentNode, 0, size - 1); - } - } + return null; } } - private int getPosition(Node node, Node parentNode, int down, int up) { - if ((up - down) == 1) { - return up; - } else { - int middle = (up + down) / 2; - int k = node.compareTo((Node) parentNode.getChildAt(middle)); - if (k == 0) { - return middle + 1; - } else if (k < 0) { - return getPosition(node, parentNode, down, middle); - } else { - return getPosition(node, parentNode, middle, up); - } + public AgentTreeModel getModel() { + if (tree.getModel() instanceof AgentTreeModel) + return (AgentTreeModel) tree.getModel(); + else { + System.out.println(tree.getModel()); + return null; } } - /** - * @deprecated Use addAgentNode(String, String, String) instead - */ - public void addAgentNode(AgentNode node, String containerName, String agentName, String agentAddress, String agentType) { - AgentTreeModel model = getModel(); - MutableTreeNode root = (MutableTreeNode) model.getRoot(); - node.setType(agentType); - node.setAddress(agentAddress); - node.setState("Running"); - //search for the folder of the local Platform - Enumeration folders = root.children(); - while (folders.hasMoreElements()) { - Node folderNode = (Node) folders.nextElement(); - String folderName = folderNode.getName(); - if (folderName.equalsIgnoreCase(localPlatformName)) { - // Search for the agent container 'containerName' - Enumeration containers = folderNode.children(); - while (containers.hasMoreElements()) { - Node container = (Node) containers.nextElement(); - String contName = container.getName(); - if (contName.equalsIgnoreCase(containerName)) { - // Add this new agent to this container and return - model.insertNodeInto(node, container, container.getChildCount()); - return; - } - } + public void register(String key, JPopupMenu popmenu, String pathImage) { + NodeDescriptor nDescriptor = new NodeDescriptor(popmenu, pathImage); + mapDescriptor.put(key, nDescriptor); + } + + public JPopupMenu getPopupMenu(String key) { + NodeDescriptor nDescriptor = mapDescriptor.get(key); + return nDescriptor.getPopupMenu(); + } + + public void setNewPopupMenu(String key, JPopupMenu pop) { + if (mapDescriptor.containsKey(key)) { + NodeDescriptor nDescriptor = mapDescriptor.get(key); + nDescriptor.setNewPopupMenu(pop); + } + } + + protected String getIconAgent(String key) { + NodeDescriptor nDescriptor = mapDescriptor.get(key); + return nDescriptor.getPathImage(); + } + + private Node findAgentNode(Node container, String name) { + + Enumeration agents = container.children(); + while (agents.hasMoreElements()) { + Node agent = (Node) agents.nextElement(); + if (agent.getName().equalsIgnoreCase(name)) { + return agent; } } + + return null; } - public void modifyAgentNode(String containerName, String agentName, String address, String state, String ownership) { + private Node findContainerNode(String name) { AgentTreeModel model = getModel(); MutableTreeNode root = (MutableTreeNode) model.getRoot(); //search for the folder of the local Platform @@ -643,345 +672,308 @@ public void modifyAgentNode(String containerName, String agentName, String addre Node folderNode = (Node) folders.nextElement(); String folderName = folderNode.getName(); if (folderName.equalsIgnoreCase(localPlatformName)) { - // Search for the agent container 'containerName' + // Search for the agent container 'name' Enumeration containers = folderNode.children(); while (containers.hasMoreElements()) { Node container = (Node) containers.nextElement(); String contName = container.getName(); - if (contName.equalsIgnoreCase(containerName)) { - Enumeration agents = container.children(); - while (agents.hasMoreElements()) { - Node agent = (Node) agents.nextElement(); - - if (agent.getName().equalsIgnoreCase(agentName)) { - if (state != null) - agent.setState(state); - if (ownership != null) - agent.setOwnership(ownership); - agent.changeIcon(state); - model.nodeChanged(agent); - return; - } - } + if (contName.equalsIgnoreCase(name)) { + return container; } } } } - } - public void moveAgentNode(String fromContainerName, String toContainerName, String agentName) { - AgentTreeModel model = getModel(); - Node fromContainer = findContainerNode(fromContainerName); - Node toContainer = findContainerNode(toContainerName); + return null; - // If there is a frozen agent already, do nothing, else move the agent node - Node frozenAgents = findFrozenAgentsFolder(toContainer, FROZEN_AGENTS_FOLDER_NAME); - if (frozenAgents != null) { - Node agent = findAgentNode(frozenAgents, agentName); - if (agent == null) { - // Move the agent node - agent = findAgentNode(fromContainer, agentName); - model.removeNodeFromParent(agent); - model.insertNodeInto(agent, toContainer, toContainer.getChildCount()); + } + + private Node findFrozenAgentsFolder(Node container, String name) { + Enumeration agents = container.children(); + while (agents.hasMoreElements()) { + Node child = (Node) agents.nextElement(); + if (child.getName().equalsIgnoreCase(name) && child.getType().equalsIgnoreCase(FROZEN_CONTAINER_TYPE)) { + return child; } - } else { - // Move the agent node - Node agent = findAgentNode(fromContainer, agentName); - model.removeNodeFromParent(agent); - model.insertNodeInto(agent, toContainer, toContainer.getChildCount()); } + + return null; } - public void freezeAgentNode(String oldContainerName, String newContainerName, String agentName) { - AgentTreeModel model = getModel(); - Node oldContainer = findContainerNode(oldContainerName); - Node agent = findAgentNode(oldContainer, agentName); - model.removeNodeFromParent(agent); + /** + * Inner class Node + * Common base class for all AgentTree nodes + */ + public abstract class Node extends DefaultMutableTreeNode { - agent.setState("frozen"); - agent.changeIcon("frozen"); + protected Icon img; + protected String name; + protected String state; + protected String ownership; + protected boolean greyOut = false; - Node newContainer = findContainerNode(newContainerName); - Node frozenAgents = findFrozenAgentsFolder(newContainer, FROZEN_AGENTS_FOLDER_NAME); - if (frozenAgents == null) { - frozenAgents = createContainerNode(FROZEN_AGENTS_FOLDER_NAME); - frozenAgents.setType(FROZEN_CONTAINER_TYPE); - model.insertNodeInto(frozenAgents, newContainer, 0); + public Node(String name) { + this.name = name; } - model.insertNodeInto(agent, frozenAgents, frozenAgents.getChildCount()); - } + public Icon getIcon(String typeAgent) { + Image image = getToolkit().getImage(getClass().getResource(getIconAgent(typeAgent))); + if (greyOut) { + ImageFilter colorfilter = new MyFilterImage(); + Image imageFiltered = createImage(new FilteredImageSource(image.getSource(), colorfilter)); + return new ImageIcon(imageFiltered); + } else + return new ImageIcon(image); + } - public void thawAgentNode(String oldContainerName, String newContainerName, String agentName) { - AgentTreeModel model = getModel(); - Node oldContainer = findContainerNode(oldContainerName); - Node frozenAgents = findFrozenAgentsFolder(oldContainer, FROZEN_AGENTS_FOLDER_NAME); - Node agent = findAgentNode(frozenAgents, agentName); - model.removeNodeFromParent(agent); - if (frozenAgents.isLeaf()) { - model.removeNodeFromParent(frozenAgents); + public String getName() { + return name; } - agent.setState("active"); - agent.changeIcon("active"); + public void setName(String name) { + this.name = name; + } - Node newContainer = findContainerNode(newContainerName); - model.insertNodeInto(agent, newContainer, newContainer.getChildCount()); + public String getState() { + return state != null ? state : ""; + } - } + public void setState(String state) { + this.state = state; + } - public void removeAgentNode(String containerName, String agentName) { - AgentTreeModel model = getModel(); - Node container = findContainerNode(containerName); - if (container != null) { - Node agent = findAgentNode(container, agentName); + public String getOwnership() { + return ownership != null ? ownership : ""; + } - if (agent != null) { - model.removeNodeFromParent(agent); - } else { - // It can be a frozen agent - Node frozenAgents = findFrozenAgentsFolder(container, FROZEN_AGENTS_FOLDER_NAME); - if (frozenAgents != null) { - agent = findAgentNode(frozenAgents, agentName); + public void setOwnership(String ownership) { + this.ownership = ownership; + } - model.removeNodeFromParent(agent); - if (frozenAgents.isLeaf()) { - model.removeNodeFromParent(frozenAgents); - } - } + public void changeIcon(String agentState) { + if (agentState.equalsIgnoreCase("suspended")) { + greyOut = true; + setType(AGENT_TYPE); + } else if (agentState.equalsIgnoreCase("active")) { + greyOut = false; + setType(AGENT_TYPE); + } else if (agentState.equalsIgnoreCase("frozen")) { + greyOut = false; + setType(FROZEN_AGENT_TYPE); } } - } - public void addRemotePlatformNode(AID ams, APDescription desc) { + public abstract String getType(); - AgentTreeModel model = getModel(); - MutableTreeNode root = (MutableTreeNode) model.getRoot(); + public abstract void setType(String type); - // Search for the folder REMOTEPLATFORM - Enumeration containers = root.children(); - while (containers.hasMoreElements()) {//1 - Node container = (Node) containers.nextElement(); - String contName = container.getName(); - if (contName.equalsIgnoreCase(REMOTE_PLATFORMS_FOLDER_NAME)) {//2 - boolean found = false; - Enumeration agents = container.children(); - while (agents.hasMoreElements() && !found) {//3 - RemotePlatformNode platform = (RemotePlatformNode) agents.nextElement(); - String APName = platform.getName(); - if (APName.equalsIgnoreCase(desc.getName())) {//update the APDescription of this node - platform.setAPDescription(desc); - found = true; - } - }//3 - if (!found) { - // Add this new platform to this container and return - RemotePlatformNode node = new RemotePlatformNode(desc.getName()); - node.setAPDescription(desc); - node.setAmsAID(ams); - model.insertNodeInto(node, container, container.getChildCount()); - } - return; - }//2 - }//1 - } + public abstract String getToolTipText(); + + public String toString() { + return (getType() != null ? getType() + "-" + name : name); + } + + public int compareTo(Node n) { + return name.compareTo(n.getName()); + } + } // END of inner class Node + + /** + * Inner class AgentNode + */ + public class AgentNode extends Node { + private String agentType; + private String agentAddress; + + public AgentNode(String name) { + super(name); + agentType = AGENT_TYPE; + } + + public String getAddress() { + return agentAddress; + } + + public void setAddress(String address) { + agentAddress = address; + } + + public String getType() { + return agentType; + } + + public void setType(String type) { + agentType = type; + } + + public String getToolTipText() { + return ("Local Agent"); + } + } // END of inner class AgentNode + + /** + * Inner class ContainerNode + */ + public class ContainerNode extends Node { + private InetAddress addressmachine; + private String containerType; + + public ContainerNode(String name) { + super(name); + containerType = CONTAINER_TYPE; + } + + public void setAddress(InetAddress addr) { + addressmachine = addr; + } + + public String getType() { + return containerType; + } + + public void setType(String type) { + containerType = type; + } + + public String getToolTipText() { + if (addressmachine != null) + return name + " " + "[" + addressmachine.getHostAddress() + "]"; + else + return name + " " + "[???:???:???:???]"; + } + } // END of inner class ContainerNode - public void removeRemotePlatformNode(String name) { - AgentTreeModel model = getModel(); - MutableTreeNode root = (MutableTreeNode) model.getRoot(); + /** + * Inner class SuperContainer + */ + public class SuperContainer extends Node { - // Search for the RemotePlatforms node - Enumeration containers = root.children(); - while (containers.hasMoreElements()) { - Node container = (Node) containers.nextElement(); - String contName = container.getName(); - if (contName.equalsIgnoreCase(REMOTE_PLATFORMS_FOLDER_NAME)) { - // Search for the ams - Enumeration agents = container.children(); - while (agents.hasMoreElements()) { - Node agent = (Node) agents.nextElement(); - String agName = agent.getName(); - if (agName.equalsIgnoreCase(name)) { - model.removeNodeFromParent(agent); - //if it's the last child remove the folder REMOTEPLATFORMS - if (container.getChildCount() == 0) - model.removeNodeFromParent(container); - return; - } - } - } + public SuperContainer(String name) { + super(name); } - } - public void addRemoteAgentNode(AMSAgentDescription agent, String HAP) { + public String getToolTipText() { + return ("Java Agent DEvelopment Framework"); + } - AgentTreeModel model = getModel(); - MutableTreeNode root = (MutableTreeNode) model.getRoot(); + public String getType() { + return TREE_ROOT_TYPE; + } - //Search for the REMOTEPLATFORMS node - Enumeration containers = root.children(); + public void setType(String noType) { + } + } // END of inner class SuperContainer - while (containers.hasMoreElements()) { + /** + * Inner class RemotePlatformsFolderNode + */ + public class RemotePlatformsFolderNode extends Node { - Node container = (Node) containers.nextElement(); - String contName = container.getName(); + public RemotePlatformsFolderNode(String name) { + super(name); + } - if (contName.equalsIgnoreCase(REMOTE_PLATFORMS_FOLDER_NAME)) { - //search the remotePlatform - Enumeration plat_Enum = container.children(); + public String getToolTipText() { + return ("List of RemotePlatforms"); + } - while (plat_Enum.hasMoreElements()) { - Node platformNode = (Node) plat_Enum.nextElement(); - String platformNodeName = platformNode.getName(); - if (platformNodeName.equalsIgnoreCase(HAP)) { - //now add remote agent registered with that ams... - Enumeration remote_agents = platformNode.children(); - boolean found = false; - while (remote_agents.hasMoreElements() && !found) { + public String getType() { + return (REMOTE_PLATFORMS_FOLDER_TYPE); + } - RemoteAgentNode node = (RemoteAgentNode) remote_agents.nextElement(); - String remoteName = node.getName(); - if (remoteName.equalsIgnoreCase(agent.getName().getName())) { - node.setAMSDescription(agent); //update the AMSDescription - found = true; - } - } - if (!found) { - RemoteAgentNode newNode = new RemoteAgentNode(agent.getName().getName()); - newNode.setAMSDescription(agent); - int position = getPosition(newNode, platformNode); - model.insertNodeInto(newNode, platformNode, position); - } - } - } - } + public void setType(String noType) { } - } + } // END of inner class RemotePlatformsFolderNode - public void clearRemotePlatformAgents(String HAP) { + /** + * Inner class localPlatformFolderNode + */ + public class LocalPlatformFolderNode extends Node { - AgentTreeModel model = getModel(); - MutableTreeNode root = (MutableTreeNode) model.getRoot(); + public LocalPlatformFolderNode(String name) { + super(name); + } - //Search for the REMOTEPLATFORMS node - Enumeration containers = root.children(); + public String getToolTipText() { + return ("Local JADE Platform"); + } - while (containers.hasMoreElements()) { + public String getType() { + return ("LOCALPLATFORM"); + } - Node container = (Node) containers.nextElement(); - String contName = container.getName(); + public void setType(String noType) { + } + } // END of inner class LocalPlatformFolderNode - if (contName.equalsIgnoreCase(REMOTE_PLATFORMS_FOLDER_NAME)) { - //search the remotePlatform - Enumeration plat_Enum = container.children(); + /** + * Inner class RemotePlatformNode + */ + public class RemotePlatformNode extends Node { - while (plat_Enum.hasMoreElements()) { - Node platformNode = (Node) plat_Enum.nextElement(); - String platformNodeName = platformNode.getName(); + private APDescription AP_Profile; + private AID amsAID; - if (platformNodeName.equalsIgnoreCase(HAP)) { - Enumeration en = platformNode.children(); - List remoteAgents = new ArrayList<>(); - while (en.hasMoreElements()) { - remoteAgents.add(en.nextElement()); - } - for (TreeNode agent : remoteAgents) { - Node remoteAgent = (Node) agent; - model.removeNodeFromParent(remoteAgent); - } - } - } - } + public RemotePlatformNode(String name) { + super(name); } - } - public Node getSelectedNode() { - TreePath path = tree.getSelectionPath(); - if (path != null) { - return (Node) path.getLastPathComponent(); - } else { - return null; + public String getToolTipText() { + return ("Remote Platform"); } - } - public AgentTreeModel getModel() { - if (tree.getModel() instanceof AgentTreeModel) - return (AgentTreeModel) tree.getModel(); - else { - System.out.println(tree.getModel()); - return null; + public String getType() { + return ("REMOTEPLATFORM"); } - } - - public void register(String key, JPopupMenu popmenu, String pathImage) { - NodeDescriptor nDescriptor = new NodeDescriptor(popmenu, pathImage); - mapDescriptor.put(key, nDescriptor); - } - public JPopupMenu getPopupMenu(String key) { - NodeDescriptor nDescriptor = mapDescriptor.get(key); - return nDescriptor.getPopupMenu(); - } + public void setType(String noType) { + } - public void setNewPopupMenu(String key, JPopupMenu pop) { - if (mapDescriptor.containsKey(key)) { - NodeDescriptor nDescriptor = mapDescriptor.get(key); - nDescriptor.setNewPopupMenu(pop); + public APDescription getAPDescription() { + return AP_Profile; } - } - protected String getIconAgent(String key) { - NodeDescriptor nDescriptor = mapDescriptor.get(key); - return nDescriptor.getPathImage(); - } + public void setAPDescription(APDescription desc) { + AP_Profile = desc; + } - private Node findAgentNode(Node container, String name) { + public AID getAmsAID() { + return amsAID; + } - Enumeration agents = container.children(); - while (agents.hasMoreElements()) { - Node agent = (Node) agents.nextElement(); - if (agent.getName().equalsIgnoreCase(name)) { - return agent; - } + public void setAmsAID(AID id) { + amsAID = id; } + } // END of inner class RemotePlatformNode - return null; - } + /** + * Inner class RemoteAgentNode + */ + public class RemoteAgentNode extends AgentNode { - private Node findContainerNode(String name) { - AgentTreeModel model = getModel(); - MutableTreeNode root = (MutableTreeNode) model.getRoot(); - //search for the folder of the local Platform - Enumeration folders = root.children(); - while (folders.hasMoreElements()) { - Node folderNode = (Node) folders.nextElement(); - String folderName = folderNode.getName(); - if (folderName.equalsIgnoreCase(localPlatformName)) { - // Search for the agent container 'name' - Enumeration containers = folderNode.children(); - while (containers.hasMoreElements()) { - Node container = (Node) containers.nextElement(); - String contName = container.getName(); - if (contName.equalsIgnoreCase(name)) { - return container; - } - } - } + private AMSAgentDescription amsd; + + public RemoteAgentNode(String name) { + super(name); } - return null; + public String getToolTipText() { + return ("Remote Agent"); + } - } + public String getType() { + return ("REMOTEAGENT"); + } - private Node findFrozenAgentsFolder(Node container, String name) { - Enumeration agents = container.children(); - while (agents.hasMoreElements()) { - Node child = (Node) agents.nextElement(); - if (child.getName().equalsIgnoreCase(name) && child.getType().equalsIgnoreCase(FROZEN_CONTAINER_TYPE)) { - return child; - } + public void setType(String noType) { } - return null; - } + public AMSAgentDescription getAMSDescription() { + return amsd; + } + + public void setAMSDescription(AMSAgentDescription id) { + amsd = id; + } + } // END of inner class RemoteAgentNode } diff --git a/src/jade/gui/AgentWindowed.java b/src/jade/gui/AgentWindowed.java index 78b7bd4..670184f 100644 --- a/src/jade/gui/AgentWindowed.java +++ b/src/jade/gui/AgentWindowed.java @@ -1,7 +1,6 @@ package jade.gui; import javax.swing.*; -import java.util.Random; /** @@ -9,28 +8,33 @@ * * @author revised by Emmanuel ADAM */ -public class AgentWindowed extends GuiAgent{ +public class AgentWindowed extends GuiAgent { protected SimpleWindow4Agent window; - /** GUI */ + /** + * GUI + */ - public AgentWindowed() { + public AgentWindowed() { } - /**print a msg n the associated window*/ - protected void println(String msg) - { + /** + * print a msg n the associated window + */ + protected void println(String msg) { SwingUtilities.invokeLater(() -> window.println(msg)); } - /**fonction a remplir pour repondre aux evenements de la fenetre - * (par defaut, tue l'agent quand la fenetre est fermee)*/ + /** + * fonction a remplir pour repondre aux evenements de la fenetre + * (par defaut, tue l'agent quand la fenetre est fermee) + */ @Override protected void onGuiEvent(GuiEvent evt) { - if(evt.getType()==SimpleWindow4Agent.QUIT_EVENT) { + if (evt.getType() == SimpleWindow4Agent.QUIT_EVENT) { //fermeture de la fenetre, on tue l'agent doDelete(); } diff --git a/src/jade/gui/BrowserLauncher.java b/src/jade/gui/BrowserLauncher.java index 06c8514..036aa35 100644 --- a/src/jade/gui/BrowserLauncher.java +++ b/src/jade/gui/BrowserLauncher.java @@ -54,17 +54,69 @@ */ public class BrowserLauncher { + /** + * JVM constant for MRJ 2.0 + */ + private static final int MRJ_2_0 = 0; + /** + * JVM constant for MRJ 2.1 or later + */ + private static final int MRJ_2_1 = 1; + /** + * JVM constant for any Windows NT JVM + */ + private static final int WINDOWS_NT = 2; + /** + * JVM constant for any Windows 9x JVM + */ + private static final int WINDOWS_9x = 3; + private static final int WINDOWS_2000 = 4; + /** + * JVM constant for any other platform + */ + private static final int OTHER = -1; + /** + * The file type of the Finder on a Macintosh. Hardcoding "Finder" would keep non-U.S. English + * systems from working properly. + */ + private static final String FINDER_TYPE = "FNDR"; + /** + * The creator code of the Finder on a Macintosh, which is needed to send AppleEvents to the + * application. + */ + private static final String FINDER_CREATOR = "MACS"; + /** + * The name for the AppleEvent type corresponding to a GetURL event. + */ + private static final String GURL_EVENT = "GURL"; + /** + * The first parameter that needs to be passed into Runtime.exec() to open the default web + * browser on Windows. + */ + private static final String FIRST_WINDOWS_PARAMETER = "/c"; + /** + * The second parameter for Runtime.exec() on Windows. + */ + private static final String SECOND_WINDOWS_PARAMETER = "start"; + /** + * The shell parameters for Netscape that opens a given URL in an already-open copy of Netscape + * on many command-line systems. + */ + private static final String NETSCAPE_OPEN_PARAMETER_START = " -remote 'openURL("; + private static final String NETSCAPE_OPEN_PARAMETER_END = ")'"; + /** + * The URL for the official JADE Home Page. + */ + public static String jadeURL = "http://jade.tilab.com/"; /** * The Java virtual machine that we are running on. Actually, in most cases we only care * about the operating system, but some operating systems require us to switch on the VM. */ private static int jvm; - /** * The browser for the system */ private static Object browser; - /** * Caches whether any classes, methods, and fields that are not part of the JDK and need to * be dynamically loaded at runtime loaded successfully. @@ -73,160 +125,75 @@ public class BrowserLauncher { * IOException. */ private static boolean loadedWithoutErrors; - /** * The com.apple.mrj.MRJFileUtils class */ private static Class mrjFileUtilsClass; - /** * The com.apple.mrj.MRJOSType class */ private static Class mrjOSTypeClass; - /** * The com.apple.MacOS.MacOSError class */ private static Class macOSErrorClass; - /** * The com.apple.MacOS.AEDesc class */ private static Class aeDescClass; - /** * The (int) method of com.apple.MacOS.AETarget */ private static Constructor aeTargetConstructor; - /** * The (int, int, int) method of com.apple.MacOS.AppleEvent */ private static Constructor appleEventConstructor; - /** * The (String) method of com.apple.MacOS.AEDesc */ private static Constructor aeDescConstructor; - /** * The findFolder method of com.apple.mrj.MRJFileUtils */ private static Method findFolder; - /** * The getFileType method of com.apple.mrj.MRJOSType */ private static Method getFileType; - /** * The makeOSType method of com.apple.MacOS.OSUtils */ private static Method makeOSType; - /** * The putParameter method of com.apple.MacOS.AppleEvent */ private static Method putParameter; - /** * The sendNoReply method of com.apple.MacOS.AppleEvent */ private static Method sendNoReply; - /** * Actually an MRJOSType pointing to the System Folder on a Macintosh */ private static Object kSystemFolderType; - /** * The keyDirectObject AppleEvent parameter type */ private static Integer keyDirectObject; - /** * The kAutoGenerateReturnID AppleEvent code */ private static Integer kAutoGenerateReturnID; - /** * The kAnyTransactionID AppleEvent code */ private static Integer kAnyTransactionID; - - /** - * JVM constant for MRJ 2.0 - */ - private static final int MRJ_2_0 = 0; - - /** - * JVM constant for MRJ 2.1 or later - */ - private static final int MRJ_2_1 = 1; - - /** - * JVM constant for any Windows NT JVM - */ - private static final int WINDOWS_NT = 2; - - /** - * JVM constant for any Windows 9x JVM - */ - private static final int WINDOWS_9x = 3; - - - private static final int WINDOWS_2000 = 4; - - /** - * JVM constant for any other platform - */ - private static final int OTHER = -1; - - /** - * The file type of the Finder on a Macintosh. Hardcoding "Finder" would keep non-U.S. English - * systems from working properly. - */ - private static final String FINDER_TYPE = "FNDR"; - - /** - * The creator code of the Finder on a Macintosh, which is needed to send AppleEvents to the - * application. - */ - private static final String FINDER_CREATOR = "MACS"; - - /** - * The name for the AppleEvent type corresponding to a GetURL event. - */ - private static final String GURL_EVENT = "GURL"; - - /** - * The first parameter that needs to be passed into Runtime.exec() to open the default web - * browser on Windows. - */ - private static final String FIRST_WINDOWS_PARAMETER = "/c"; - - /** - * The second parameter for Runtime.exec() on Windows. - */ - private static final String SECOND_WINDOWS_PARAMETER = "start"; - - /** - * The shell parameters for Netscape that opens a given URL in an already-open copy of Netscape - * on many command-line systems. - */ - private static final String NETSCAPE_OPEN_PARAMETER_START = " -remote 'openURL("; - private static final String NETSCAPE_OPEN_PARAMETER_END = ")'"; - /** * The message from any exception thrown throughout the initialization process. */ private static String errorMessage; - /** - * The URL for the official JADE Home Page. - */ - public static String jadeURL = "http://jade.tilab.com/"; - /** * An initialization block that determines the operating system and loads the necessary * runtime data. diff --git a/src/jade/gui/ClassSelectionDialog.java b/src/jade/gui/ClassSelectionDialog.java index d9c4b52..65ea254 100644 --- a/src/jade/gui/ClassSelectionDialog.java +++ b/src/jade/gui/ClassSelectionDialog.java @@ -42,8 +42,14 @@ public class ClassSelectionDialog extends JDialog implements WindowListener, ActionListener, ListSelectionListener { + public final static int DLG_OK = 1; + public final static int DLG_CANCEL = 0; + public static final int ACC_INTERFACE = 0x0200; + public static final int ACC_ABSTRACT = 0x0400; @Serial private static final long serialVersionUID = 1L; + private final String classname; + private final ClassFinderFilter classfilter; private JPanel jContentPane = null; private JPanel jPanel = null; private JButton jButtonOk = null; @@ -54,121 +60,21 @@ public class ClassSelectionDialog extends JDialog implements WindowListener, Act private ClassesTableModel jTableModel; private int result; private String selectedClassname; - public final static int DLG_OK = 1; - public final static int DLG_CANCEL = 0; private boolean classesLoaded; - private final String classname; - private final ClassFinderFilter classfilter; - - public static final int ACC_INTERFACE = 0x0200; - public static final int ACC_ABSTRACT = 0x0400; - - private class ClassFilter implements ClassFinderFilter { - public boolean include(Class superClazz, Class clazz) { - int modifiers = clazz.getModifiers(); - boolean doInclude = ((modifiers & (ACC_ABSTRACT | ACC_INTERFACE)) == 0); - if (doInclude) { - doInclude = !clazz.getName().equals(classname); - } - return doInclude; - } - } - private class ClassUpdater implements Runnable, ClassFinderListener { - - private final static int UPDATE_EVERY = 1; - - private int numberOfClasses; - private List classNamesCache; - private final String classname; - private final ClassFinderFilter classfilter; - - public ClassUpdater(String classname, ClassFinderFilter classfilter) { - this.classname = classname; - this.classfilter = classfilter; - } - - public void add(Class clazz, URL location) { - numberOfClasses++; - classNamesCache.add(clazz.getName()); - if ((numberOfClasses % UPDATE_EVERY) == 0) { - appendToList(classNamesCache); - classNamesCache.clear(); - } - } - - public void run() { - classNamesCache = new ArrayList<>(UPDATE_EVERY); - numberOfClasses = 0; - ClassFinder cf = new ClassFinder(); - cf.findSubclasses(classname, this, classfilter); - if (classNamesCache.size() > 0) { - appendToList(classNamesCache); - classNamesCache.clear(); - } - // last call, with empty list, to update status message - appendToList(classNamesCache); - classNamesCache = null; - classesLoaded = true; - } + /** + * @param owner + */ + public ClassSelectionDialog(Dialog owner, String title, String classname, ClassFinderFilter classfilter) { + super(owner, title, true); + initialize(); + classesLoaded = false; + this.classname = classname; + this.classfilter = classfilter; } - public static class ClassesTableModel extends AbstractTableModel { - @Serial - private static final long serialVersionUID = 1L; - - private final Vector dynamicRowData; - private final Vector staticRowData; - - public ClassesTableModel() { - dynamicRowData = new Vector<>(); - staticRowData = new Vector<>(); - } - - public String getColumnName(int col) { - return "Classname"; - } - - public int getRowCount() { - return dynamicRowData.size() + staticRowData.size(); - } - - public int getColumnCount() { - return 1; - } - - public Object getValueAt(int row, int col) { - return getRowValue(row); - } - - public boolean isCellEditable(int row, int col) { - return false; - } - - public void appendStaticRows(Collection newRows) { - if (newRows.size() > 0) { - int firstRow = staticRowData.size(); - staticRowData.addAll(newRows); - fireTableRowsInserted(firstRow, staticRowData.size() - 1); - } - } - - public void setDynamicRows(Collection rows) { - dynamicRowData.clear(); - fireTableRowsDeleted(0, dynamicRowData.size()); - if (rows.size() > 0) { - dynamicRowData.addAll(rows); - fireTableRowsInserted(0, dynamicRowData.size() - 1); - } - } - - public String getRowValue(int index) { - if (index < dynamicRowData.size()) { - return (String) dynamicRowData.get(index); - } else { - return staticRowData.get(index - dynamicRowData.size()); - } - } + public ClassSelectionDialog(Dialog owner, String title, String classname) { + this(owner, title, classname, null); } private void appendToList(List list) { @@ -194,21 +100,6 @@ public String getSelectedClassname() { return selectedClassname; } - /** - * @param owner - */ - public ClassSelectionDialog(Dialog owner, String title, String classname, ClassFinderFilter classfilter) { - super(owner, title, true); - initialize(); - classesLoaded = false; - this.classname = classname; - this.classfilter = classfilter; - } - - public ClassSelectionDialog(Dialog owner, String title, String classname) { - this(owner, title, classname, null); - } - public int doShow(Collection firstRows) { jButtonOk.setEnabled(false); synchronized (jTable) { @@ -405,4 +296,111 @@ public void valueChanged(ListSelectionEvent e) { jButtonOk.setEnabled(true); } } + + public static class ClassesTableModel extends AbstractTableModel { + @Serial + private static final long serialVersionUID = 1L; + + private final Vector dynamicRowData; + private final Vector staticRowData; + + public ClassesTableModel() { + dynamicRowData = new Vector<>(); + staticRowData = new Vector<>(); + } + + public String getColumnName(int col) { + return "Classname"; + } + + public int getRowCount() { + return dynamicRowData.size() + staticRowData.size(); + } + + public int getColumnCount() { + return 1; + } + + public Object getValueAt(int row, int col) { + return getRowValue(row); + } + + public boolean isCellEditable(int row, int col) { + return false; + } + + public void appendStaticRows(Collection newRows) { + if (newRows.size() > 0) { + int firstRow = staticRowData.size(); + staticRowData.addAll(newRows); + fireTableRowsInserted(firstRow, staticRowData.size() - 1); + } + } + + public void setDynamicRows(Collection rows) { + dynamicRowData.clear(); + fireTableRowsDeleted(0, dynamicRowData.size()); + if (rows.size() > 0) { + dynamicRowData.addAll(rows); + fireTableRowsInserted(0, dynamicRowData.size() - 1); + } + } + + public String getRowValue(int index) { + if (index < dynamicRowData.size()) { + return (String) dynamicRowData.get(index); + } else { + return staticRowData.get(index - dynamicRowData.size()); + } + } + } + + private class ClassFilter implements ClassFinderFilter { + public boolean include(Class superClazz, Class clazz) { + int modifiers = clazz.getModifiers(); + boolean doInclude = ((modifiers & (ACC_ABSTRACT | ACC_INTERFACE)) == 0); + if (doInclude) { + doInclude = !clazz.getName().equals(classname); + } + return doInclude; + } + } + + private class ClassUpdater implements Runnable, ClassFinderListener { + + private final static int UPDATE_EVERY = 1; + private final String classname; + private final ClassFinderFilter classfilter; + private int numberOfClasses; + private List classNamesCache; + + public ClassUpdater(String classname, ClassFinderFilter classfilter) { + this.classname = classname; + this.classfilter = classfilter; + } + + public void add(Class clazz, URL location) { + numberOfClasses++; + classNamesCache.add(clazz.getName()); + if ((numberOfClasses % UPDATE_EVERY) == 0) { + appendToList(classNamesCache); + classNamesCache.clear(); + } + } + + public void run() { + classNamesCache = new ArrayList<>(UPDATE_EVERY); + numberOfClasses = 0; + ClassFinder cf = new ClassFinder(); + cf.findSubclasses(classname, this, classfilter); + if (classNamesCache.size() > 0) { + appendToList(classNamesCache); + classNamesCache.clear(); + } + // last call, with empty list, to update status message + appendToList(classNamesCache); + classNamesCache = null; + classesLoaded = true; + } + } } diff --git a/src/jade/gui/GuiAgent.java b/src/jade/gui/GuiAgent.java index bd409a1..3b2a8ff 100644 --- a/src/jade/gui/GuiAgent.java +++ b/src/jade/gui/GuiAgent.java @@ -78,6 +78,54 @@ public abstract class GuiAgent extends Agent { */ private final Boolean guiEventQueueLock; + /** + * Default constructor. + */ + public GuiAgent() { + super(); + guiEventQueue = new Vector<>(); + guiEventQueueLock = Boolean.TRUE; + + // Add the GUI handler behaviour + Behaviour b = new GuiHandlerBehaviour(); + addBehaviour(b); + } + + /** + * Posts an event from the GUI thread to the agent event queue. + * + * @param e The GUI event to post. + */ + public void postGuiEvent(GuiEvent e) { + synchronized (guiEventQueueLock) { + guiEventQueue.addElement(e); + doWake(); + } + } + + /** + * Abstract method to handle posted GUI events. Subclasses of + * GuiAgent will implement their own reactions to + * GUI events starting with this method. + * + * @param ev The GUI event to handle. + */ + protected abstract void onGuiEvent(GuiEvent ev); + + ///////////////////////////////////////////////////////////////////////// + // METHODS TO POST PREDEFINED EXIT AND CLOSEGUI EVENTS IN GUI EVENT QUEUE + /*public void postExitEvent(Object g) + { + GuiEvent e = new GuiEvent(g, GuiEvent.EXIT); + postGuiEvent(e); + } + + public void postCloseGuiEvent(Object g) + { + GuiEvent e = new GuiEvent(g, GuiEvent.CLOSEGUI); + postGuiEvent(e); + }*/ + //////////////////////// // GUI HANDLER BEHAVIOUR private class GuiHandlerBehaviour extends SimpleBehaviour { @@ -124,53 +172,4 @@ public boolean done() { } } - /** - * Default constructor. - */ - public GuiAgent() { - super(); - guiEventQueue = new Vector<>(); - guiEventQueueLock = Boolean.TRUE; - - // Add the GUI handler behaviour - Behaviour b = new GuiHandlerBehaviour(); - addBehaviour(b); - } - - /** - * Posts an event from the GUI thread to the agent event queue. - * - * @param e The GUI event to post. - */ - public void postGuiEvent(GuiEvent e) { - synchronized (guiEventQueueLock) { - guiEventQueue.addElement(e); - doWake(); - } - } - - ///////////////////////////////////////////////////////////////////////// - // METHODS TO POST PREDEFINED EXIT AND CLOSEGUI EVENTS IN GUI EVENT QUEUE - /*public void postExitEvent(Object g) - { - GuiEvent e = new GuiEvent(g, GuiEvent.EXIT); - postGuiEvent(e); - } - - public void postCloseGuiEvent(Object g) - { - GuiEvent e = new GuiEvent(g, GuiEvent.CLOSEGUI); - postGuiEvent(e); - }*/ - - - /** - * Abstract method to handle posted GUI events. Subclasses of - * GuiAgent will implement their own reactions to - * GUI events starting with this method. - * - * @param ev The GUI event to handle. - */ - protected abstract void onGuiEvent(GuiEvent ev); - } diff --git a/src/jade/gui/GuiEvent.java b/src/jade/gui/GuiEvent.java index 8bd154f..5162f06 100644 --- a/src/jade/gui/GuiEvent.java +++ b/src/jade/gui/GuiEvent.java @@ -40,12 +40,11 @@ * @see GuiAgent */ public class GuiEvent { + private final List parameters; //#APIDOC_EXCLUDE_BEGIN protected Object source; - protected int type; //#APIDOC_EXCLUDE_END - - private final List parameters; + protected int type; /** * Create a GUI event. diff --git a/src/jade/gui/GuiProperties.java b/src/jade/gui/GuiProperties.java index 2c978e9..07bb1c7 100644 --- a/src/jade/gui/GuiProperties.java +++ b/src/jade/gui/GuiProperties.java @@ -36,9 +36,9 @@ */ public class GuiProperties { + public static final String ImagePath = ""; protected static UIDefaults MyDefaults; protected static GuiProperties foo = new GuiProperties(); - public static final String ImagePath = ""; static { Object[] icons = { diff --git a/src/jade/gui/ServiceDscDlg.java b/src/jade/gui/ServiceDscDlg.java index b665357..3e5d048 100644 --- a/src/jade/gui/ServiceDscDlg.java +++ b/src/jade/gui/ServiceDscDlg.java @@ -36,6 +36,7 @@ import java.awt.*; import java.util.Enumeration; import java.util.Iterator; +import java.util.Objects; import java.util.Properties; /** @@ -87,10 +88,7 @@ ServiceDescription viewSD(ServiceDescription dsc, boolean ed, boolean checkManda editable = ed; checkSlots = checkMandatorySlots; - if (dsc != null) - serviceDesc = dsc; - else - serviceDesc = new ServiceDescription(); + serviceDesc = Objects.requireNonNullElseGet(dsc, ServiceDescription::new); JPanel main = new JPanel(); main.setLayout(new BoxLayout(main, BoxLayout.Y_AXIS)); diff --git a/src/jade/gui/SimpleWindow4Agent.java b/src/jade/gui/SimpleWindow4Agent.java index a0a714c..506c165 100644 --- a/src/jade/gui/SimpleWindow4Agent.java +++ b/src/jade/gui/SimpleWindow4Agent.java @@ -9,11 +9,14 @@ import java.awt.event.WindowEvent; -/** a simple window with a text area to display informations +/** + * a simple window with a text area to display informations * and a button * the window find automaticcaly its place in the screen - * @author emmanueladam */ -public class SimpleWindow4Agent extends JFrame implements ActionListener { + * + * @author emmanueladam + */ +public class SimpleWindow4Agent extends JFrame implements ActionListener { public final static int OK_EVENT = 1; public final static int QUIT_EVENT = -1; static int nb = 0; @@ -33,22 +36,25 @@ public class SimpleWindow4Agent extends JFrame implements ActionListener { private boolean buttonActivated; - /** a simple window with a text area to display informations + /** + * a simple window with a text area to display informations * and a button * the window find automaticcaly its place in the screen - * @author emmanueladam */ + * + * @author emmanueladam + */ public SimpleWindow4Agent() { no = nb++; int widthJFrame = 450; int heightJFrame = 200; Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); - int nbWindowsByRow = (int)Math.floor(screen.getWidth()/widthJFrame); - int xx = ((no%nbWindowsByRow) * (widthJFrame+5)); - int yy = (((no/nbWindowsByRow)*(heightJFrame+10)))%((int)screen.getHeight()); + int nbWindowsByRow = (int) Math.floor(screen.getWidth() / widthJFrame); + int xx = ((no % nbWindowsByRow) * (widthJFrame + 5)); + int yy = (((no / nbWindowsByRow) * (heightJFrame + 10))) % ((int) screen.getHeight()); setBounds(xx, yy, widthJFrame, heightJFrame); buildGui(); this.addWindowListener(new WindowAdapter() { - public void windowClosing(WindowEvent windowEvent){ + public void windowClosing(WindowEvent windowEvent) { GuiEvent ev = new GuiEvent(this, QUIT_EVENT); myAgent.postGuiEvent(ev); } @@ -106,8 +112,7 @@ public void actionPerformed(ActionEvent evt) { myAgent.postGuiEvent(ev); } - public void setBackgroundTextColor(Color c) - { + public void setBackgroundTextColor(Color c) { jTextArea.setBackground(c); } @@ -116,14 +121,11 @@ public boolean isButtonActivated() { } public void setButtonActivated(boolean buttonActivated) { - if(buttonActivated) - { + if (buttonActivated) { jbutton.setEnabled(true); jbutton.setText("-- go --"); jbutton.addActionListener(this); - } - else - { + } else { jbutton.setEnabled(false); jbutton.setText("--"); jbutton.addActionListener(null); diff --git a/src/jade/gui/SingleProperty.java b/src/jade/gui/SingleProperty.java index 84d3707..f491f12 100644 --- a/src/jade/gui/SingleProperty.java +++ b/src/jade/gui/SingleProperty.java @@ -56,17 +56,17 @@ String getKey() { } /** - * Returns th value. + * To set the key. */ - String getValue() { - return this.value; + void setKey(String k) { + this.key = k; } /** - * To set the key. + * Returns th value. */ - void setKey(String k) { - this.key = k; + String getValue() { + return this.value; } /** diff --git a/src/jade/gui/TimeChooser.java b/src/jade/gui/TimeChooser.java index 0ddba89..85941c4 100644 --- a/src/jade/gui/TimeChooser.java +++ b/src/jade/gui/TimeChooser.java @@ -47,20 +47,18 @@ */ public class TimeChooser implements ActionListener { - private Date date; - private int mode; - private int retVal; - private JDialog dlg; - private JTextField year, month, day, hour, min, sec; - - JToggleButton absButton; - JToggleButton relButton; - //#APIDOC_EXCLUDE_BEGIN public static final int ABSOLUTE = 0; public static final int RELATIVE = 1; public static final int OK = 1; public static final int CANCEL = 0; + JToggleButton absButton; + JToggleButton relButton; + private Date date; + private int mode; + private int retVal; + private JDialog dlg; + private JTextField year, month, day, hour, min, sec; //#APIDOC_EXCLUDE_END /** diff --git a/src/jade/gui/TreeHelp.java b/src/jade/gui/TreeHelp.java index 6595488..9584249 100644 --- a/src/jade/gui/TreeHelp.java +++ b/src/jade/gui/TreeHelp.java @@ -42,23 +42,22 @@ public class TreeHelp extends JDialog { /** * @serial */ - private JEditorPane htmlPane; - + private final boolean playWithLineStyle = false; /** * @serial */ - private URL helpURL; + private final String lineStyle = "Angled"; //Optionally play with line styles. Possible values are //"Angled", "Horizontal", and "None" (the default). /** * @serial */ - private final boolean playWithLineStyle = false; + private JEditorPane htmlPane; /** * @serial */ - private final String lineStyle = "Angled"; + private URL helpURL; public TreeHelp(Frame owner, String title, String url) { diff --git a/src/jade/gui/VisualStringList.java b/src/jade/gui/VisualStringList.java index 71b230a..a66f3d0 100644 --- a/src/jade/gui/VisualStringList.java +++ b/src/jade/gui/VisualStringList.java @@ -60,11 +60,14 @@ **/ public class VisualStringList extends JPanel { + static String VIEW_LABEL = "View"; + static String EDIT_LABEL = "Edit"; + static String ADD_LABEL = "Add"; + static String REMOVE_LABEL = "Remove"; /** * @serial */ Component owner; - /** * @serial */ @@ -94,11 +97,6 @@ public class VisualStringList extends JPanel { */ JMenuItem removeItem; - static String VIEW_LABEL = "View"; - static String EDIT_LABEL = "Edit"; - static String ADD_LABEL = "Add"; - static String REMOVE_LABEL = "Remove"; - /** * Constructor of a panel showing a list of strings. * By default the panel is editable and all the three operations (Add - Edit - Remove) are allowed. diff --git a/src/jade/gui/help/BOOTGUI.html b/src/jade/gui/help/BOOTGUI.html index 00b801a..7508576 100644 --- a/src/jade/gui/help/BOOTGUI.html +++ b/src/jade/gui/help/BOOTGUI.html @@ -2,12 +2,12 @@ - - + + JADE 1.3 API Reference: Class DFGUI - + diff --git a/src/jade/gui/help/DFGUI.html b/src/jade/gui/help/DFGUI.html index a82b083..86fe193 100644 --- a/src/jade/gui/help/DFGUI.html +++ b/src/jade/gui/help/DFGUI.html @@ -2,12 +2,12 @@ - - + + JADE 1.3 API Reference: Class DFGUI - + diff --git a/src/jade/imtp/leap/BackEndStub.java b/src/jade/imtp/leap/BackEndStub.java index 215f5f0..9f72414 100644 --- a/src/jade/imtp/leap/BackEndStub.java +++ b/src/jade/imtp/leap/BackEndStub.java @@ -58,6 +58,60 @@ public BackEndStub(Dispatcher d, Properties props) { } } + public static final void parseCreateMediatorResponse(String responseMessage, Properties pp) { + Vector v = Specifier.parseList(responseMessage, '#'); + for (int i = 0; i < v.size(); ++i) { + String s = (String) v.elementAt(i); + if (s.length() > 0) { + try { + int index = s.indexOf('='); + String key = s.substring(0, index); + String value = s.substring(index + 1); + pp.setProperty(key, value); + } catch (Exception e) { + Logger.println("Property format error: " + s); + e.printStackTrace(); + } + String mediatorId = pp.getProperty(JICPProtocol.MEDIATOR_ID_KEY); + if (mediatorId != null) { + pp.setProperty(MicroRuntime.CONTAINER_NAME_KEY, mediatorId); + } + } + } + } + + /** + * The method encodes the create mediator request, setting all the common properties + * retrived in the passed property parameter. + * + * @param pp + * @return a StringBuffer to allow the dispatcher to add dispatcher specific properties. + */ + public static final StringBuffer encodeCreateMediatorRequest(Properties pp) { + StringBuffer sb = new StringBuffer(); + appendProp(sb, JICPProtocol.MEDIATOR_CLASS_KEY, pp.getProperty(JICPProtocol.MEDIATOR_CLASS_KEY)); + appendProp(sb, JICPProtocol.MAX_DISCONNECTION_TIME_KEY, pp.getProperty(JICPProtocol.MAX_DISCONNECTION_TIME_KEY)); + appendProp(sb, FrontEnd.REMOTE_BACK_END_ADDRESSES, pp.getProperty(FrontEnd.REMOTE_BACK_END_ADDRESSES)); + appendProp(sb, MicroRuntime.OWNER_KEY, pp.getProperty(MicroRuntime.OWNER_KEY)); + appendProp(sb, MicroRuntime.AGENTS_KEY, pp.getProperty(MicroRuntime.AGENTS_KEY)); + appendProp(sb, MicroRuntime.BE_REQUIRED_SERVICES_KEY, pp.getProperty(MicroRuntime.BE_REQUIRED_SERVICES_KEY)); + appendProp(sb, JICPProtocol.KEEP_ALIVE_TIME_KEY, pp.getProperty(JICPProtocol.KEEP_ALIVE_TIME_KEY)); + appendProp(sb, MicroRuntime.PLATFORM_KEY, pp.getProperty(MicroRuntime.PLATFORM_KEY)); + appendProp(sb, JICPProtocol.MSISDN_KEY, pp.getProperty(JICPProtocol.MSISDN_KEY)); + appendProp(sb, JICPProtocol.VERSION_KEY, pp.getProperty(JICPProtocol.VERSION_KEY)); + appendProp(sb, JICPProtocol.GET_SERVER_TIME_KEY, pp.getProperty(JICPProtocol.GET_SERVER_TIME_KEY)); + return sb; + } + + public static void appendProp(StringBuffer sb, String key, String val) { + if ((val != null) && (val.length() != 0)) { + sb.append(key); + sb.append('='); + sb.append(val); + sb.append('#'); + } + } + /** * */ @@ -192,59 +246,5 @@ protected void handlePostponedCommandExpired(Command c, ICPException exception) MicroRuntime.notifyFailureToSender(msg, sender, "Cannot deliver message in due time" + cause); } } - - public static final void parseCreateMediatorResponse(String responseMessage, Properties pp) { - Vector v = Specifier.parseList(responseMessage, '#'); - for (int i = 0; i < v.size(); ++i) { - String s = (String) v.elementAt(i); - if (s.length() > 0) { - try { - int index = s.indexOf('='); - String key = s.substring(0, index); - String value = s.substring(index + 1); - pp.setProperty(key, value); - } catch (Exception e) { - Logger.println("Property format error: " + s); - e.printStackTrace(); - } - String mediatorId = pp.getProperty(JICPProtocol.MEDIATOR_ID_KEY); - if (mediatorId != null) { - pp.setProperty(MicroRuntime.CONTAINER_NAME_KEY, mediatorId); - } - } - } - } - - /** - * The method encodes the create mediator request, setting all the common properties - * retrived in the passed property parameter. - * - * @param pp - * @return a StringBuffer to allow the dispatcher to add dispatcher specific properties. - */ - public static final StringBuffer encodeCreateMediatorRequest(Properties pp) { - StringBuffer sb = new StringBuffer(); - appendProp(sb, JICPProtocol.MEDIATOR_CLASS_KEY, pp.getProperty(JICPProtocol.MEDIATOR_CLASS_KEY)); - appendProp(sb, JICPProtocol.MAX_DISCONNECTION_TIME_KEY, pp.getProperty(JICPProtocol.MAX_DISCONNECTION_TIME_KEY)); - appendProp(sb, FrontEnd.REMOTE_BACK_END_ADDRESSES, pp.getProperty(FrontEnd.REMOTE_BACK_END_ADDRESSES)); - appendProp(sb, MicroRuntime.OWNER_KEY, pp.getProperty(MicroRuntime.OWNER_KEY)); - appendProp(sb, MicroRuntime.AGENTS_KEY, pp.getProperty(MicroRuntime.AGENTS_KEY)); - appendProp(sb, MicroRuntime.BE_REQUIRED_SERVICES_KEY, pp.getProperty(MicroRuntime.BE_REQUIRED_SERVICES_KEY)); - appendProp(sb, JICPProtocol.KEEP_ALIVE_TIME_KEY, pp.getProperty(JICPProtocol.KEEP_ALIVE_TIME_KEY)); - appendProp(sb, MicroRuntime.PLATFORM_KEY, pp.getProperty(MicroRuntime.PLATFORM_KEY)); - appendProp(sb, JICPProtocol.MSISDN_KEY, pp.getProperty(JICPProtocol.MSISDN_KEY)); - appendProp(sb, JICPProtocol.VERSION_KEY, pp.getProperty(JICPProtocol.VERSION_KEY)); - appendProp(sb, JICPProtocol.GET_SERVER_TIME_KEY, pp.getProperty(JICPProtocol.GET_SERVER_TIME_KEY)); - return sb; - } - - public static void appendProp(StringBuffer sb, String key, String val) { - if ((val != null) && (val.length() != 0)) { - sb.append(key); - sb.append('='); - sb.append(val); - sb.append('#'); - } - } } diff --git a/src/jade/imtp/leap/Command.java b/src/jade/imtp/leap/Command.java index 17c4ccf..989d823 100644 --- a/src/jade/imtp/leap/Command.java +++ b/src/jade/imtp/leap/Command.java @@ -46,14 +46,6 @@ public class Command { * Unspecified object id */ public static final int DUMMY_ID = -1; - - /** - * Command identifier code for response command. - */ - - // Lower limit for service and node management related commands - static final int SERVICE_BASE = 0; - // Service and node management related command IDs public static final int GET_PLATFORM_NAME = 1; public static final int ADD_NODE = 2; @@ -71,11 +63,15 @@ public class Command { public static final int SERVICE_MANAGER_ADD_REPLICA = 14; public static final int SERVICE_MANAGER_UPDATE_COUNTERS = 15; public static final int PLATFORM_MANAGER_DEAD = 16; - public static final int OK = 1; public static final int ERROR = 2; public static final int FORWARD = 37; + /** + * Command identifier code for response command. + */ + // Lower limit for service and node management related commands + static final int SERVICE_BASE = 0; /** * Code defining the type of command. */ diff --git a/src/jade/imtp/leap/CommandDispatcher.java b/src/jade/imtp/leap/CommandDispatcher.java index c285137..04f3754 100644 --- a/src/jade/imtp/leap/CommandDispatcher.java +++ b/src/jade/imtp/leap/CommandDispatcher.java @@ -55,15 +55,13 @@ * @version 1.0 */ class CommandDispatcher implements StubHelper, ICP.Listener { - private static final String MAIN_PROTO_CLASS = "main-proto-class"; - /** * The default name for new instances of the class * CommandDispatcher that have not get an unique name by * their container yet. */ protected static final String DEFAULT_NAME = "Default"; - + private static final String MAIN_PROTO_CLASS = "main-proto-class"; private static final boolean enableMultiplePlatforms; /** @@ -76,42 +74,39 @@ class CommandDispatcher implements StubHelper, ICP.Listener { */ protected static Map dispatchers = new HashMap(); - private String platformName; + static { + enableMultiplePlatforms = "true".equals(System.getProperty("jade.enable.multiple.platforms")); + } + private final Logger myLogger = Logger.getMyLogger(getClass().getName()); /** * The unique name of this command dispatcher used to avoid loops in * the forwarding mechanism. */ protected String name; - /** * The transport address of the default router. Commands that cannot * be dispatched directly will be sent to this address. */ protected TransportAddress routerTA = null; - - /** * This hashtable maps the IDs of the objects remotized by this * command dispatcher to the skeletons for these objects. It is used * when a command is received from a remote JVM. */ protected Map skeletons = new HashMap(); - /** * This hashtable maps the objects remotized by this command * dispatcher to their IDs. It is used when a stub of a remotized * object must be built to be sent to a remote JVM. */ protected Map ids = new HashMap(); - /** * A counter that is used for determining IDs for remotized objects. * Everytime a new object is registered by the command dispatcher it * gets the value of this field as ID and the field is increased. */ protected int nextID; - /** * The pool of ICP objects used by this command dispatcher to * actually send/receive data over the network. It is a table that @@ -119,29 +114,35 @@ class CommandDispatcher implements StubHelper, ICP.Listener { * to a list of ICPs supporting that protocol. */ protected Map icps = new HashMap(); - /** * The transport addresses the ICPs managed by this command * dispatcher are listening for commands on. */ protected List addresses = new ArrayList(); - /** * The URLs corresponding to the local transport addresses. */ protected List urls = new ArrayList(); - + private String platformName; /** - The stub for the platform service manager. This stub will be - shared by all nodes within this Java virtual Machine. + * The stub for the platform service manager. This stub will be + * shared by all nodes within this Java virtual Machine. */ private PlatformManager thePlatformManager = null; - - private final Logger myLogger = Logger.getMyLogger(getClass().getName()); - - static { - enableMultiplePlatforms = "true".equals(System.getProperty("jade.enable.multiple.platforms")); + /** + * A sole constructor. To get a command dispatcher the constructor + * should not be called directly but the static create and + * getDispatcher methods should be used. Thereby the + * existence of a singleton instance of the command dispatcher will + * be guaranteed. + */ + private CommandDispatcher() { + // Set a temporary name. Will be substituted as soon as the first + // container attached to this CommandDispatcher will receive a + // unique name from the main. + name = DEFAULT_NAME; + nextID = 1; } /** @@ -149,6 +150,7 @@ class CommandDispatcher implements StubHelper, ICP.Listener { * Such instance is created if necessary. * If no platform name is specified or the enableMultiplePlatforms flag is not set, then use the default * CommandDispatcher + * * @return the singleton instance of the CommandDispatcher for the indicated platform. */ public synchronized static final CommandDispatcher getDispatcher(String name) throws IMTPException { @@ -184,21 +186,6 @@ private void setPlatformName(String name) { platformName = name; } - /** - * A sole constructor. To get a command dispatcher the constructor - * should not be called directly but the static create and - * getDispatcher methods should be used. Thereby the - * existence of a singleton instance of the command dispatcher will - * be guaranteed. - */ - private CommandDispatcher() { - // Set a temporary name. Will be substituted as soon as the first - // container attached to this CommandDispatcher will receive a - // unique name from the main. - name = DEFAULT_NAME; - nextID = 1; - } - synchronized PlatformManager getPlatformManagerProxy(Profile p) throws IMTPException { if (thePlatformManager == null) { @@ -300,12 +287,12 @@ void setRouterAddress(String url) { * (among those specified) to which dispatching succeeds. * * @param destTAs a list of transport addresses where the command - * dispatcher should try to dispatch the command. + * dispatcher should try to dispatch the command. * @param command the command that is to be dispatched. * @return a response command from the receiving container. - * throws DispatcherException if an error occurs during dispatching. + * throws DispatcherException if an error occurs during dispatching. * @throws UnreachableException if none of the destination addresses - * is reachable. + * is reachable. */ public Command dispatchCommand(List destTAs, Command command) throws DispatcherException, UnreachableException { // DEBUG @@ -352,16 +339,16 @@ private boolean isLocal(List destTAs) { * specified transport addresses (the first where dispatching * succeeds) directly or through the router. * - * @param destTAs a list of transport addresses where the command - * dispatcher should try to dispatch the command. + * @param destTAs a list of transport addresses where the command + * dispatcher should try to dispatch the command. * @param commandPayload the serialized command that is to be - * dispatched. - * @param origin a String object describing the origin of - * the command to be dispatched. + * dispatched. + * @param origin a String object describing the origin of + * the command to be dispatched. * @return a response command from the receiving container. * throws DispatcherException if an error occurs during dispatching. * @throws UnreachableException if none of the destination addresses - * is reachable. + * is reachable. */ private Command dispatchSerializedCommand(List destTAs, byte[] commandPayload, boolean requireFreshConnection, String origin) throws DispatcherException, UnreachableException { // Be sure that the destination addresses are correctly specified @@ -405,23 +392,23 @@ private Command dispatchSerializedCommand(List destTAs, byte[] commandPayload, b * specified transport addresses (the first where dispatching * succeeds) directly. * - * @param destTAs a list of transport addresses where the command - * dispatcher should try to dispatch the command. + * @param destTAs a list of transport addresses where the command + * dispatcher should try to dispatch the command. * @param commandPayload the serialized command that is to be - * dispatched. + * dispatched. * @return a serialized response command from the receiving * container. * @throws UnreachableException if none of the destination addresses - * is reachable. + * is reachable. */ private byte[] dispatchDirectly(List destTAs, byte[] commandPayload, boolean requireFreshConnection) throws UnreachableException { // Loop on destinaltion addresses (No need to check again // that the list of addresses is not-null and not-empty) UnreachableException lastException = null; - for (int i = 0; i < destTAs.size(); i++) { + for (Object destTA : destTAs) { try { - return send((TransportAddress) destTAs.get(i), commandPayload, requireFreshConnection); + return send((TransportAddress) destTA, commandPayload, requireFreshConnection); } catch (UnreachableException ue) { lastException = ue; // Can't send command to this address --> try the next one @@ -442,17 +429,17 @@ private byte[] dispatchDirectly(List destTAs, byte[] commandPayload, boolean req * specified transport addresses (the first where dispatching * succeeds) through the router. * - * @param destTAs a list of transport addresses where the command - * dispatcher should try to dispatch the command. + * @param destTAs a list of transport addresses where the command + * dispatcher should try to dispatch the command. * @param commandPayload the serialized command that is to be - * dispatched. - * @param origin a String object describing the origin of - * the command to be dispatched. + * dispatched. + * @param origin a String object describing the origin of + * the command to be dispatched. * @return a serialized response command from the receiving * container. * throws DispatcherException if an error occurs during dispatching. * @throws UnreachableException if none of the destination addresses - * is reachable. + * is reachable. */ private byte[] dispatchThroughRouter(List destTAs, byte[] commandPayload, boolean requireFreshConnection, String origin) throws DispatcherException, UnreachableException { // Build a FORWARD command @@ -474,10 +461,10 @@ private byte[] dispatchThroughRouter(List destTAs, byte[] commandPayload, boolea * command dispatcher throws the corresponding exception locally. * * @param response the resonse comman from the receiving container. - * throws DispatcherException if an error occurs on the remote site - * during dispatching. + * throws DispatcherException if an error occurs on the remote site + * during dispatching. * @throws UnreachableException if the destination address is not - * reachable. + * reachable. */ protected void checkRemoteExceptions(Command response) throws DispatcherException, UnreachableException { if (response.getCode() == Command.ERROR) { @@ -579,8 +566,8 @@ private TransportAddress initMainTA(Profile p) throws IMTPException { * Adds (and activates) an ICP to this command dispatcher. * * @param peer the ICP to add. - * param args the arguments required by the ICP for the activation. - * These arguments are ICP specific. + * param args the arguments required by the ICP for the activation. + * These arguments are ICP specific. */ public void addICP(ICP peer, String peerID, Profile p) { try { @@ -626,12 +613,12 @@ TransportProtocol getProtocol(String protoName) { * @param remoteObject the object whose ID should be returned. * @return the ID of the reomte object. * @throws RuntimeException if the specified object is not - * remotized by this command dispatcher. + * remotized by this command dispatcher. */ public int getID(Object remoteObject) throws IMTPException { Integer id = (Integer) ids.get(remoteObject); if (id != null) { - return id.intValue(); + return id; } throw new IMTPException("specified object is not remotized by this command dispatcher."); @@ -691,10 +678,10 @@ protected TransportAddress stringToAddr(String url) throws DispatcherException { /** * Registers the specified skeleton to the command dispatcher. * - * @param skeleton a skeleton to be managed by the command - * dispatcher. + * @param skeleton a skeleton to be managed by the command + * dispatcher. * @param remotizedObject the remote object related to the specified - * skeleton. + * skeleton. */ public synchronized void registerSkeleton(Skeleton skeleton, Object remotizedObject) throws IMTPException { Integer id = null; @@ -716,7 +703,7 @@ public synchronized void registerSkeleton(Skeleton skeleton, Object remotizedObj * Deregisters the specified remote object from the command dispatcher. * * @param remoteObject the remote object related to the specified - * skeleton. + * skeleton. */ public synchronized void deregisterSkeleton(final Object remoteObject) { if (myLogger.isLoggable(Logger.FINE)) { @@ -731,15 +718,13 @@ public synchronized void deregisterSkeleton(final Object remoteObject) { // JVM it needs some time to broadcast the termination of this node // to its replicas (if any) --> asynchronously deregister the skeleton after // a while - Thread t = new Thread() { - public void run() { - try { - Thread.sleep(1000); - } catch (InterruptedException ignored) { - } - removeRemoteObject(remoteObject); + Thread t = new Thread(() -> { + try { + Thread.sleep(1000); + } catch (InterruptedException ignored) { } - }; + removeRemoteObject(remoteObject); + }); t.start(); } } @@ -788,14 +773,14 @@ public Stub buildLocalStub(Object remotizedObject) throws IMTPException { * Selects a suitable peer and sends the specified serialized command * to the specified transport address. * - * @param ta the transport addresses where the command should be - * sent. + * @param ta the transport addresses where the command should be + * sent. * @param commandPayload the serialized command that is to be - * sent. + * sent. * @return a serialized response command from the receiving * container. * @throws UnreachableException if the destination address is not - * reachable. + * reachable. */ private byte[] send(TransportAddress ta, byte[] commandPayload, boolean requireFreshConnection) throws UnreachableException { @@ -860,7 +845,7 @@ private void shutDown() { * deserialize it and launch processing of the command. * * @param commandPayload the command to be deserialized and - * processed. + * processed. * @return a byte array containing the serialized response * command. * throws LEAPSerializationException if the command cannot be diff --git a/src/jade/imtp/leap/FrontEndStub.java b/src/jade/imtp/leap/FrontEndStub.java index 90cb375..1cd0071 100644 --- a/src/jade/imtp/leap/FrontEndStub.java +++ b/src/jade/imtp/leap/FrontEndStub.java @@ -41,6 +41,58 @@ public FrontEndStub(Dispatcher d) { super(d); } + public static final String encodeCreateMediatorResponse(Properties pp) { + StringBuffer sb = new StringBuffer(); + appendProp(sb, Profile.PLATFORM_ID, pp); + appendProp(sb, MicroRuntime.PLATFORM_ADDRESSES_KEY, pp); + appendProp(sb, JICPProtocol.MEDIATOR_ID_KEY, pp); + appendProp(sb, JICPProtocol.LOCAL_HOST_KEY, pp); + appendProp(sb, Profile.AGENTS, pp, false); + return sb.toString(); + } + + public static final String encodeProperties(Properties pp) { + StringBuffer sb = new StringBuffer(); + Enumeration en = pp.keys(); + while (en.hasMoreElements()) { + String key = (String) en.nextElement(); + appendProp(sb, key, pp, en.hasMoreElements()); + } + return sb.toString(); + } + + private static void appendProp(StringBuffer sb, String key, Properties pp) { + appendProp(sb, key, pp, true); + } + + private static void appendProp(StringBuffer sb, String key, Properties pp, boolean appendHash) { + Object val = pp.get(key); + if (val != null) { + String strVal = val.toString(); + if (strVal.length() > 0) { + sb.append(key); + sb.append('='); + sb.append(val); + if (appendHash) { + sb.append('#'); + } + } + } + } + + public static final Properties parseCreateMediatorRequest(String s) throws ICPException { + StringTokenizer st = new StringTokenizer(s, "=#"); + Properties p = new Properties(); + while (st.hasMoreTokens()) { + String key = st.nextToken(); + if (!st.hasMoreTokens()) { + throw new ICPException("Wrong initialization properties format."); + } + p.setProperty(key, st.nextToken()); + } + return p; + } + /** * */ @@ -169,57 +221,5 @@ public List removePendingMessages(MessageTemplate template) { return messages; } } - - public static final String encodeCreateMediatorResponse(Properties pp) { - StringBuffer sb = new StringBuffer(); - appendProp(sb, Profile.PLATFORM_ID, pp); - appendProp(sb, MicroRuntime.PLATFORM_ADDRESSES_KEY, pp); - appendProp(sb, JICPProtocol.MEDIATOR_ID_KEY, pp); - appendProp(sb, JICPProtocol.LOCAL_HOST_KEY, pp); - appendProp(sb, Profile.AGENTS, pp, false); - return sb.toString(); - } - - public static final String encodeProperties(Properties pp) { - StringBuffer sb = new StringBuffer(); - Enumeration en = pp.keys(); - while (en.hasMoreElements()) { - String key = (String) en.nextElement(); - appendProp(sb, key, pp, en.hasMoreElements()); - } - return sb.toString(); - } - - private static void appendProp(StringBuffer sb, String key, Properties pp) { - appendProp(sb, key, pp, true); - } - - private static void appendProp(StringBuffer sb, String key, Properties pp, boolean appendHash) { - Object val = pp.get(key); - if (val != null) { - String strVal = val.toString(); - if (strVal.length() > 0) { - sb.append(key); - sb.append('='); - sb.append(val); - if (appendHash) { - sb.append('#'); - } - } - } - } - - public static final Properties parseCreateMediatorRequest(String s) throws ICPException { - StringTokenizer st = new StringTokenizer(s, "=#"); - Properties p = new Properties(); - while (st.hasMoreTokens()) { - String key = st.nextToken(); - if (!st.hasMoreTokens()) { - throw new ICPException("Wrong initialization properties format."); - } - p.setProperty(key, st.nextToken()); - } - return p; - } } diff --git a/src/jade/imtp/leap/ICP.java b/src/jade/imtp/leap/ICP.java index c63f697..3a13a78 100644 --- a/src/jade/imtp/leap/ICP.java +++ b/src/jade/imtp/leap/ICP.java @@ -46,25 +46,6 @@ */ public interface ICP { - /** - * Callback interface to be notified of command arrivals over this - * ICP. - */ - interface Listener { - - /** - * Handle a received (still serialized) command object, i.e. deserialize it - * and launch processing of the command. - * - * @param cmdPayload the command to be deserialized and processed - * @return a byte array containing the serialized response command - * exception LEAPSerializationException if an error occurs during the - * LEAP surrogate serialization mechanism - */ - byte[] handleCommand(byte[] cmdPayload) throws LEAPSerializationException; - } // End of Listener interface - - /** * Start listening for platform management commands */ @@ -84,5 +65,23 @@ interface Listener { * Returns the protocol supported by this ICP */ TransportProtocol getProtocol(); + + /** + * Callback interface to be notified of command arrivals over this + * ICP. + */ + interface Listener { + + /** + * Handle a received (still serialized) command object, i.e. deserialize it + * and launch processing of the command. + * + * @param cmdPayload the command to be deserialized and processed + * @return a byte array containing the serialized response command + * exception LEAPSerializationException if an error occurs during the + * LEAP surrogate serialization mechanism + */ + byte[] handleCommand(byte[] cmdPayload) throws LEAPSerializationException; + } // End of Listener interface } diff --git a/src/jade/imtp/leap/JICP/BIBEDispatcher.java b/src/jade/imtp/leap/JICP/BIBEDispatcher.java index 47cce9d..94894f6 100644 --- a/src/jade/imtp/leap/JICP/BIBEDispatcher.java +++ b/src/jade/imtp/leap/JICP/BIBEDispatcher.java @@ -43,25 +43,25 @@ public class BIBEDispatcher extends Thread implements BEConnectionManager, Dispa private static final int UNREACHABLE = 0; private final int frontEndStatus = UNREACHABLE; + private final Logger myLogger = Logger.getMyLogger(getClass().getName()); + private final Object shutdownLock = new Object(); + protected InpConnectionHolder inpHolder = new InpConnectionHolder(); + protected OutConnectionHolder outHolder = new OutConnectionHolder(); private long maxDisconnectionTime; private long keepAliveTime; private long lastReceivedTime; - private JICPMediatorManager myMediatorManager; private String myID; - private byte lastSid = 0x0f; private int inpCnt = 0; private boolean active = true; - - protected InpConnectionHolder inpHolder = new InpConnectionHolder(); - protected OutConnectionHolder outHolder = new OutConnectionHolder(); - private MicroSkeleton mySkel = null; private FrontEndStub myStub = null; private BackEndContainer myContainer = null; - - private final Logger myLogger = Logger.getMyLogger(getClass().getName()); + ////////////////////////////////////////////////// + // The embedded Thread handling outgoing commands + ////////////////////////////////////////////////// + private JICPPacket lastResponse; /** * Constructor declaration @@ -156,8 +156,6 @@ protected final BackEndSkel startBackEndContainer(Properties props) throws ICPEx } } - private final Object shutdownLock = new Object(); - /** * Shutdown self initiated or forced by the JICPServer this * BackEndContainer is attached to. @@ -212,6 +210,10 @@ public boolean handleIncomingConnection(Connection c, JICPPacket pkt, InetAddres return true; } + //////////////////////////////////////////////// + // BEConnectionManager interface implementation + //////////////////////////////////////////////// + public void tick(long currentTime) { if (keepAliveTime > 0) { if ((currentTime - lastReceivedTime) > (keepAliveTime + 60000)) { @@ -241,10 +243,6 @@ public void tick(long currentTime) { } } - //////////////////////////////////////////////// - // BEConnectionManager interface implementation - //////////////////////////////////////////////// - /** * Return a stub of the remote FrontEnd that is connected to the * local BackEnd. @@ -258,7 +256,6 @@ public FrontEnd getFrontEnd(BackEnd be, Properties props) throws IMTPException { return myStub; } - /** * Make this BackEndDispatcher terminate. */ @@ -346,11 +343,6 @@ private synchronized JICPPacket dispatchPacket(JICPPacket pkt, boolean flush, in } } - ////////////////////////////////////////////////// - // The embedded Thread handling outgoing commands - ////////////////////////////////////////////////// - private JICPPacket lastResponse; - public void run() { lastResponse = null; int status = 0; @@ -456,6 +448,13 @@ private JICPPacket readPacket(Connection c) throws IOException { return pkt; } + private void close(Connection c) { + try { + c.close(); + } catch (IOException ioe) { + } + } + /** * Inner class InpConnectionHolder. * Wrapper for the connection used to deliver commands to the FrontEnd @@ -529,7 +528,6 @@ private synchronized void stopWatchDog() { } } // END of inner class InpConnectionHolder - /** * Inner class OutConnectionHolder * Wrapper for the connection used to receive commands from the FrontEnd @@ -538,18 +536,6 @@ protected class OutConnectionHolder { private Connection myConnection; private boolean connectionRefreshed; - private synchronized void setConnection(Connection c) { - if (myLogger.isLoggable(Logger.FINE)) - myLogger.log(Logger.FINE, myID + " - New output connection."); - - if (myConnection != null) { - close(myConnection); - } - myConnection = c; - connectionRefreshed = true; - notifyAll(); - } - private synchronized Connection getConnection() { while (myConnection == null) { try { @@ -566,6 +552,18 @@ private synchronized Connection getConnection() { return myConnection; } + private synchronized void setConnection(Connection c) { + if (myLogger.isLoggable(Logger.FINE)) + myLogger.log(Logger.FINE, myID + " - New output connection."); + + if (myConnection != null) { + close(myConnection); + } + myConnection = c; + connectionRefreshed = true; + notifyAll(); + } + public synchronized void resetConnection() { if (!connectionRefreshed) { if (myConnection != null) { @@ -579,12 +577,5 @@ private synchronized boolean isConnected() { return myConnection != null; } } // END of inner class OutConnectionHolder - - private void close(Connection c) { - try { - c.close(); - } catch (IOException ioe) { - } - } } diff --git a/src/jade/imtp/leap/JICP/BIFEDispatcher.java b/src/jade/imtp/leap/JICP/BIFEDispatcher.java index f3549fa..184353a 100644 --- a/src/jade/imtp/leap/JICP/BIFEDispatcher.java +++ b/src/jade/imtp/leap/JICP/BIFEDispatcher.java @@ -41,11 +41,16 @@ public class BIFEDispatcher implements FEConnectionManager, Dispatcher, TimerLis protected static final byte INP = (byte) 1; protected static final byte OUT = (byte) 0; private static final int RESPONSE_TIMEOUT = 30000; + private final Logger myLogger = Logger.getMyLogger(getClass().getName()); protected String myMediatorClass = "jade.imtp.leap.JICP.BIBEDispatcher"; - private MicroSkeleton mySkel = null; - private BackEndStub myStub = null; // Variables related to the connection with the Mediator protected TransportAddress mediatorTA; + protected Connection outConnection; + protected InputManager myInputManager; + protected boolean refreshingInput = false; + protected boolean refreshingOutput = false; + private MicroSkeleton mySkel = null; + private BackEndStub myStub = null; private String myMediatorID; private long retryTime = JICPProtocol.DEFAULT_RETRY_TIME; private long maxDisconnectionTime = JICPProtocol.DEFAULT_MAX_DISCONNECTION_TIME; @@ -53,24 +58,24 @@ public class BIFEDispatcher implements FEConnectionManager, Dispatcher, TimerLis private long connectionDropDownTime = -1; private Timer kaTimer, cdTimer; private Properties props; - protected Connection outConnection; - protected InputManager myInputManager; private ConnectionListener myConnectionListener; private boolean active = true; private boolean connectionDropped = false; private boolean waitingForFlush = false; - protected boolean refreshingInput = false; - protected boolean refreshingOutput = false; private byte lastSid = 0x0f; private int outCnt = 0; private Thread terminator; private String beAddrsText; private String[] backEndAddresses; - private final Logger myLogger = Logger.getMyLogger(getClass().getName()); ////////////////////////////////////////////// // FEConnectionManager interface implementation ////////////////////////////////////////////// + // These variables are only used within the InputManager class, + // but are declared externally since they must "survive" when + // an InputManager is replaced + private JICPPacket lastResponse = null; + private int cnt = 0; /** * Connect to a remote BackEnd and return a stub to communicate with it @@ -185,6 +190,9 @@ public BackEnd getBackEnd(FrontEnd fe, Properties props) throws IMTPException { } } + ////////////////////////////////////////////// + // Dispatcher interface implementation + ////////////////////////////////////////////// /** * Make this BIFEDispatcher terminate. @@ -282,10 +290,6 @@ private JICPConnection createBackEnd() throws IMTPException { throw new IMTPException("Error creating the BackEnd."); } - ////////////////////////////////////////////// - // Dispatcher interface implementation - ////////////////////////////////////////////// - /** * Deliver a serialized command to the BackEnd. * @@ -348,106 +352,6 @@ public synchronized byte[] dispatch(byte[] payload, boolean flush, int oldSessio } } - // These variables are only used within the InputManager class, - // but are declared externally since they must "survive" when - // an InputManager is replaced - private JICPPacket lastResponse = null; - private int cnt = 0; - - /** - * Inner class InputManager. - * This class is responsible for serving incoming commands - */ - private class InputManager extends Thread { - - private int myId; - private Connection myConnection = null; - - public void run() { - myId = cnt++; - if (myLogger.isLoggable(Logger.INFO)) { - myLogger.log(Logger.INFO, "IM-" + myId + " started"); - } - - int status = 0; - connectInp(); - //connect(INP); - try { - while (isConnected()) { - status = 0; - JICPPacket pkt = myConnection.readPacket(); - // HACK!: For some misterious reason just after a BE re-creation it - // may happen that we get a RESPONSE packet here. Waiting for a cleaner - // solution, we just ignore it and go back reading the next incoming - // command - if (pkt.getType() == JICPProtocol.RESPONSE_TYPE) { - myLogger.log(Logger.WARNING, "Unexpected response packet received on INP connection. Ignore it"); - continue; - } - status = 1; - byte sid = pkt.getSessionID(); - if (sid == lastSid) { - // Duplicated packet - if (myLogger.isLoggable(Logger.WARNING)) { - myLogger.log(Logger.WARNING, "Duplicated packet from BE: pkt-type=" + pkt.getType() + " info=" + pkt.getInfo() + " SID=" + sid); - } - pkt = lastResponse; - } else { - if (pkt.getType() == JICPProtocol.KEEP_ALIVE_TYPE) { - // Keep-alive - pkt = new JICPPacket(JICPProtocol.RESPONSE_TYPE, JICPProtocol.DEFAULT_INFO, null); - } else { - // Incoming command - if (myLogger.isLoggable(Logger.FINE)) { - myLogger.log(Logger.FINE, "Incoming command received " + sid + " pkt-type=" + pkt.getType()); - } - byte[] rspData = mySkel.handleCommand(pkt.getData()); - if (myLogger.isLoggable(Logger.FINER)) { - myLogger.log(Logger.FINER, "Incoming command served " + sid); - } - pkt = new JICPPacket(JICPProtocol.RESPONSE_TYPE, JICPProtocol.DEFAULT_INFO, rspData); - } - pkt.setSessionID(sid); - if (Thread.currentThread() == terminator) { - // Attach the TERMINATED_INFO flag to the response - pkt.setTerminatedInfo(true); - } - lastSid = sid; - lastResponse = pkt; - } - status = 2; - writePacket(pkt, myConnection); - status = 3; - } - } catch (IOException ioe) { - if (active) { - myLogger.log(Logger.WARNING, "IOException IC[" + status + "]" + ioe); - refreshInp(); - } - } - - if (myLogger.isLoggable(Logger.INFO)) { - myLogger.log(Logger.INFO, "IM-" + myId + " terminated"); - } - } - - private void close() { - try { - myConnection.close(); - } catch (Exception e) { - } - myConnection = null; - } - - private final void setConnection(Connection c) { - myConnection = c; - } - - private final boolean isConnected() { - return myConnection != null; - } - } // END of inner class InputManager - /** * Close the current InputManager (if any) and start a new one */ @@ -787,10 +691,6 @@ protected void writePacket(JICPPacket pkt, Connection c) throws IOException { } } - //////////////////////////////////////////////////////////////// - // Keep-alive and connection drop-down mechanism management - //////////////////////////////////////////////////////////////// - /** * Refresh the keep-alive timer. * Mutual exclusion with doTimeOut() @@ -805,6 +705,10 @@ private synchronized void updateKeepAlive() { } } + //////////////////////////////////////////////////////////////// + // Keep-alive and connection drop-down mechanism management + //////////////////////////////////////////////////////////////// + /** * Refresh the connection drop-down timer. * Mutual exclusion with doTimeOut() @@ -1000,5 +904,99 @@ private void handleBENotFound() { myConnectionListener.handleConnectionEvent(ConnectionListener.BE_NOT_FOUND, null); } } + + /** + * Inner class InputManager. + * This class is responsible for serving incoming commands + */ + private class InputManager extends Thread { + + private int myId; + private Connection myConnection = null; + + public void run() { + myId = cnt++; + if (myLogger.isLoggable(Logger.INFO)) { + myLogger.log(Logger.INFO, "IM-" + myId + " started"); + } + + int status = 0; + connectInp(); + //connect(INP); + try { + while (isConnected()) { + status = 0; + JICPPacket pkt = myConnection.readPacket(); + // HACK!: For some misterious reason just after a BE re-creation it + // may happen that we get a RESPONSE packet here. Waiting for a cleaner + // solution, we just ignore it and go back reading the next incoming + // command + if (pkt.getType() == JICPProtocol.RESPONSE_TYPE) { + myLogger.log(Logger.WARNING, "Unexpected response packet received on INP connection. Ignore it"); + continue; + } + status = 1; + byte sid = pkt.getSessionID(); + if (sid == lastSid) { + // Duplicated packet + if (myLogger.isLoggable(Logger.WARNING)) { + myLogger.log(Logger.WARNING, "Duplicated packet from BE: pkt-type=" + pkt.getType() + " info=" + pkt.getInfo() + " SID=" + sid); + } + pkt = lastResponse; + } else { + if (pkt.getType() == JICPProtocol.KEEP_ALIVE_TYPE) { + // Keep-alive + pkt = new JICPPacket(JICPProtocol.RESPONSE_TYPE, JICPProtocol.DEFAULT_INFO, null); + } else { + // Incoming command + if (myLogger.isLoggable(Logger.FINE)) { + myLogger.log(Logger.FINE, "Incoming command received " + sid + " pkt-type=" + pkt.getType()); + } + byte[] rspData = mySkel.handleCommand(pkt.getData()); + if (myLogger.isLoggable(Logger.FINER)) { + myLogger.log(Logger.FINER, "Incoming command served " + sid); + } + pkt = new JICPPacket(JICPProtocol.RESPONSE_TYPE, JICPProtocol.DEFAULT_INFO, rspData); + } + pkt.setSessionID(sid); + if (Thread.currentThread() == terminator) { + // Attach the TERMINATED_INFO flag to the response + pkt.setTerminatedInfo(true); + } + lastSid = sid; + lastResponse = pkt; + } + status = 2; + writePacket(pkt, myConnection); + status = 3; + } + } catch (IOException ioe) { + if (active) { + myLogger.log(Logger.WARNING, "IOException IC[" + status + "]" + ioe); + refreshInp(); + } + } + + if (myLogger.isLoggable(Logger.INFO)) { + myLogger.log(Logger.INFO, "IM-" + myId + " terminated"); + } + } + + private void close() { + try { + myConnection.close(); + } catch (Exception e) { + } + myConnection = null; + } + + private final void setConnection(Connection c) { + myConnection = c; + } + + private final boolean isConnected() { + return myConnection != null; + } + } // END of inner class InputManager } diff --git a/src/jade/imtp/leap/JICP/Connection.java b/src/jade/imtp/leap/JICP/Connection.java index a8a0ef0..5b7220a 100644 --- a/src/jade/imtp/leap/JICP/Connection.java +++ b/src/jade/imtp/leap/JICP/Connection.java @@ -36,25 +36,26 @@ import java.io.IOException; /** - Abstract base class representing a generic connection that can be used - to send/receive JICP packets over the network. - @author Giovanni Caire - TILAB + * Abstract base class representing a generic connection that can be used + * to send/receive JICP packets over the network. + * + * @author Giovanni Caire - TILAB */ public abstract class Connection { public static int socketCnt = 0; /** - Read a JICPPacket from the connection + * Read a JICPPacket from the connection */ public abstract JICPPacket readPacket() throws IOException; /** - Write a JICPPacket on the connection + * Write a JICPPacket on the connection */ public abstract int writePacket(JICPPacket pkt) throws IOException; /** - Close the connection + * Close the connection */ public abstract void close() throws IOException; diff --git a/src/jade/imtp/leap/JICP/ConnectionPool.java b/src/jade/imtp/leap/JICP/ConnectionPool.java index 3b04a04..b77bbc6 100644 --- a/src/jade/imtp/leap/JICP/ConnectionPool.java +++ b/src/jade/imtp/leap/JICP/ConnectionPool.java @@ -83,11 +83,7 @@ ConnectionWrapper acquire(TransportAddress ta, boolean requireFreshConnection) t throw new ICPException("Pool closed"); } - l = connections.get(url); - if (l == null) { - l = new ArrayList<>(); - connections.put(url, l); - } + l = connections.computeIfAbsent(url, k -> new ArrayList<>()); if (requireFreshConnection) { // We are checking a given destination. This means that this destination may be no longer valid diff --git a/src/jade/imtp/leap/JICP/FrontEndDispatcher.java b/src/jade/imtp/leap/JICP/FrontEndDispatcher.java index 7297e5b..e89846d 100644 --- a/src/jade/imtp/leap/JICP/FrontEndDispatcher.java +++ b/src/jade/imtp/leap/JICP/FrontEndDispatcher.java @@ -39,12 +39,22 @@ */ public class FrontEndDispatcher implements FEConnectionManager, Dispatcher, TimerListener, Runnable { private static final int KEEP_ALIVE_RESPONSE_TIMEOUT = 10000; - + // Lock used to synchronize sections managing timers for KEEP_ALIVE and DROP_DOWN. + // Such sections never contain possibly blocking code --> Cannot cause deadlock + private final Object timersLock = new Object(); + private final Object connectionLock = new Object(); + // Lock used to synchronize threads waiting for a response with the ConnectionReader thread + // receiving data from the network --> Cannot cause deadlock + private final Object responseLock = new Object(); + private final Logger myLogger = Logger.getMyLogger(getClass().getName()); + public boolean refreshingConnection = false; + protected String myMediatorClass = "jade.imtp.leap.nio.BackEndDispatcher"; + protected long connectionTimeout = JICPProtocol.DEFAULT_CONNECTION_TIMEOUT; + // Host and port to bind the local side of the connection with the BE (useful in case more than one Network Interface is available) + protected String bindHost; + protected int bindPort; private MicroSkeleton mySkel = null; private BackEndStub myStub = null; - - protected String myMediatorClass = "jade.imtp.leap.nio.BackEndDispatcher"; - // Variables related to the connection with the Mediator private Properties myProperties; private String[] backEndAddresses; @@ -54,29 +64,13 @@ public class FrontEndDispatcher implements FEConnectionManager, Dispatcher, Time private long retryTime = JICPProtocol.DEFAULT_RETRY_TIME; private long maxDisconnectionTime = JICPProtocol.DEFAULT_MAX_DISCONNECTION_TIME; private long keepAliveTime = JICPProtocol.DEFAULT_KEEP_ALIVE_TIME; - protected long connectionTimeout = JICPProtocol.DEFAULT_CONNECTION_TIMEOUT; private long responseTimeoutOffset = JICPProtocol.DEFAULT_RESPONSE_TIMEOUT_OFFSET; private long connectionDropDownTime = -1; - - // Host and port to bind the local side of the connection with the BE (useful in case more than one Network Interface is available) - protected String bindHost; - protected int bindPort; - private Timer kaTimer, cdTimer; - // Lock used to synchronize sections managing timers for KEEP_ALIVE and DROP_DOWN. - // Such sections never contain possibly blocking code --> Cannot cause deadlock - private final Object timersLock = new Object(); - private IncomingCommandServer myCommandServer; private ConnectionReader myConnectionReader; private Connection myConnection = null; - public boolean refreshingConnection = false; - private final Object connectionLock = new Object(); - // Lock used to synchronize threads waiting for a response with the ConnectionReader thread - // receiving data from the network --> Cannot cause deadlock - private final Object responseLock = new Object(); private ConnectionListener myConnectionListener; - private boolean active = false; private boolean connectionDropped = false; private boolean waitingForFlush = false; @@ -85,14 +79,36 @@ public class FrontEndDispatcher implements FEConnectionManager, Dispatcher, Time private JICPPacket lastOutgoingResponse = null; private Thread terminator; private int reconnectionAttemptCnt = 0; - private int verbosity = 1; - private final Logger myLogger = Logger.getMyLogger(getClass().getName()); ////////////////////////////////////////////// // FEConnectionManager interface implementation ////////////////////////////////////////////// + // This variable is only used within the ConnectionReader class, + // but is declared externally since it must "survive" when + // a ConnectionReader is replaced + private int cnt = 0; + + /*private void manageRemoteConfig() throws IMTPException { + String remoteConfigHost = myProperties.getProperty(MicroRuntime.REMOTE_CONFIG_HOST_KEY); + String remoteConfigPort = myProperties.getProperty(MicroRuntime.REMOTE_CONFIG_PORT_KEY); + if (remoteConfigHost != null && remoteConfigPort != null) { + // Remote configuration options specified: Retrieve connectivity related + // configurations from the indicated host and port + JICPConnection c = getConnection(new JICPAddress(remoteConfigHost, remoteConfigPort, myMediatorID, "")); + JICPPacket pkt = new JICPPacket(JICPProtocol.GET_CONFIG_OPTIONS_TYPE, JICPProtocol.DEFAULT_INFO, null); + writePacket(pkt, c); + pkt = c.readPacket(); + c.close(); + ... + String replyMsg = new String(pkt.getData()); + if (pkt.getType() != JICPProtocol.ERROR_TYPE) { + // BackEnd creation successful + BackEndStub.parseCreateMediatorResponse(replyMsg, myProperties); + + } + }*/ /** * Connect to a remote BackEnd and return a stub to communicate with it @@ -266,26 +282,6 @@ public BackEnd getBackEnd(FrontEnd fe, Properties props) throws IMTPException { throw new IMTPException("Connection error", icpe); } } - - /*private void manageRemoteConfig() throws IMTPException { - String remoteConfigHost = myProperties.getProperty(MicroRuntime.REMOTE_CONFIG_HOST_KEY); - String remoteConfigPort = myProperties.getProperty(MicroRuntime.REMOTE_CONFIG_PORT_KEY); - if (remoteConfigHost != null && remoteConfigPort != null) { - // Remote configuration options specified: Retrieve connectivity related - // configurations from the indicated host and port - JICPConnection c = getConnection(new JICPAddress(remoteConfigHost, remoteConfigPort, myMediatorID, "")); - JICPPacket pkt = new JICPPacket(JICPProtocol.GET_CONFIG_OPTIONS_TYPE, JICPProtocol.DEFAULT_INFO, null); - writePacket(pkt, c); - pkt = c.readPacket(); - c.close(); - ... - String replyMsg = new String(pkt.getData()); - if (pkt.getType() != JICPProtocol.ERROR_TYPE) { - // BackEnd creation successful - BackEndStub.parseCreateMediatorResponse(replyMsg, myProperties); - - } - }*/ /** * Send the CREATE_MEDIATOR command with the necessary parameter @@ -401,6 +397,10 @@ private void initServerTimeOffset(Connection con) { } } + ////////////////////////////////////////////// + // Dispatcher interface implementation + ////////////////////////////////////////////// + /** * Make this FrontEndDispatcher terminate. */ @@ -434,10 +434,6 @@ public synchronized void shutdown() { } } - ////////////////////////////////////////////// - // Dispatcher interface implementation - ////////////////////////////////////////////// - /** * Deliver a serialized command to the BackEnd. * @@ -505,7 +501,6 @@ public synchronized byte[] dispatch(byte[] payload, boolean flush, int oldSessio } } - ////////////////////////////////////////////////// // Connection reader ////////////////////////////////////////////////// @@ -515,88 +510,6 @@ private void startConnectionReader(Connection c) { myConnectionReader.start(); } - // This variable is only used within the ConnectionReader class, - // but is declared externally since it must "survive" when - // a ConnectionReader is replaced - private int cnt = 0; - - /** - * Inner class ConnectionReader. - * This class is responsible for reading incoming packets (incoming commands and responses - * to outgoing commands) - */ - private class ConnectionReader extends Thread { - private int myId; - private Connection myConnection = null; - - public ConnectionReader(Connection c) { - super(); - myConnection = c; - //#MIDP_EXCLUDE_BEGIN - setName("ConnectionReader-" + myId); - //#MIDP_EXCLUDE_END - } - - public void run() { - myId = cnt++; - myLogger.log(Logger.INFO, myMediatorID + " - CR-" + myId + " started"); - - try { - while (isConnected()) { - JICPPacket pkt = myConnection.readPacket(); - myLogger.log(getLevel(Logger.FINER), myMediatorID + " - CR-" + myId + " packet received, SID=" + pkt.getSessionID()); - - pkt = handleIncomingPacket(pkt); - if (pkt != null) { - writePacket(pkt, myConnection); - } - } - } catch (IOException ioe) { - synchronized (connectionLock) { - if (active && !connectionDropped) { - myLogger.log(Logger.WARNING, myMediatorID + " - CR Exception ", ioe); - // This synchronized check avoids that an old connection reader suddenly realizes that its connection is down - // and tries to refresh an already restored connection - if (this == FrontEndDispatcher.this.myConnectionReader) { - // Unblock any Thread waiting for a response. It will behave as if the response timeout was expired - notifyOutgoingResponseReceived(null); - handleDisconnection(); - } - } - } - } - - myLogger.log(Logger.INFO, myMediatorID + " - CR-" + myId + " terminated"); - } - - - private JICPPacket handleIncomingPacket(JICPPacket pkt) { - switch (pkt.getType()) { - case JICPProtocol.COMMAND_TYPE -> { - myLogger.log(getLevel(Logger.FINE), myMediatorID + " - CR-" + myId + " COMMAND received from BE, SID=" + pkt.getSessionID()); - updateTimers(); - serveCommand(pkt); - myLogger.log(getLevel(Logger.FINEST), myMediatorID + " - CR-" + myId + " Incoming command passed to asynchronous command server"); - } - case JICPProtocol.KEEP_ALIVE_TYPE -> { - // Server-side initiated keep-alive - updateKeepAlive(); - return handleIncomingKeepAlive(pkt); - } - case JICPProtocol.RESPONSE_TYPE, JICPProtocol.ERROR_TYPE -> { - myLogger.log(getLevel(Logger.FINER), myMediatorID + " - CR-" + myId + " RESPONSE/ERROR received from BE. " + pkt.getSessionID()); - notifyOutgoingResponseReceived(pkt); - } - default -> myLogger.log(Logger.WARNING, myMediatorID + " - Unexpected incoming packet type: " + pkt.getType()); - } - return null; - } - - private boolean isConnected() { - return myConnection != null; - } - } // END of inner class ConnectionReader - private JICPPacket handleIncomingCommand(JICPPacket cmd) { // Incoming command if (myLogger.isLoggable(Logger.FINE)) { @@ -673,7 +586,6 @@ private void notifyOutgoingResponseReceived(JICPPacket rsp) { } } - /////////////////////////////////////////////////////// // Reconnection related methods /////////////////////////////////////////////////////// @@ -810,7 +722,6 @@ private void waitABit(long period) { } } - //////////////////////////////////////////////////////////////// // Keep-alive and connection drop-down mechanism management //////////////////////////////////////////////////////////////// @@ -987,7 +898,6 @@ protected void undrop() throws ICPException { throw new ConnectionDropped(); } - ////////////////////////////////////////////////////////////////// // Asynchronous command serving part ////////////////////////////////////////////////////////////////// @@ -999,6 +909,97 @@ private void serveCommand(JICPPacket command) { myCommandServer.serve(command); } + //#J2ME_EXCLUDE_BEGIN + private java.util.logging.Level getLevel(java.util.logging.Level level) { + if (verbosity > 0) { + if (level == Logger.FINE) { + return Logger.INFO; + } else if (level == Logger.FINER) { + return verbosity >= 2 ? Logger.INFO : Logger.FINE; + } else if (level == Logger.FINEST) { + return verbosity >= 3 ? Logger.INFO : verbosity == 2 ? Logger.FINE : Logger.FINER; + } + } + return level; + } + + /** + * Inner class ConnectionReader. + * This class is responsible for reading incoming packets (incoming commands and responses + * to outgoing commands) + */ + private class ConnectionReader extends Thread { + private int myId; + private Connection myConnection = null; + + public ConnectionReader(Connection c) { + super(); + myConnection = c; + //#MIDP_EXCLUDE_BEGIN + setName("ConnectionReader-" + myId); + //#MIDP_EXCLUDE_END + } + + public void run() { + myId = cnt++; + myLogger.log(Logger.INFO, myMediatorID + " - CR-" + myId + " started"); + + try { + while (isConnected()) { + JICPPacket pkt = myConnection.readPacket(); + myLogger.log(getLevel(Logger.FINER), myMediatorID + " - CR-" + myId + " packet received, SID=" + pkt.getSessionID()); + + pkt = handleIncomingPacket(pkt); + if (pkt != null) { + writePacket(pkt, myConnection); + } + } + } catch (IOException ioe) { + synchronized (connectionLock) { + if (active && !connectionDropped) { + myLogger.log(Logger.WARNING, myMediatorID + " - CR Exception ", ioe); + // This synchronized check avoids that an old connection reader suddenly realizes that its connection is down + // and tries to refresh an already restored connection + if (this == FrontEndDispatcher.this.myConnectionReader) { + // Unblock any Thread waiting for a response. It will behave as if the response timeout was expired + notifyOutgoingResponseReceived(null); + handleDisconnection(); + } + } + } + } + + myLogger.log(Logger.INFO, myMediatorID + " - CR-" + myId + " terminated"); + } + + + private JICPPacket handleIncomingPacket(JICPPacket pkt) { + switch (pkt.getType()) { + case JICPProtocol.COMMAND_TYPE -> { + myLogger.log(getLevel(Logger.FINE), myMediatorID + " - CR-" + myId + " COMMAND received from BE, SID=" + pkt.getSessionID()); + updateTimers(); + serveCommand(pkt); + myLogger.log(getLevel(Logger.FINEST), myMediatorID + " - CR-" + myId + " Incoming command passed to asynchronous command server"); + } + case JICPProtocol.KEEP_ALIVE_TYPE -> { + // Server-side initiated keep-alive + updateKeepAlive(); + return handleIncomingKeepAlive(pkt); + } + case JICPProtocol.RESPONSE_TYPE, JICPProtocol.ERROR_TYPE -> { + myLogger.log(getLevel(Logger.FINER), myMediatorID + " - CR-" + myId + " RESPONSE/ERROR received from BE. " + pkt.getSessionID()); + notifyOutgoingResponseReceived(pkt); + } + default -> myLogger.log(Logger.WARNING, myMediatorID + " - Unexpected incoming packet type: " + pkt.getType()); + } + return null; + } + + private boolean isConnected() { + return myConnection != null; + } + } // END of inner class ConnectionReader + /** * Inner class IncomingCommandServer * Serving incoming commands asynchronously is necessary to support commands whose serving process @@ -1077,20 +1078,6 @@ private synchronized void releaseCurrentCommand() { notifyAll(); } } // END of inner class IncomingCommandServer - - //#J2ME_EXCLUDE_BEGIN - private java.util.logging.Level getLevel(java.util.logging.Level level) { - if (verbosity > 0) { - if (level == Logger.FINE) { - return Logger.INFO; - } else if (level == Logger.FINER) { - return verbosity >= 2 ? Logger.INFO : Logger.FINE; - } else if (level == Logger.FINEST) { - return verbosity >= 3 ? Logger.INFO : verbosity == 2 ? Logger.FINE : Logger.FINER; - } - } - return level; - } //#J2ME_EXCLUDE_END /*#J2ME_INCLUDE_BEGIN diff --git a/src/jade/imtp/leap/JICP/JICPAddress.java b/src/jade/imtp/leap/JICP/JICPAddress.java index 37c0329..4ff62ec 100644 --- a/src/jade/imtp/leap/JICP/JICPAddress.java +++ b/src/jade/imtp/leap/JICP/JICPAddress.java @@ -38,6 +38,7 @@ /** * Class declaration + * * @author Giovanni Caire - TILAB */ public class JICPAddress implements TransportAddress { @@ -54,6 +55,7 @@ public JICPAddress() { /** * Constructor declaration + * * @param host * @param port * @param file @@ -68,6 +70,7 @@ public JICPAddress(String host, String port, String file, String anchor) { /** * Method declaration + * * @return * @see */ @@ -77,6 +80,7 @@ public String getProto() { /** * Method declaration + * * @return * @see */ @@ -86,6 +90,7 @@ public String getHost() { /** * Method declaration + * * @return * @see */ @@ -95,6 +100,7 @@ public String getPort() { /** * Method declaration + * * @return * @see */ @@ -104,6 +110,7 @@ public String getFile() { /** * Method declaration + * * @return * @see */ @@ -120,7 +127,7 @@ public boolean equals(Object rhs) { } public String toString() { - StringBuffer address = new StringBuffer(); + StringBuilder address = new StringBuilder(); address.append(JICPProtocol.NAME); address.append("://"); diff --git a/src/jade/imtp/leap/JICP/JICPClient.java b/src/jade/imtp/leap/JICP/JICPClient.java index de1ad38..ebcf387 100644 --- a/src/jade/imtp/leap/JICP/JICPClient.java +++ b/src/jade/imtp/leap/JICP/JICPClient.java @@ -46,17 +46,18 @@ /** * Class declaration + * * @author Giovanni Caire - TILAB * @author Ronnie Taib - Motorola * @author Steffen Rusitschka - Siemens */ class JICPClient { + private static final Logger log = Logger.getMyLogger(JICPClient.class.getName()); private final TransportProtocol protocol; private final ConnectionFactory connFactory; private final ConnectionPool pool; private final int readTimeout; - private static final Logger log = Logger.getMyLogger(JICPClient.class.getName()); /** * Constructor declaration @@ -70,11 +71,11 @@ public JICPClient(TransportProtocol tp, ConnectionFactory f, int max, int rt) { /** * Send a command to this transport address - * @param ta the address to send the command to + * + * @param ta the address to send the command to * @param dataType the type of data as defined in the JICPPeer - * @param data the command + * @param data the command * @return a byte array corresponding to the answer - * * @throws ICPException */ public byte[] send(TransportAddress ta, byte dataType, byte[] data, boolean requireFreshConnection) throws ICPException { @@ -175,7 +176,7 @@ public void shutdown() { } /** - Called by the JICPPeer ticker at each tick + * Called by the JICPPeer ticker at each tick */ public void tick(long currentTime) { pool.clearExpiredConnections(currentTime); diff --git a/src/jade/imtp/leap/JICP/JICPCompressor.java b/src/jade/imtp/leap/JICP/JICPCompressor.java index 9955c3c..7ae1e0b 100644 --- a/src/jade/imtp/leap/JICP/JICPCompressor.java +++ b/src/jade/imtp/leap/JICP/JICPCompressor.java @@ -39,6 +39,16 @@ * * @author Steffen Rusitschka, Siemens AG, CT IC 6 * @author Dmitri Toropov, Siemens AG, CT IC 6 + *

+ * Byte Array Compressor + *

+ * The (de-)compression algorthm is quite simple and memory efficient. + *

+ * the compression is done using a dictionary of words. words are detected + * by predefined seperators (see isSep()). the dictionary of the words is + * the (de-)compression array itself. + * @author Steffen Rusitschka, Siemens AG, CT IC 6 + * @author Dmitri Toropov, Siemens AG, CT IC 6 */ /** @@ -69,9 +79,9 @@ public class JICPCompressor { // internal fields private static final int RLE_FLUSH = 0x100; + private final int count = 0; private int rleOldValue = RLE_FLUSH; private int rleOccurrence = 0; - private final int count = 0; private byte[] ba; @@ -83,6 +93,43 @@ private static boolean isSep(int value) { value == '_'); } + /** + * compress() + * + * algorithm: + * + * if during compression a word is detected, its position inside the array + * is stored in the wordIndexes[] array. but only, if the word itself was not + * found in the array before. if so, only a magic byte (WORD_MAGIC=255) and the index of + * the word in the wordIndexes[] array is stored as a byte. the magic byte is + * encoded as (255, 255). this limits the number of words that are possible + * inside the wordIndexs[] array to 254 (=MAX_WORD constant). + * + */ + public static byte[] compress(byte[] ba) { + if (ba == null) + return null; + else { + return new JICPCompressor().compressHelper(ba); + } + } + + /** + * decompress() + * + * algorithm: + * + * during decompression, the wordIndexes[] array will be built. this is done by reading + * the compressed array, decode it and look for words. if a magic byte (WORD_MAGIC=255) is detected, + * it will be decoded to a "real" 255 if the following byte is also 255 (255, 255 - sequence). + * if the following byte is not 255, it is treated as an index in the wordIndexes[] array. + * the index stored inside there is used as the beginning of a word. this word will be copied + * to the end of the decoded stream. the end of the word is detected by a separator (see + * isSep()). + */ + public static byte[] decompress(byte[] cba) { + return new JICPCompressor().decompressHelper(cba); + } /** * run length encoding write @@ -152,28 +199,6 @@ private void setValue(int index, int value) { ba[index] = (byte) value; } - - /** - * compress() - * - * algorithm: - * - * if during compression a word is detected, its position inside the array - * is stored in the wordIndexes[] array. but only, if the word itself was not - * found in the array before. if so, only a magic byte (WORD_MAGIC=255) and the index of - * the word in the wordIndexes[] array is stored as a byte. the magic byte is - * encoded as (255, 255). this limits the number of words that are possible - * inside the wordIndexs[] array to 254 (=MAX_WORD constant). - * - */ - public static byte[] compress(byte[] ba) { - if (ba == null) - return null; - else { - return new JICPCompressor().compressHelper(ba); - } - } - private byte[] compressHelper(byte[] uba) { int[] wordIndexes = new int[MAX_WORDS]; @@ -254,24 +279,6 @@ private byte[] compressHelper(byte[] uba) { return baos.toByteArray(); } - - /** - * decompress() - * - * algorithm: - * - * during decompression, the wordIndexes[] array will be built. this is done by reading - * the compressed array, decode it and look for words. if a magic byte (WORD_MAGIC=255) is detected, - * it will be decoded to a "real" 255 if the following byte is also 255 (255, 255 - sequence). - * if the following byte is not 255, it is treated as an index in the wordIndexes[] array. - * the index stored inside there is used as the beginning of a word. this word will be copied - * to the end of the decoded stream. the end of the word is detected by a separator (see - * isSep()). - */ - public static byte[] decompress(byte[] cba) { - return new JICPCompressor().decompressHelper(cba); - } - private byte[] decompressHelper(byte[] cba) { int[] wordIndexes = new int[MAX_WORDS]; int wordIndex = 0; diff --git a/src/jade/imtp/leap/JICP/JICPCompressor1.java b/src/jade/imtp/leap/JICP/JICPCompressor1.java index 2090b68..37ae51c 100644 --- a/src/jade/imtp/leap/JICP/JICPCompressor1.java +++ b/src/jade/imtp/leap/JICP/JICPCompressor1.java @@ -39,6 +39,45 @@ private static boolean isSep(int value) { value == '_'); } + /** + * compress() + *

+ * algorithm: + *

+ * if during compression a word is detected, its position inside the array + * is stored in the wordIndexes[] array. but only, if the word itself was not + * found in the array before. if so, only a magic byte (WORD_MAGIC) and the index of + * the word in the wordIndexes[] array is stored as a byte. the magic byte is + * encoded as (WORD_MAGIC, 255). this limits the number of words that are possible + * inside the wordIndexes[] array to 254 (=MAX_WORD constant). + */ + public static byte[] compress(byte[] ba) { + if (ba == null) { + return null; + } + return new JICPCompressor1().compressHelper(ba); + } + + /** + * decompress() + *

+ * algorithm: + *

+ * during decompression, the wordIndexes[] array will be built. this is done by + * reading the compressed array, decode it and look for words. if a magic byte + * (WORD_MAGIC) is detected, it will be decoded to a "real" WORD_MAGIC if the + * following byte is 255 (WORD_MAGIC, 255 - sequence). if the following byte + * is not 255, it is treated as an index in the wordIndexes[] array. + * the index stored inside there is used as the beginning of a word. this word + * will be copied to the end of the decoded stream. the end of the word is + * detected by a separator (see isSep()). + */ + public static byte[] decompress(byte[] cba) { + if (cba == null) { + return null; + } + return new JICPCompressor1().decompressHelper(cba); + } /** * run length encoding write @@ -106,27 +145,6 @@ private void setValue(int index, int value) { ba[index] = (byte) value; } - - /** - * compress() - * - * algorithm: - * - * if during compression a word is detected, its position inside the array - * is stored in the wordIndexes[] array. but only, if the word itself was not - * found in the array before. if so, only a magic byte (WORD_MAGIC) and the index of - * the word in the wordIndexes[] array is stored as a byte. the magic byte is - * encoded as (WORD_MAGIC, 255). this limits the number of words that are possible - * inside the wordIndexes[] array to 254 (=MAX_WORD constant). - * - */ - public static byte[] compress(byte[] ba) { - if (ba == null) { - return null; - } - return new JICPCompressor1().compressHelper(ba); - } - private byte[] compressHelper(byte[] uba) { int[] wordIndexes = new int[MAX_WORDS]; @@ -215,28 +233,6 @@ private byte[] compressHelper(byte[] uba) { return baos.toByteArray(); } - - /** - * decompress() - * - * algorithm: - * - * during decompression, the wordIndexes[] array will be built. this is done by - * reading the compressed array, decode it and look for words. if a magic byte - * (WORD_MAGIC) is detected, it will be decoded to a "real" WORD_MAGIC if the - * following byte is 255 (WORD_MAGIC, 255 - sequence). if the following byte - * is not 255, it is treated as an index in the wordIndexes[] array. - * the index stored inside there is used as the beginning of a word. this word - * will be copied to the end of the decoded stream. the end of the word is - * detected by a separator (see isSep()). - */ - public static byte[] decompress(byte[] cba) { - if (cba == null) { - return null; - } - return new JICPCompressor1().decompressHelper(cba); - } - private byte[] decompressHelper(byte[] cba) { // System.out.print("" + cba.length + " -> "); diff --git a/src/jade/imtp/leap/JICP/JICPCompressor2.java b/src/jade/imtp/leap/JICP/JICPCompressor2.java index fad2c62..b022eb5 100644 --- a/src/jade/imtp/leap/JICP/JICPCompressor2.java +++ b/src/jade/imtp/leap/JICP/JICPCompressor2.java @@ -40,6 +40,7 @@ /** * Class declaration + * * @author Dmitri Toropov - Siemens AG */ @@ -49,7 +50,6 @@ class JICPCompressor2 { * * @param sym - byte to check * @return true if sym is separator, false otherwise - * */ public static boolean is_separator(byte sym) { return (sym <= 32) || (sym == '(') || (sym == ')') || (sym == '@') || (sym == ':') || (sym == '/') || (sym == '!'); @@ -88,7 +88,6 @@ private static int min(int a, int b) { * * @param data the data to compress * @return compressed data - * */ public static byte[] compress(byte[] data) { if (data == null) return null; @@ -208,7 +207,6 @@ public static byte[] compress(byte[] data) { * * @param data the data to compress * @return compressed data - * */ public static byte[] decompress(byte[] data) { if (data == null) return null; diff --git a/src/jade/imtp/leap/JICP/JICPCompressor3.java b/src/jade/imtp/leap/JICP/JICPCompressor3.java index 91a04eb..b2831c6 100644 --- a/src/jade/imtp/leap/JICP/JICPCompressor3.java +++ b/src/jade/imtp/leap/JICP/JICPCompressor3.java @@ -25,9 +25,9 @@ public class JICPCompressor3 { // internal fields private static final int RLE_FLUSH = 0x100; + private final int count = 0; private int rleOldValue = RLE_FLUSH; private int rleOccurrence = 0; - private final int count = 0; private byte[] ba; @@ -39,6 +39,38 @@ private static boolean isSep(int value) { value == '_'); } + /** + * compress() + *

+ * algorithm: + *

+ * if during compression a word is detected, its position inside the array + * is stored in the wordIndexes[] array. but only, if the word itself was not + * found in the array before. if so, only a magic byte (WORD_MAGIC=255) and the index of + * the word in the wordIndexes[] array is stored as a byte. the magic byte is + * encoded as (255, 255). this limits the number of words that are possible + * inside the wordIndexs[] array to 254 (=MAX_WORD constant). + */ + public static byte[] compress(byte[] ba) { + return new JICPCompressor3().compressHelper(ba); + } + + /** + * decompress() + *

+ * algorithm: + *

+ * during decompression, the wordIndexes[] array will be built. this is done by reading + * the compressed array, decode it and look for words. if a magic byte (WORD_MAGIC=255) is detected, + * it will be decoded to a "real" 255 if the following byte is also 255 (255, 255 - sequence). + * if the following byte is not 255, it is treated as an index in the wordIndexes[] array. + * the index stored inside there is used as the beginning of a word. this word will be copied + * to the end of the decoded stream. the end of the word is detected by a separator (see + * isSep()). + */ + public static byte[] decompress(byte[] cba) { + return new JICPCompressor3().decompressHelper(cba); + } /** * run length encoding write @@ -108,24 +140,6 @@ private void setValue(int index, int value) { ba[index] = (byte) value; } - - /** - * compress() - * - * algorithm: - * - * if during compression a word is detected, its position inside the array - * is stored in the wordIndexes[] array. but only, if the word itself was not - * found in the array before. if so, only a magic byte (WORD_MAGIC=255) and the index of - * the word in the wordIndexes[] array is stored as a byte. the magic byte is - * encoded as (255, 255). this limits the number of words that are possible - * inside the wordIndexs[] array to 254 (=MAX_WORD constant). - * - */ - public static byte[] compress(byte[] ba) { - return new JICPCompressor3().compressHelper(ba); - } - private byte[] compressHelper(byte[] uba) { int[] wordIndexes = new int[MAX_WORDS]; @@ -206,24 +220,6 @@ private byte[] compressHelper(byte[] uba) { return baos.toByteArray(); } - - /** - * decompress() - * - * algorithm: - * - * during decompression, the wordIndexes[] array will be built. this is done by reading - * the compressed array, decode it and look for words. if a magic byte (WORD_MAGIC=255) is detected, - * it will be decoded to a "real" 255 if the following byte is also 255 (255, 255 - sequence). - * if the following byte is not 255, it is treated as an index in the wordIndexes[] array. - * the index stored inside there is used as the beginning of a word. this word will be copied - * to the end of the decoded stream. the end of the word is detected by a separator (see - * isSep()). - */ - public static byte[] decompress(byte[] cba) { - return new JICPCompressor3().decompressHelper(cba); - } - private byte[] decompressHelper(byte[] cba) { int[] wordIndexes = new int[MAX_WORDS]; int wordIndex = 0; diff --git a/src/jade/imtp/leap/JICP/JICPConnection.java b/src/jade/imtp/leap/JICP/JICPConnection.java index 5196371..62ad9e5 100644 --- a/src/jade/imtp/leap/JICP/JICPConnection.java +++ b/src/jade/imtp/leap/JICP/JICPConnection.java @@ -49,14 +49,15 @@ /** * Class declaration + * * @author Steffen Rusitschka - Siemens */ public class JICPConnection extends Connection { + protected static Logger myLogger = Logger.getMyLogger(JICPConnection.class.getName()); //#MIDP_EXCLUDE_BEGIN protected Socket sc; - protected static Logger myLogger = Logger.getMyLogger(JICPConnection.class.getName()); //#MIDP_EXCLUDE_END /*#MIDP_INCLUDE_BEGIN protected StreamConnection sc; @@ -127,6 +128,13 @@ public JICPConnection(TransportAddress ta, int timeout, String bindHost, int bin #MIDP_INCLUDE_END*/ } + /** + * Constructor declaration + */ + public JICPConnection(Socket s) { + sc = s; + } + //#MIDP_EXCLUDE_BEGIN public void setReadTimeout(int timeout) throws IOException { if (sc != null) { @@ -137,13 +145,6 @@ public void setReadTimeout(int timeout) throws IOException { protected void bindSocket(Socket sc) { // Just do nothing. } - - /** - * Constructor declaration - */ - public JICPConnection(Socket s) { - sc = s; - } //#MIDP_EXCLUDE_END public JICPPacket readPacket() throws IOException { @@ -176,6 +177,7 @@ public int writePacket(JICPPacket pkt) throws IOException { } /** + * */ protected OutputStream getOutputStream() throws IOException { return new ByteArrayOutputStream() { @@ -206,6 +208,7 @@ public void close() throws IOException { } /** + * */ public void close() throws IOException { IOException firstExc = null; @@ -242,6 +245,7 @@ public void close() throws IOException { //#MIDP_EXCLUDE_BEGIN /** + * */ public String getRemoteHost() throws Exception { return sc.getInetAddress().getHostAddress(); diff --git a/src/jade/imtp/leap/JICP/JICPMediator.java b/src/jade/imtp/leap/JICP/JICPMediator.java index c51a2aa..075fcc4 100644 --- a/src/jade/imtp/leap/JICP/JICPMediator.java +++ b/src/jade/imtp/leap/JICP/JICPMediator.java @@ -44,17 +44,17 @@ */ public interface JICPMediator { /** - Retrieve the ID of this mediator + * Retrieve the ID of this mediator */ String getID(); /** - Initialize this JICPMediator + * Initialize this JICPMediator */ void init(JICPMediatorManager mgr, String id, Properties props) throws ICPException; /** - Kill this JICPMediator + * Kill this JICPMediator */ void kill(); @@ -63,9 +63,10 @@ public interface JICPMediator { * entity. * This is called by the JICPServer this Mediator is attached to * as soon as the mediated entity (re)connects. - * @param c the connection to the mediated entity - * @param pkt the packet that was sent by the mediated entity when - * opening this connection + * + * @param c the connection to the mediated entity + * @param pkt the packet that was sent by the mediated entity when + * opening this connection * @param addr the address of the mediated entity * @param port the local port used by the mediated entity * @return an indication to the JICPMediatorManager to keep the @@ -78,16 +79,17 @@ public interface JICPMediator { * This is called by the JICPServer this Mediator is attached to * when a JICPPacket is received having the recipient-ID field * set to the ID of this JICPMediator. - * @param p the JICPPacket + * + * @param p the JICPPacket * @param addr the address of the mediated entity * @param port the local port used by the mediated entity */ JICPPacket handleJICPPacket(JICPPacket p, InetAddress addr, int port) throws ICPException; /** - This is periodically called by the JICPMediatorManager and should - be used by a JICPMediator to evaluate the elapsed time without - the need of a dedicated thread or timer. + * This is periodically called by the JICPMediatorManager and should + * be used by a JICPMediator to evaluate the elapsed time without + * the need of a dedicated thread or timer. */ void tick(long time); } diff --git a/src/jade/imtp/leap/JICP/JICPMediatorManager.java b/src/jade/imtp/leap/JICP/JICPMediatorManager.java index aad2cca..6f08f9c 100644 --- a/src/jade/imtp/leap/JICP/JICPMediatorManager.java +++ b/src/jade/imtp/leap/JICP/JICPMediatorManager.java @@ -46,17 +46,17 @@ public interface JICPMediatorManager { String LEAP_PROPERTY_FILE_DEFAULT = "leap.properties"; /** - Deregister a given mediator from this JICPMediatorManager + * Deregister a given mediator from this JICPMediatorManager */ void deregisterMediator(String mediatorId); /** - Retrieve the local host of this JICPMediatorManager + * Retrieve the local host of this JICPMediatorManager */ String getLocalHost(); /** - Retrieve the local port of this JICPMediatorManager + * Retrieve the local port of this JICPMediatorManager */ int getLocalPort(); } diff --git a/src/jade/imtp/leap/JICP/JICPPacket.java b/src/jade/imtp/leap/JICP/JICPPacket.java index 3138851..d42636f 100644 --- a/src/jade/imtp/leap/JICP/JICPPacket.java +++ b/src/jade/imtp/leap/JICP/JICPPacket.java @@ -44,27 +44,25 @@ /** * This class is the JICP data packet representation along * with methods for reading from and writing to dataXXputStreams. + * * @author Ronnie Taib - Motorola * @author Steffen Rusitschka - Siemens AG */ public class JICPPacket { public static final int MAX_SIZE = 10000000; - + private static final Logger logger = Logger.getJADELogger("jade.imtp.leap.JICP.JICPPacket"); /** * The type of data included in the packet */ private byte type; - /** * Bit encoded information about the content of the packet: */ private byte info; - /** * An optional identifier for the session this packet belongs to */ private byte sessionID = -1; - /** * An optional field indicating the actual recipient for this JICPPacket. * - A JICPServer receiving a JICPPacket from a remote container @@ -74,14 +72,11 @@ public class JICPPacket { * final destination to forward the packet. */ private String recipientID; - /** * The payload data itself, as a byte array */ private byte[] data; - private static final Logger logger = Logger.getJADELogger("jade.imtp.leap.JICP.JICPPacket"); - /** * Empty constructor */ @@ -90,6 +85,7 @@ private JICPPacket() { /** * Constructor. + * * @param type The type of data included in the packet * @param data The data itself, as a byte array. */ @@ -99,6 +95,7 @@ public JICPPacket(byte type, byte info, byte[] data) { /** * Constructor used to set the recipientID. + * * @param type The type of data included in the packet * @param data The data itself, as a byte array. */ @@ -119,6 +116,85 @@ public JICPPacket(String explanation, Exception e) { } /** + * This static method reads from a given + * DataInputStream and returns the JICPPacket that + * it reads. The input stream is not opened nor closed by this method. + * + * @param in The InputStream to read from + * @throws IOException May send a large bunch of exceptions, mainly in the IO + * package. + */ + public static JICPPacket readFrom(InputStream in) throws IOException { + JICPPacket p = new JICPPacket(); + + // Read packet type + p.type = read(in); + long firstByteTime = System.currentTimeMillis(); + + // Read the packet info + p.info = read(in); + + // Read session ID if present + if ((p.info & JICPProtocol.SESSION_ID_PRESENT_INFO) != 0) { + p.sessionID = read(in); + } + + // Read recipient ID if present + if ((p.info & JICPProtocol.RECIPIENT_ID_PRESENT_INFO) != 0) { + int size = (read(in) & 0x000000ff); + byte[] bb = new byte[size]; + in.read(bb, 0, size); + p.recipientID = new String(bb); + } + + // Read data if present + if ((p.info & JICPProtocol.DATA_PRESENT_INFO) != 0) { + int b1 = read(in); + int b2 = read(in); + int size = ((b2 << 8) & 0x0000ff00) | (b1 & 0x000000ff); + int b3 = read(in); + int b4 = read(in); + size |= ((b4 << 24) & 0xff000000) | ((b3 << 16) & 0x00ff0000); + if (size == 0) { + p.data = new byte[0]; + } else { + // Read the actual data + p.data = new byte[size]; + + int cnt = 0; + int n; + do { + n = in.read(p.data, cnt, size - cnt); + if (n == -1) { + throw new EOFException("EOF reading packet data"); + } + cnt += n; + } + while (cnt < size); + } + //Logger.println("JICPPacket read. Type:"+p.type+" Info:"+p.info+" RID:"+p.recipientID+" Data-length:"+(p.data != null ? p.data.length : 0)); + } + + long packetReadTime = System.currentTimeMillis() - firstByteTime; + if (packetReadTime > 2000) { + logger.log(Logger.WARNING, "JICPPacket read time over threshold: " + packetReadTime + " ms. Packet size = " + p.getLength()); + } + + // DEBUG + //System.out.println(p.getLength()+" bytes read"); + return p; + } + + private static byte read(InputStream in) throws IOException { + int i = in.read(); + if (i == -1) { + throw new EOFException("EOF reading packet header"); + } + return (byte) i; + } + + /** + * */ private void init(byte t, byte i, String id, byte[] d) { type = t; @@ -223,8 +299,8 @@ public byte[] getData() { * but not opened nor closed by this method. * * @param out The OutputStream to write the data in - * @exception IOException May send a large bunch of exceptions, mainly in the IO - * package. + * @throws IOException May send a large bunch of exceptions, mainly in the IO + * package. */ public int writeTo(OutputStream out) throws IOException { int cnt = 2; @@ -267,84 +343,6 @@ public int writeTo(OutputStream out) throws IOException { return cnt; } - /** - * This static method reads from a given - * DataInputStream and returns the JICPPacket that - * it reads. The input stream is not opened nor closed by this method. - * - * @param in The InputStream to read from - * @exception IOException May send a large bunch of exceptions, mainly in the IO - * package. - */ - public static JICPPacket readFrom(InputStream in) throws IOException { - JICPPacket p = new JICPPacket(); - - // Read packet type - p.type = read(in); - long firstByteTime = System.currentTimeMillis(); - - // Read the packet info - p.info = read(in); - - // Read session ID if present - if ((p.info & JICPProtocol.SESSION_ID_PRESENT_INFO) != 0) { - p.sessionID = read(in); - } - - // Read recipient ID if present - if ((p.info & JICPProtocol.RECIPIENT_ID_PRESENT_INFO) != 0) { - int size = (read(in) & 0x000000ff); - byte[] bb = new byte[size]; - in.read(bb, 0, size); - p.recipientID = new String(bb); - } - - // Read data if present - if ((p.info & JICPProtocol.DATA_PRESENT_INFO) != 0) { - int b1 = read(in); - int b2 = read(in); - int size = ((b2 << 8) & 0x0000ff00) | (b1 & 0x000000ff); - int b3 = read(in); - int b4 = read(in); - size |= ((b4 << 24) & 0xff000000) | ((b3 << 16) & 0x00ff0000); - if (size == 0) { - p.data = new byte[0]; - } else { - // Read the actual data - p.data = new byte[size]; - - int cnt = 0; - int n; - do { - n = in.read(p.data, cnt, size - cnt); - if (n == -1) { - throw new EOFException("EOF reading packet data"); - } - cnt += n; - } - while (cnt < size); - } - //Logger.println("JICPPacket read. Type:"+p.type+" Info:"+p.info+" RID:"+p.recipientID+" Data-length:"+(p.data != null ? p.data.length : 0)); - } - - long packetReadTime = System.currentTimeMillis() - firstByteTime; - if (packetReadTime > 2000) { - logger.log(Logger.WARNING, "JICPPacket read time over threshold: " + packetReadTime + " ms. Packet size = " + p.getLength()); - } - - // DEBUG - //System.out.println(p.getLength()+" bytes read"); - return p; - } - - private static byte read(InputStream in) throws IOException { - int i = in.read(); - if (i == -1) { - throw new EOFException("EOF reading packet header"); - } - return (byte) i; - } - public int getLength() { int cnt = 2; if ((info & JICPProtocol.SESSION_ID_PRESENT_INFO) != 0) { diff --git a/src/jade/imtp/leap/JICP/JICPPeer.java b/src/jade/imtp/leap/JICP/JICPPeer.java index 0912d94..10e071f 100644 --- a/src/jade/imtp/leap/JICP/JICPPeer.java +++ b/src/jade/imtp/leap/JICP/JICPPeer.java @@ -49,25 +49,22 @@ /** * Class declaration + * * @author Giovanni Caire - TILAB * @author Jamie Lawrence - Broadcom Eireann Research * @author Ronnie Taib - Motorola * @author Nicolas Lhuillier - Motorola */ public class JICPPeer implements ICP, ProtocolManager { + public static final String CONNECTION_TIMEOUT = "jade_imtp_leap_JICP_JICPPeer_connectiontimeout"; + public static final String READ_TIMEOUT = "jade_imtp_leap_JICP_JICPPeer_readtimeout"; private static final int POOL_SIZE = 50; - private JICPClient client; private JICPServer server; private Ticker ticker; - private String myID; - private int connectionTimeout; - public static final String CONNECTION_TIMEOUT = "jade_imtp_leap_JICP_JICPPeer_connectiontimeout"; - public static final String READ_TIMEOUT = "jade_imtp_leap_JICP_JICPPeer_readtimeout"; - /** * Start listening for internal platform messages on the specified port */ @@ -121,11 +118,11 @@ final String getID() { /** * Pings the specified transport address in order to obtain * the local hostname or IP address. + * * @param pingURL The URL to ping (usually the - * main container). + * main container). * @return The local IP address of the local container as a * String. - * * @throws ICPException */ String getAddress(String pingURL) throws ICPException { @@ -144,16 +141,16 @@ String getAddress(String pingURL) throws ICPException { } /** - Subclasses may re-define this method to return their own - protocol + * Subclasses may re-define this method to return their own + * protocol */ public TransportProtocol getProtocol() { return JICPProtocol.getInstance(); } /** - Subclasses may re-define this method to return their own - ConnectionFactory + * Subclasses may re-define this method to return their own + * ConnectionFactory */ public ConnectionFactory getConnectionFactory() { return new ConnectionFactory() { @@ -190,7 +187,7 @@ protected ServerSocket getServerSocket(String host, int port, boolean changePort } /** - Inner class Ticker + * Inner class Ticker */ private class Ticker extends Thread { private final long period; diff --git a/src/jade/imtp/leap/JICP/JICPProtocol.java b/src/jade/imtp/leap/JICP/JICPProtocol.java index 2bd3f3d..74e804b 100644 --- a/src/jade/imtp/leap/JICP/JICPProtocol.java +++ b/src/jade/imtp/leap/JICP/JICPProtocol.java @@ -43,6 +43,7 @@ /** * Class declaration + * * @author Giovanni Caire - TILAB * @author Ronnie Taib - Motorola * @author Steffen Rusitschka - Siemens @@ -57,25 +58,45 @@ public class JICPProtocol extends TransportProtocol { // JICP packet types - /** ID code for packets carrying IMTP commands */ + /** + * ID code for packets carrying IMTP commands + */ public static final byte COMMAND_TYPE = 0; - /** ID code for packets carrying IMTP responses */ + /** + * ID code for packets carrying IMTP responses + */ public static final byte RESPONSE_TYPE = 1; - /** ID code for packets carrying keep-alive */ + /** + * ID code for packets carrying keep-alive + */ public static final byte KEEP_ALIVE_TYPE = 2; - /** ID code for packets carrying requests to get the local address */ + /** + * ID code for packets carrying requests to get the local address + */ public static final byte GET_CONFIG_OPTIONS_TYPE = 20; - /** ID code for packets carrying requests to get the local address */ + /** + * ID code for packets carrying requests to get the local address + */ public static final byte GET_ADDRESS_TYPE = 21; - /** ID code for packets carrying requests to create a Mediator */ + /** + * ID code for packets carrying requests to create a Mediator + */ public static final byte CREATE_MEDIATOR_TYPE = 22; - /** ID code for packets carrying requests to connect to a Mediator */ + /** + * ID code for packets carrying requests to connect to a Mediator + */ public static final byte CONNECT_MEDIATOR_TYPE = 23; - /** ID code for packets carrying requests to retrieve the current server time */ + /** + * ID code for packets carrying requests to retrieve the current server time + */ public static final byte GET_SERVER_TIME_TYPE = 24; - /** ID code for packets carrying requests to drop-down the connection with the mediator */ + /** + * ID code for packets carrying requests to drop-down the connection with the mediator + */ public static final byte DROP_DOWN_TYPE = 30; - /** ID code for packets carrying JICP protocol errors */ + /** + * ID code for packets carrying JICP protocol errors + */ public static final byte ERROR_TYPE = 100; @@ -158,6 +179,14 @@ public static JICPProtocol getInstance() { return theInstance; } + public static final long computeTimeout(long timeoutOffset, double factor, int packetLength) { + // factor < 0 means "use default" + if (factor < 0) { + factor = DEFAULT_RESPONSE_TIMEOUT_MULTIPLICATIVE_FACTOR; + } + return timeoutOffset + (long) (factor * packetLength); + } + /** * Constructor declaration */ @@ -177,6 +206,7 @@ public String addrToString(TransportAddress ta) throws ICPException { /** * Method declaration + * * @param s * @return * @throws ICPException @@ -199,6 +229,7 @@ public TransportAddress stringToAddr(String s) throws ICPException { } /** + * */ public TransportAddress buildAddress(String host, String port, String file, String anchor) { return new JICPAddress(host, port, file, anchor); @@ -206,6 +237,7 @@ public TransportAddress buildAddress(String host, String port, String file, Stri /** * Method declaration + * * @return * @see */ @@ -213,13 +245,5 @@ public String getName() { return NAME; } - public static final long computeTimeout(long timeoutOffset, double factor, int packetLength) { - // factor < 0 means "use default" - if (factor < 0) { - factor = DEFAULT_RESPONSE_TIMEOUT_MULTIPLICATIVE_FACTOR; - } - return timeoutOffset + (long) (factor * packetLength); - } - } diff --git a/src/jade/imtp/leap/JICP/JICPSConnection.java b/src/jade/imtp/leap/JICP/JICPSConnection.java index 729a7e2..ece2f4b 100644 --- a/src/jade/imtp/leap/JICP/JICPSConnection.java +++ b/src/jade/imtp/leap/JICP/JICPSConnection.java @@ -50,13 +50,14 @@ /** * Class declaration + * * @author Steffen Rusitschka - Siemens * @author Giosue Vitaglione - TILAB */ public class JICPSConnection extends JICPConnection { - private static SSLSocketFactory scsf = null; protected static Logger myLogger = Logger.getMyLogger(JICPSConnection.class.getName()); + private static SSLSocketFactory scsf = null; protected JICPSConnection() { super(); @@ -81,6 +82,13 @@ public JICPSConnection(TransportAddress ta, boolean useSSLAuth, int timeout, Str } } // end constructor + /** + * Constructor declaration + */ + public JICPSConnection(Socket s) { + super(s); + } + private void constructJICPSConnectionNoAuth(TransportAddress ta, int timeout, String bindHost, int bindPort) throws IOException { myLogger.log(Logger.INFO, "Creating JICPSConnection with NO-AUTHENTICATION (only confidentiality)."); @@ -170,12 +178,5 @@ private void constructJICPSConnectionWithAuth(TransportAddress ta, int timeout, } }// end while } - - /** - * Constructor declaration - */ - public JICPSConnection(Socket s) { - super(s); - } } diff --git a/src/jade/imtp/leap/JICP/JICPSPeer.java b/src/jade/imtp/leap/JICP/JICPSPeer.java index 117bdb3..7c241ef 100644 --- a/src/jade/imtp/leap/JICP/JICPSPeer.java +++ b/src/jade/imtp/leap/JICP/JICPSPeer.java @@ -51,9 +51,9 @@ /** * JICPSPeer - JICP Secure Peer - * - * This JICP peer uses secure connections - * with or without mutual authentication + *

+ * This JICP peer uses secure connections + * with or without mutual authentication * of the endpoints by using digital certificates. * It leverages SSL/TLS. * @@ -68,6 +68,23 @@ public class JICPSPeer extends JICPPeer { protected static Logger myLogger = Logger.getMyLogger(JICPSPeer.class.getName()); private SSLContext ctx = null; + private boolean useSSLAuth = false; + + private static String getChiperDebugString(SSLServerSocket sss) { + // debug + StringBuilder sb = new StringBuilder(); + sb.append("\n--EnabledProtocols:\n"); + String[] prot = sss.getEnabledProtocols(); + for (String item : prot) sb.append(" ").append(item); + sb.append("\n--EnabledCipherSuites:\n"); + String[] suite = sss.getEnabledCipherSuites(); + for (String value : suite) sb.append(" ").append(value); + sb.append("\n--SupportedCipherSuites\n"); + String[] supported_suite = sss.getSupportedCipherSuites(); + for (String s : supported_suite) sb.append(" ").append(s); + sb.append("\n--\n"); + return sb.toString(); + } public TransportAddress activate(Listener l, String peerID, Profile p) throws ICPException { if (myLogger.isLoggable(Logger.FINE)) { @@ -89,8 +106,8 @@ public TransportAddress activate(Listener l, String peerID, Profile p) throws IC } /** - Subclasses may re-define this method to return their own - ConnectionFactory + * Subclasses may re-define this method to return their own + * ConnectionFactory */ public ConnectionFactory getConnectionFactory() { return new ConnectionFactory() { @@ -163,22 +180,6 @@ private ServerSocket getServerSocketWithAuth(String host, int port, boolean chan return sss; } // end getServerSocketWithAuth - private static String getChiperDebugString(SSLServerSocket sss) { - // debug - StringBuffer sb = new StringBuffer(); - sb.append("\n--EnabledProtocols:\n"); - String[] prot = sss.getEnabledProtocols(); - for (String item : prot) sb.append(" ").append(item); - sb.append("\n--EnabledCipherSuites:\n"); - String[] suite = sss.getEnabledCipherSuites(); - for (String value : suite) sb.append(" ").append(value); - sb.append("\n--SupportedCipherSuites\n"); - String[] supported_suite = sss.getSupportedCipherSuites(); - for (String s : supported_suite) sb.append(" ").append(s); - sb.append("\n--\n"); - return sb.toString(); - } - private ServerSocket getServerSocketNoAuth(String host, int port, boolean changePortIfBusy) throws ICPException { // Create the SSLContext if necessary if (ctx == null) { @@ -223,9 +224,6 @@ private ServerSocket getServerSocketNoAuth(String host, int port, boolean change return sss; } // end getServerSocketNoAuth(..) - - private boolean useSSLAuth = false; - private boolean getUseSSLAuth() { // if needed, may become public return useSSLAuth; } diff --git a/src/jade/imtp/leap/JICP/JICPServer.java b/src/jade/imtp/leap/JICP/JICPServer.java index 799b75a..f84ebad 100644 --- a/src/jade/imtp/leap/JICP/JICPServer.java +++ b/src/jade/imtp/leap/JICP/JICPServer.java @@ -58,6 +58,7 @@ /** * Class declaration + * * @author Giovanni Caire - TILAB * @author Ronnie Taib - Motorola * @author Nicolas Lhuillier - Motorola @@ -68,41 +69,32 @@ public class JICPServer extends Thread implements PDPContextManager.Listener, JICPMediatorManager //#J2ME_EXCLUDE_END { + public static final String ACCEPT_LOCAL_HOST_ONLY = "jade_imtp_leap_JICP_JICPServer_acceptlocalhostonly"; + public static final String UNCHECK_LOCAL_HOST = "jade_imtp_leap_JICP_JICPServer_unchecklocalhost"; + //#J2ME_EXCLUDE_BEGIN + public static final String ACCEPT_MEDIATORS = "jade_imtp_leap_JICP_JICPServer_acceptmediators"; private static final int INIT = 0; private static final int REQUEST_READ = 1; private static final int REQUEST_SERVED = 2; private static final int RESPONSE_SENT = 3; - - public static final String ACCEPT_LOCAL_HOST_ONLY = "jade_imtp_leap_JICP_JICPServer_acceptlocalhostonly"; - public static final String UNCHECK_LOCAL_HOST = "jade_imtp_leap_JICP_JICPServer_unchecklocalhost"; - private static final int LISTENING = 0; private static final int TERMINATING = 1; - - private int state = LISTENING; - - private String host; private final String exportHost; - private Integer exportPort; - - private ServerSocket server; private final ICP.Listener cmdListener; - - private int mediatorCnt = 1; private final Hashtable mediators = new Hashtable(); - //#J2ME_EXCLUDE_BEGIN - public static final String ACCEPT_MEDIATORS = "jade_imtp_leap_JICP_JICPServer_acceptmediators"; - private boolean acceptMediators = true; private final Properties leapProps = new Properties(); - private PDPContextManager myPDPContextManager; - //#J2ME_EXCLUDE_END - private final int maxHandlers; private final Vector connectionHandlers; - private final ConnectionFactory connFactory; - private final Logger myLogger; + private int state = LISTENING; + private String host; + private Integer exportPort; + //#J2ME_EXCLUDE_END + private ServerSocket server; + private int mediatorCnt = 1; + private boolean acceptMediators = true; + private PDPContextManager myPDPContextManager; /** * Constructor declaration @@ -115,15 +107,15 @@ public JICPServer(Profile p, JICPPeer myPeer, ICP.Listener l, ConnectionFactory maxHandlers = max; myLogger = Logger.getMyLogger(getClass().getName()); - StringBuffer sb = null; + StringBuilder sb = null; int idLength; String peerID = myPeer.getID(); if (peerID != null) { - sb = new StringBuffer(peerID); + sb = new StringBuilder(peerID); sb.append('-'); idLength = sb.length(); } else { - sb = new StringBuffer(); + sb = new StringBuilder(); idLength = 0; } @@ -214,12 +206,12 @@ public JICPServer(Profile p, JICPPeer myPeer, ICP.Listener l, ConnectionFactory String exportPortStr = p.getParameter(Profile.EXPORT_PORT, null); try { exportPort = Integer.getInteger(exportPortStr); - } catch (Exception e) { + } catch (Exception ignored) { } } public int getLocalPort() { - return exportPort != null ? exportPort.intValue() : server.getLocalPort(); + return exportPort != null ? exportPort : server.getLocalPort(); } public String getLocalHost() { @@ -229,7 +221,7 @@ public String getLocalHost() { } /** - Shut down this JICP server + * Shut down this JICP server */ public synchronized void shutdown() { @@ -246,10 +238,8 @@ public synchronized void shutdown() { // Wait for the listening thread to complete this.join(); - } catch (IOException ioe) { + } catch (IOException | InterruptedException ioe) { ioe.printStackTrace(); - } catch (InterruptedException ie) { - ie.printStackTrace(); } } @@ -331,7 +321,7 @@ public void run() { } /** - Called by the JICPPeer ticker at each tick + * Called by the JICPPeer ticker at each tick */ public void tick(long currentTime) { //#J2ME_EXCLUDE_BEGIN @@ -346,8 +336,53 @@ public void tick(long currentTime) { } /** - Inner class ConnectionHandler. - Handle a connection accepted by this JICPServer + * Called by a Mediator to notify that it is no longer active + */ + public void deregisterMediator(String id) { + myLogger.log(Logger.FINE, "Deregistering mediator " + id); + mediators.remove(id); + } + + //#J2ME_EXCLUDE_BEGIN + + /** + * Called by the PDPContextManager (if any) + */ + public void handlePDPContextClosed(String id) { + // FIXME: to be implemented + } + + private void mergeProperties(Properties p1, Properties p2) { + Enumeration e = p2.propertyNames(); + while (e.hasMoreElements()) { + String key = (String) e.nextElement(); + p1.setProperty(key, p2.getProperty(key)); + } + } + + private JICPMediator startMediator(String id, Properties p) throws Exception { + String className = p.getProperty(JICPProtocol.MEDIATOR_CLASS_KEY); + if (className != null) { + JICPMediator m = (JICPMediator) Class.forName(className).newInstance(); + mergeProperties(p, leapProps); + myLogger.log(Logger.FINE, "Initializing mediator " + id + " with properties " + p); + m.init(this, id, p); + return m; + } else { + throw new ICPException("No JICPMediator class specified."); + } + } + + private void waitABit(long t) { + try { + Thread.sleep(t); + } catch (InterruptedException ie) { + } + } + + /** + * Inner class ConnectionHandler. + * Handle a connection accepted by this JICPServer */ class ConnectionHandler extends Thread { private final Connection c; @@ -656,51 +691,6 @@ public void run() { } } } // END of inner class ConnectionHandler - - //#J2ME_EXCLUDE_BEGIN - - /** - * Called by a Mediator to notify that it is no longer active - */ - public void deregisterMediator(String id) { - myLogger.log(Logger.FINE, "Deregistering mediator " + id); - mediators.remove(id); - } - - /** - Called by the PDPContextManager (if any) - */ - public void handlePDPContextClosed(String id) { - // FIXME: to be implemented - } - - private void mergeProperties(Properties p1, Properties p2) { - Enumeration e = p2.propertyNames(); - while (e.hasMoreElements()) { - String key = (String) e.nextElement(); - p1.setProperty(key, p2.getProperty(key)); - } - } - - private JICPMediator startMediator(String id, Properties p) throws Exception { - String className = p.getProperty(JICPProtocol.MEDIATOR_CLASS_KEY); - if (className != null) { - JICPMediator m = (JICPMediator) Class.forName(className).newInstance(); - mergeProperties(p, leapProps); - myLogger.log(Logger.FINE, "Initializing mediator " + id + " with properties " + p); - m.init(this, id, p); - return m; - } else { - throw new ICPException("No JICPMediator class specified."); - } - } - - private void waitABit(long t) { - try { - Thread.sleep(t); - } catch (InterruptedException ie) { - } - } //#J2ME_EXCLUDE_END } diff --git a/src/jade/imtp/leap/JICP/MaskableJICPPeer.java b/src/jade/imtp/leap/JICP/MaskableJICPPeer.java index a5f2cfe..1a94ef6 100644 --- a/src/jade/imtp/leap/JICP/MaskableJICPPeer.java +++ b/src/jade/imtp/leap/JICP/MaskableJICPPeer.java @@ -48,6 +48,7 @@ /** * Class declaration + * * @author Giovanni Caire - TILAB */ public class MaskableJICPPeer extends JICPPeer { @@ -81,8 +82,8 @@ public TransportAddress activate(Listener l, String peerID, Profile p) throws IC sb.append(JICPProtocol.UNREACHABLE_KEY); List ls = p.getSpecifiers(sb.toString()); if (ls != null) { - for (Object o : ls) { - Specifier s = (Specifier) o; + for (Specifier o : ls) { + Specifier s = o; // Note that in this case the className field of a specifier does // not have anything to do with a class. updateMask(s.getClassName()); @@ -110,9 +111,7 @@ public byte[] deliverCommand(TransportAddress ta, byte[] payload, boolean requir * Method declaration * * @param m - * * @throws ICPException - * * @see */ private void updateMask(String m) throws ICPException { @@ -124,9 +123,7 @@ private void updateMask(String m) throws ICPException { * Method declaration * * @param host - * * @return - * * @see */ private boolean isMasked(String host) { @@ -163,11 +160,8 @@ private boolean isMasked(String host) { * Method declaration * * @param addr - * * @return - * * @throws ICPException - * * @see */ private int[] parseIP(String addr) throws ICPException { diff --git a/src/jade/imtp/leap/JICP/NATUtils.java b/src/jade/imtp/leap/JICP/NATUtils.java index 1ab98e3..adc7ceb 100644 --- a/src/jade/imtp/leap/JICP/NATUtils.java +++ b/src/jade/imtp/leap/JICP/NATUtils.java @@ -16,6 +16,47 @@ public NATUtils(String serverAddr, int serverPort) { this.serverPort = serverPort; } + public static void main(String[] args) { +// TransportAddress ta = new JICPAddress(args[0], args[1], null, null); +// try { +// JICPConnection con = new JICPConnection(ta) { +// @Override +// protected void bindSocket(Socket sc) { +// try { +// sc.bind(new InetSocketAddress(3333)); +// } catch (IOException e) { +// // TODO Auto-generated catch block +// e.printStackTrace(); +// } +// } +// }; +// JICPPacket pkt = new JICPPacket(JICPProtocol.GET_ADDRESS_TYPE, JICPProtocol.DEFAULT_INFO, new byte[]{0}); +// con.writePacket(pkt); +// pkt = con.readPacket(); +// byte[] data = pkt.getData(); +// if (data != null) { +// System.out.println(new String(data)); +// } +// else { +// System.out.println("NO DATA"); +// } +// con.close(); +// } catch (IOException e) { +// // TODO Auto-generated catch block +// e.printStackTrace(); +// } + + NATUtils nat = new NATUtils(args[0], Integer.parseInt(args[1])); + + try { + InetSocketAddress[] aa = nat.getNATMapping(null, 8888, 10000); + System.out.println("local = " + aa[0]); + System.out.println("external = " + aa[1]); + } catch (Exception e) { + e.printStackTrace(); + } + } + public InetSocketAddress[] getNATMapping(final String localAddress, final int localPort, int timeout) throws Exception { TransportAddress ta = new JICPAddress(serverAddr, String.valueOf(serverPort), null, null); JICPConnection con = null; @@ -70,45 +111,4 @@ protected void bindSocket(Socket sc) { } } } - - public static void main(String[] args) { -// TransportAddress ta = new JICPAddress(args[0], args[1], null, null); -// try { -// JICPConnection con = new JICPConnection(ta) { -// @Override -// protected void bindSocket(Socket sc) { -// try { -// sc.bind(new InetSocketAddress(3333)); -// } catch (IOException e) { -// // TODO Auto-generated catch block -// e.printStackTrace(); -// } -// } -// }; -// JICPPacket pkt = new JICPPacket(JICPProtocol.GET_ADDRESS_TYPE, JICPProtocol.DEFAULT_INFO, new byte[]{0}); -// con.writePacket(pkt); -// pkt = con.readPacket(); -// byte[] data = pkt.getData(); -// if (data != null) { -// System.out.println(new String(data)); -// } -// else { -// System.out.println("NO DATA"); -// } -// con.close(); -// } catch (IOException e) { -// // TODO Auto-generated catch block -// e.printStackTrace(); -// } - - NATUtils nat = new NATUtils(args[0], Integer.parseInt(args[1])); - - try { - InetSocketAddress[] aa = nat.getNATMapping(null, 8888, 10000); - System.out.println("local = " + aa[0]); - System.out.println("external = " + aa[1]); - } catch (Exception e) { - e.printStackTrace(); - } - } } diff --git a/src/jade/imtp/leap/JICP/PDPContextManager.java b/src/jade/imtp/leap/JICP/PDPContextManager.java index 763a94c..29e2cf5 100644 --- a/src/jade/imtp/leap/JICP/PDPContextManager.java +++ b/src/jade/imtp/leap/JICP/PDPContextManager.java @@ -34,13 +34,13 @@ public interface PDPContextManager { String PASSWORD = "pdp-context-password"; String LOCATION = "location"; - interface Listener { - void handlePDPContextClosed(String msisdn); - } - void init(Properties p) throws Exception; void registerListener(Listener l); Properties getPDPContextInfo(InetAddress addr, String owner) throws JADESecurityException; + + interface Listener { + void handlePDPContextClosed(String msisdn); + } } \ No newline at end of file diff --git a/src/jade/imtp/leap/LEAPIMTPManager.java b/src/jade/imtp/leap/LEAPIMTPManager.java index a3c115c..91927bc 100644 --- a/src/jade/imtp/leap/LEAPIMTPManager.java +++ b/src/jade/imtp/leap/LEAPIMTPManager.java @@ -48,33 +48,26 @@ */ public class LEAPIMTPManager implements IMTPManager { + public static final String CHANGE_PORT_IF_BUSY = "jade_imtp_leap_LEAPIMTPManager_changeportifbusy"; /** * Profile keys for LEAP-IMTP specific parameters */ static final String MAIN_URL = "main-url"; - - public static final String CHANGE_PORT_IF_BUSY = "jade_imtp_leap_LEAPIMTPManager_changeportifbusy"; - private static final String ICPS = "icps"; private static final String ROUTER_URL = "router-url"; - + Logger logger = Logger.getMyLogger(getClass().getName()); /** * Local pointer to the singleton command dispatcher in this JVM */ private CommandDispatcher theDispatcher = null; - /** * The Profile holding the configuration for this IMTPManager */ private Profile theProfile = null; - private String masterPMAddr; private String localAddr; - private NodeLEAP localNode; - Logger logger = Logger.getMyLogger(getClass().getName()); - /** * Default constructor used to dynamically instantiate a new * LEAPIMTPManager object @@ -203,7 +196,7 @@ public void exportPlatformManager(PlatformManager mgr) throws IMTPException { throw new IMTPException("Cannot attach to the original PlatformManager.", se); } catch (IMTPException imtpe) { Throwable t = imtpe.getNested(); - if ((t != null) && (t instanceof UnreachableException)) { + if ((t instanceof UnreachableException)) { // The master main container does not exist. Become the leader logger.log(Logger.INFO, "No master Main Container found at address " + masterPMAddr + ". Take the leadership"); masterPMAddr = null; @@ -240,10 +233,6 @@ public Service.Slice createSliceProxy(String serviceName, Class itf, Node whe if (proxy instanceof SliceProxy) { ((SliceProxy) proxy).setNode(where); } - //#DOTNET_EXCLUDE_BEGIN - else if (proxy instanceof SliceProxy) { - ((SliceProxy) proxy).setNode(where); - } //#DOTNET_EXCLUDE_END else { throw new IMTPException("Class " + proxyClass.getName() + " is not a slice proxy."); diff --git a/src/jade/imtp/leap/MicroStub.java b/src/jade/imtp/leap/MicroStub.java index bbc82eb..137111a 100644 --- a/src/jade/imtp/leap/MicroStub.java +++ b/src/jade/imtp/leap/MicroStub.java @@ -37,13 +37,12 @@ */ public class MicroStub { public static final long MINIMUM_TIMEOUT = 3000; // 3 sec - + private final Vector dispatchingThreads = new Vector<>(); protected Dispatcher myDispatcher; protected Vector pendingCommands = new Vector<>(); + protected Logger logger; private boolean flushing = false; private Thread flushingThread; - private final Vector dispatchingThreads = new Vector<>(); - protected Logger logger; public MicroStub(Dispatcher d) { myDispatcher = d; @@ -303,8 +302,8 @@ private void manageTimerExpired(final PostponedCommand pc) { protected class PostponedCommand { private final Command command; - private int sessionId; private final ICPException icpe; + private int sessionId; private Timer timer; public PostponedCommand(Command c, int sessionId, ICPException icpe) { diff --git a/src/jade/imtp/leap/NodeLEAP.java b/src/jade/imtp/leap/NodeLEAP.java index 8879470..f150cdb 100644 --- a/src/jade/imtp/leap/NodeLEAP.java +++ b/src/jade/imtp/leap/NodeLEAP.java @@ -45,9 +45,9 @@ class NodeLEAP extends BaseNode { // This monitor is used to hang a remote ping() call in order to // detect node failures. private final Object terminationLock = new Object(); - private boolean terminating = false; private final CommandDispatcher myDispatcher; private final Logger myLogger = Logger.getMyLogger(getClass().getName()); + private boolean terminating = false; public NodeLEAP(String name, boolean hasPM, CommandDispatcher dispatcher) { super(name, hasPM); diff --git a/src/jade/imtp/leap/NodeSkel.java b/src/jade/imtp/leap/NodeSkel.java index f6b5a12..1b50698 100644 --- a/src/jade/imtp/leap/NodeSkel.java +++ b/src/jade/imtp/leap/NodeSkel.java @@ -61,7 +61,6 @@ public Command executeCommand(Command command) throws Throwable { command.reset(Command.OK); command.addParam(result); - break; } case Command.PING_NODE_BLOCKING, Command.PING_NODE_NONBLOCKING -> { Boolean hang = (Boolean) command.getParamAt(0); @@ -69,17 +68,14 @@ public Command executeCommand(Command command) throws Throwable { command.reset(Command.OK); command.addParam(result); - break; } case Command.EXIT_NODE -> { myNode.exit(); command.reset(Command.OK); - break; } case Command.INTERRUPT_NODE -> { myNode.interrupt(); command.reset(Command.OK); - break; } case Command.PLATFORM_MANAGER_DEAD -> { String deadPMAddress = (String) command.getParamAt(0); @@ -87,7 +83,6 @@ public Command executeCommand(Command command) throws Throwable { myNode.platformManagerDead(deadPMAddress, notifyingPMAddress); command.reset(Command.OK); - break; } } diff --git a/src/jade/imtp/leap/NodeStub.java b/src/jade/imtp/leap/NodeStub.java index 4fea28e..6162522 100644 --- a/src/jade/imtp/leap/NodeStub.java +++ b/src/jade/imtp/leap/NodeStub.java @@ -45,14 +45,14 @@ public NodeStub(int id, String platformName) { super(id, platformName); } - public void setName(String name) { - this.name = name; - } - public String getName() { return name; } + public void setName(String name) { + this.name = name; + } + public boolean hasPlatformManager() { return hasPM; } diff --git a/src/jade/imtp/leap/SSLHelper.java b/src/jade/imtp/leap/SSLHelper.java index 1ae02b2..4db93c9 100644 --- a/src/jade/imtp/leap/SSLHelper.java +++ b/src/jade/imtp/leap/SSLHelper.java @@ -26,16 +26,15 @@ public class SSLHelper { */ public static final List supportedKeys = Collections.singletonList("TLS_ECDH_anon_WITH_AES_128_CBC_SHA"); - - public static String[] getSupportedKeys() { - return supportedKeys.toArray(new String[0]); - } - private static final Logger logger = Logger.getJADELogger(SSLHelper.class.getName()); private SSLHelper() { } + public static String[] getSupportedKeys() { + return supportedKeys.toArray(new String[0]); + } + /** * //* @param keystore * diff --git a/src/jade/imtp/leap/http/HTTPAddress.java b/src/jade/imtp/leap/http/HTTPAddress.java index 7458943..4221f09 100644 --- a/src/jade/imtp/leap/http/HTTPAddress.java +++ b/src/jade/imtp/leap/http/HTTPAddress.java @@ -38,6 +38,7 @@ /** * Class declaration + * * @author Giovanni Caire - TILAB */ public class HTTPAddress implements TransportAddress { @@ -48,6 +49,7 @@ public class HTTPAddress implements TransportAddress { /** * Constructor declaration + * * @param host * @param port * @param file @@ -62,6 +64,7 @@ public HTTPAddress(String host, String port, String file, String anchor) { /** * Method declaration + * * @return * @see */ @@ -71,6 +74,7 @@ public String getProto() { /** * Method declaration + * * @return * @see */ @@ -80,6 +84,7 @@ public String getHost() { /** * Method declaration + * * @return * @see */ @@ -89,6 +94,7 @@ public String getPort() { /** * Method declaration + * * @return * @see */ @@ -98,6 +104,7 @@ public String getFile() { /** * Method declaration + * * @return * @see */ @@ -106,7 +113,7 @@ public String getAnchor() { } public String toString() { - StringBuffer address = new StringBuffer(); + StringBuilder address = new StringBuilder(); address.append(getProto()); address.append("://"); diff --git a/src/jade/imtp/leap/http/HTTPBEDispatcher.java b/src/jade/imtp/leap/http/HTTPBEDispatcher.java index 3fb4d4e..be644f3 100644 --- a/src/jade/imtp/leap/http/HTTPBEDispatcher.java +++ b/src/jade/imtp/leap/http/HTTPBEDispatcher.java @@ -38,6 +38,7 @@ */ public class HTTPBEDispatcher implements BEConnectionManager, Dispatcher, JICPMediator { + private final Logger myLogger = Logger.getMyLogger(this.getClass().getName()); private JICPMediatorManager myMediatorManager; private String myID; private MicroSkeleton mySkel = null; @@ -46,7 +47,6 @@ public class HTTPBEDispatcher implements BEConnectionManager, Dispatcher, JICPMe private OutgoingsHandler myOutgoingsHandler; private JICPPacket lastResponse = null; private byte lastSid = 0x10; - private final Logger myLogger = Logger.getMyLogger(this.getClass().getName()); ///////////////////////////////////// // JICPMediator interface implementation @@ -296,7 +296,10 @@ private class OutgoingsHandler implements TimerListener { private static final int TERMINATED = 3; private static final long RESPONSE_TIMEOUT = 5000; // 30 sec private static final int MAX_SID = 0x0f; - + private final boolean connectionReset = false; + private final long maxDisconnectionTime; + private final long keepAliveTime; + private final Object initialResponseLock = new Object(); private int frontEndStatus = CONNECTING; private int outCnt = 0; private Thread responseWaiter = null; @@ -304,12 +307,8 @@ private class OutgoingsHandler implements TimerListener { private JICPPacket currentResponse = null; private boolean commandReady = false; private boolean responseReady = false; - private final boolean connectionReset = false; - private final long maxDisconnectionTime; - private final long keepAliveTime; private Timer maxDisconnectionTimer = null; private boolean waitingForFlush = false; - private final Object initialResponseLock = new Object(); private boolean initialResponseReceived; public OutgoingsHandler(long maxDisconnectionTime, long keepAliveTime) { diff --git a/src/jade/imtp/leap/http/HTTPClientConnection.java b/src/jade/imtp/leap/http/HTTPClientConnection.java index 92d9250..b9cad74 100644 --- a/src/jade/imtp/leap/http/HTTPClientConnection.java +++ b/src/jade/imtp/leap/http/HTTPClientConnection.java @@ -48,20 +48,20 @@ /** * Class declaration + * * @author Giovanni Caire - TILAB */ class HTTPClientConnection extends Connection { private static final int READY = 0; private static final int WRITTEN = 1; private static final int CLOSED = -1; - - //#MIDP_EXCLUDE_BEGIN - private HttpURLConnection hc; //#MIDP_EXCLUDE_END /*#MIDP_INCLUDE_BEGIN private HttpConnection hc; #MIDP_INCLUDE_END*/ private final String url; + //#MIDP_EXCLUDE_BEGIN + private HttpURLConnection hc; private InputStream is; private OutputStream os; private int state; @@ -176,6 +176,7 @@ public JICPPacket readPacket() throws IOException { } /** + * */ public void close() throws IOException { state = CLOSED; @@ -204,6 +205,7 @@ public void close() throws IOException { //#MIDP_EXCLUDE_BEGIN /** + * */ public String getRemoteHost() throws Exception { throw new Exception("Unsupported operation"); diff --git a/src/jade/imtp/leap/http/HTTPFEDispatcher.java b/src/jade/imtp/leap/http/HTTPFEDispatcher.java index 9db3db8..d768fdf 100644 --- a/src/jade/imtp/leap/http/HTTPFEDispatcher.java +++ b/src/jade/imtp/leap/http/HTTPFEDispatcher.java @@ -47,9 +47,12 @@ */ public class HTTPFEDispatcher implements FEConnectionManager, Dispatcher, TimerListener { + private final Object connectorLock = new Object(); + private final int verbosity = 1; + private final Logger myLogger = Logger.getMyLogger(getClass().getName()); + protected String myMediatorClass = "jade.imtp.leap.http.HTTPBEDispatcher"; private MicroSkeleton mySkel; private BackEndStub myStub; - private Thread terminator; private DisconnectionManager myDisconnectionManager; private KeepAliveManager myKeepAliveManager; @@ -59,28 +62,27 @@ public class HTTPFEDispatcher implements FEConnectionManager, Dispatcher, TimerL private long maxDisconnectionTime; private long keepAliveTime; private Properties props; - private TransportAddress mediatorTA; private String myMediatorID; - private String owner; - private String beAddrsText; private String[] backEndAddresses; - private ConnectionListener myConnectionListener; - - private final Object connectorLock = new Object(); private boolean locked = false; - private final int verbosity = 1; - private final Logger myLogger = Logger.getMyLogger(getClass().getName()); - - protected String myMediatorClass = "jade.imtp.leap.http.HTTPBEDispatcher"; - //////////////////////////////////////////////// // FEConnectionManager interface implementation //////////////////////////////////////////////// + // These variables are only used within the InputManager class, + // but are declared externally since they must "survive" when + // an InputManager is replaced + private JICPPacket lastResponse = null; + private byte lastSid = 0x10; + private int cnt = 0; + + ////////////////////////////////////////////// + // Dispatcher interface implementation + ////////////////////////////////////////////// /** * Create a BackEnd in the fixed network and return a stub to @@ -258,10 +260,6 @@ private synchronized void createBackEnd() throws IMTPException { throw new IMTPException("Error creating the BackEnd."); } - ////////////////////////////////////////////// - // Dispatcher interface implementation - ////////////////////////////////////////////// - /** * Dispatch a serialized command to the BackEnd and get back a serialized response. * Mutual exclusion with itself to preserve dispatching order @@ -310,12 +308,154 @@ public synchronized byte[] dispatch(byte[] payload, boolean flush, int oldSessio } } - // These variables are only used within the InputManager class, - // but are declared externally since they must "survive" when - // an InputManager is replaced - private JICPPacket lastResponse = null; - private byte lastSid = 0x10; - private int cnt = 0; + protected Connection getConnection(TransportAddress ta) { + return new HTTPClientConnection(ta); + } + + /** + * Deliver a packet to the BackEnd and get back a response using a fresh one-shot connection + */ + private JICPPacket deliver(JICPPacket pkt) throws IOException { + Connection c = getConnection(mediatorTA); + try { + return deliver(pkt, c); + } finally { + try { + c.close(); + } catch (Exception e) { + } + } + } + + /** + * Deliver a packet over a given connection and get back a response + */ + private JICPPacket deliver(JICPPacket pkt, Connection c) throws IOException { + boolean lastPacket = false; + if (Thread.currentThread() == terminator) { + pkt.setTerminatedInfo(true); + lastPacket = true; + } + pkt.setRecipientID(mediatorTA.getFile()); + byte type = pkt.getType(); + + int status = 0; + try { + c.writePacket(pkt); + status = 1; + /*#MIDP_INCLUDE_BEGIN + lock(); + if (type == JICPProtocol.RESPONSE_TYPE) { + TimerDispatcher.getTimerDispatcher().add(new Timer(System.currentTimeMillis()+5000, this)); + } + #MIDP_INCLUDE_END*/ + pkt = c.readPacket(); + + status = 2; + if (lastPacket && (pkt.getInfo() & JICPProtocol.TERMINATED_INFO) != 0) { + // When we send a packet marked with the terminated-info, the back-end may either close + // the connection (in this case we would have got an Exception) or reply with another + // packet marked with the terminated-info --> throws an Exception to expose a uniform behaviour + myLogger.log(Logger.INFO, "Termination notification ACK received"); + throw new IOException("Terminated-info"); + } + return pkt; + } catch (IOException ioe) { + // Re-throw the exception adding the status + throw new IOException(ioe.getMessage() + '[' + status + ']'); + } finally { + /*#MIDP_INCLUDE_BEGIN + if (type != JICPProtocol.RESPONSE_TYPE) { + // If we delivered a RESPONSE unlock() is already called by the TimerDispatcher + unlock(); + } + #MIDP_INCLUDE_END*/ + } + } + + public void doTimeOut(Timer t) { + unlock(); + } + + private void lock() { + synchronized (connectorLock) { + while (locked) { + try { + connectorLock.wait(); + } catch (Exception e) { + } + } + locked = true; + } + } + + private void unlock() { + synchronized (connectorLock) { + locked = false; + connectorLock.notifyAll(); + } + } + + /** + * Send a CONNECT_MEDIATOR packet to the BackEnd to check if it is reachable + */ + private boolean ping(int cnt) throws ICPException { + // Try first with the current transport address, then with the various backup addresses + for (int i = -1; i < backEndAddresses.length; i++) { + if (i >= 0) { + // Set the mediator address to a new address.. + String addr = backEndAddresses[i]; + int colonPos = addr.indexOf(':'); + String host = addr.substring(0, colonPos); + String port = addr.substring(colonPos + 1); + mediatorTA = new JICPAddress(host, port, myMediatorID, ""); + } + + try { + myLogger.log(Logger.FINE, "Ping " + mediatorTA.getHost() + ":" + mediatorTA.getPort() + "(" + cnt + ")..."); + JICPPacket pkt = new JICPPacket(JICPProtocol.CONNECT_MEDIATOR_TYPE, JICPProtocol.DEFAULT_INFO, null); + pkt = deliver(pkt); + if (pkt.getType() == JICPProtocol.ERROR_TYPE) { + // Communication OK, but there was a JICP error. + String errorMsg = new String(pkt.getData()); + if (errorMsg.equals(JICPProtocol.NOT_FOUND_ERROR)) { + // Back-end not found: either the max disconnection time expired server side or there was a fault and restart + // --> Try to recreate the Back-end + myLogger.log(Logger.WARNING, "Communication OK, but Back-end no longer present. Try to recreate it"); + if (myConnectionListener != null) { + myConnectionListener.handleConnectionEvent(ConnectionListener.BE_NOT_FOUND, null); + } + try { + createBackEnd(); + } catch (IMTPException imtpe) { + myLogger.log(Logger.WARNING, "Error re-creating the Back-end."); + return false; + } + } else { + // Generic JICP error. No need to go on + throw new ICPException("JICP error. " + errorMsg); + } + } + return true; + } catch (IOException ioe) { + // Ignore it, and try the next address... + myLogger.log(Logger.FINE, "Ping KO", ioe); + } + } + + // No address succeeded. + return false; + } + + private String[] parseBackEndAddresses(String addressesText) { + Vector addrs = Specifier.parseList(addressesText, ';'); + // Convert the list into an array of strings + String[] result = new String[addrs.size()]; + for (int i = 0; i < result.length; i++) { + result[i] = (String) addrs.elementAt(i); + } + return result; + } /** * Inner class InputManager @@ -413,104 +553,16 @@ private synchronized void kill() { } } // END of inner class InputManager - protected Connection getConnection(TransportAddress ta) { - return new HTTPClientConnection(ta); - } - - /** - * Deliver a packet to the BackEnd and get back a response using a fresh one-shot connection - */ - private JICPPacket deliver(JICPPacket pkt) throws IOException { - Connection c = getConnection(mediatorTA); - try { - return deliver(pkt, c); - } finally { - try { - c.close(); - } catch (Exception e) { - } - } - } - - /** - * Deliver a packet over a given connection and get back a response - */ - private JICPPacket deliver(JICPPacket pkt, Connection c) throws IOException { - boolean lastPacket = false; - if (Thread.currentThread() == terminator) { - pkt.setTerminatedInfo(true); - lastPacket = true; - } - pkt.setRecipientID(mediatorTA.getFile()); - byte type = pkt.getType(); - - int status = 0; - try { - c.writePacket(pkt); - status = 1; - /*#MIDP_INCLUDE_BEGIN - lock(); - if (type == JICPProtocol.RESPONSE_TYPE) { - TimerDispatcher.getTimerDispatcher().add(new Timer(System.currentTimeMillis()+5000, this)); - } - #MIDP_INCLUDE_END*/ - pkt = c.readPacket(); - - status = 2; - if (lastPacket && (pkt.getInfo() & JICPProtocol.TERMINATED_INFO) != 0) { - // When we send a packet marked with the terminated-info, the back-end may either close - // the connection (in this case we would have got an Exception) or reply with another - // packet marked with the terminated-info --> throws an Exception to expose a uniform behaviour - myLogger.log(Logger.INFO, "Termination notification ACK received"); - throw new IOException("Terminated-info"); - } - return pkt; - } catch (IOException ioe) { - // Re-throw the exception adding the status - throw new IOException(ioe.getMessage() + '[' + status + ']'); - } finally { - /*#MIDP_INCLUDE_BEGIN - if (type != JICPProtocol.RESPONSE_TYPE) { - // If we delivered a RESPONSE unlock() is already called by the TimerDispatcher - unlock(); - } - #MIDP_INCLUDE_END*/ - } - } - - public void doTimeOut(Timer t) { - unlock(); - } - - private void lock() { - synchronized (connectorLock) { - while (locked) { - try { - connectorLock.wait(); - } catch (Exception e) { - } - } - locked = true; - } - } - - private void unlock() { - synchronized (connectorLock) { - locked = false; - connectorLock.notifyAll(); - } - } - /** * Inner class DisconnectionManager. * Manages issues related to disconnection of the device. */ class DisconnectionManager implements Runnable { + private final long retryTime; + private final long maxDisconnectionTime; private boolean reachable = false; private boolean pingOK = false; private Thread myThread; - private final long retryTime; - private final long maxDisconnectionTime; private DisconnectionManager(long retryTime, long maxDisconnectionTime) { this.retryTime = retryTime; @@ -619,7 +671,6 @@ private void waitABit(long time) { } } // END of Inner class DisconnectionManager - /** * Inner class KeepAliveManager * This class is responsible for taking track of keep-alive packets @@ -653,68 +704,6 @@ private synchronized void update() { } } } // END of inner class KeepAliveManager - - - /** - * Send a CONNECT_MEDIATOR packet to the BackEnd to check if it is reachable - */ - private boolean ping(int cnt) throws ICPException { - // Try first with the current transport address, then with the various backup addresses - for (int i = -1; i < backEndAddresses.length; i++) { - if (i >= 0) { - // Set the mediator address to a new address.. - String addr = backEndAddresses[i]; - int colonPos = addr.indexOf(':'); - String host = addr.substring(0, colonPos); - String port = addr.substring(colonPos + 1); - mediatorTA = new JICPAddress(host, port, myMediatorID, ""); - } - - try { - myLogger.log(Logger.FINE, "Ping " + mediatorTA.getHost() + ":" + mediatorTA.getPort() + "(" + cnt + ")..."); - JICPPacket pkt = new JICPPacket(JICPProtocol.CONNECT_MEDIATOR_TYPE, JICPProtocol.DEFAULT_INFO, null); - pkt = deliver(pkt); - if (pkt.getType() == JICPProtocol.ERROR_TYPE) { - // Communication OK, but there was a JICP error. - String errorMsg = new String(pkt.getData()); - if (errorMsg.equals(JICPProtocol.NOT_FOUND_ERROR)) { - // Back-end not found: either the max disconnection time expired server side or there was a fault and restart - // --> Try to recreate the Back-end - myLogger.log(Logger.WARNING, "Communication OK, but Back-end no longer present. Try to recreate it"); - if (myConnectionListener != null) { - myConnectionListener.handleConnectionEvent(ConnectionListener.BE_NOT_FOUND, null); - } - try { - createBackEnd(); - } catch (IMTPException imtpe) { - myLogger.log(Logger.WARNING, "Error re-creating the Back-end."); - return false; - } - } else { - // Generic JICP error. No need to go on - throw new ICPException("JICP error. " + errorMsg); - } - } - return true; - } catch (IOException ioe) { - // Ignore it, and try the next address... - myLogger.log(Logger.FINE, "Ping KO", ioe); - } - } - - // No address succeeded. - return false; - } - - private String[] parseBackEndAddresses(String addressesText) { - Vector addrs = Specifier.parseList(addressesText, ';'); - // Convert the list into an array of strings - String[] result = new String[addrs.size()]; - for (int i = 0; i < result.length; i++) { - result[i] = (String) addrs.elementAt(i); - } - return result; - } /*private String[] parseBackEndAddresses(String addressesText) { diff --git a/src/jade/imtp/leap/http/HTTPPacket.java b/src/jade/imtp/leap/http/HTTPPacket.java index 72ede78..0c672f6 100644 --- a/src/jade/imtp/leap/http/HTTPPacket.java +++ b/src/jade/imtp/leap/http/HTTPPacket.java @@ -59,10 +59,29 @@ public class HTTPPacket { protected HTTPPacket() { } + private static boolean endOfHeader(int[] bb, int pos) { + if (bb[pos] == LF) { + if ((++pos) >= 3) { + pos = 0; + } + if (bb[pos] == CR) { + if ((++pos) >= 3) { + pos = 0; + } + return bb[pos] == LF; + } + } + return false; + } + public String getHttpType() { return httpType; } + public void setHttpType(String type) { + httpType = type; + } + public String getField(String key) { return fields.get(new CaseInsensitiveString(key)); } @@ -71,8 +90,13 @@ public byte[] getPayload() { return payload; } - public void setHttpType(String type) { - httpType = type; + public void setPayload(byte[] p) { + payload = p; + if (payload != null) { + fields.put(CONTENT_LENGTH_KEY, String.valueOf(payload.length)); + } else { + fields.remove(CONTENT_LENGTH_KEY); + } } public void setField(String key, String value) { @@ -83,15 +107,6 @@ public void setField(String key, String value) { } } - public void setPayload(byte[] p) { - payload = p; - if (payload != null) { - fields.put(CONTENT_LENGTH_KEY, String.valueOf(payload.length)); - } else { - fields.remove(CONTENT_LENGTH_KEY); - } - } - public void setPayload(byte[] bb, int first, int length) { payload = new byte[length]; System.arraycopy(bb, first, payload, 0, length); @@ -100,6 +115,7 @@ public void setPayload(byte[] bb, int first, int length) { /** * Method declaration + * * @see */ protected void readFrom(InputStream is) throws IOException { @@ -166,23 +182,9 @@ protected void readFrom(InputStream is) throws IOException { } } - private static boolean endOfHeader(int[] bb, int pos) { - if (bb[pos] == LF) { - if ((++pos) >= 3) { - pos = 0; - } - if (bb[pos] == CR) { - if ((++pos) >= 3) { - pos = 0; - } - return bb[pos] == LF; - } - } - return false; - } - /** * Method declaration + * * @see */ protected void writeTo(OutputStream os) throws IOException { @@ -212,6 +214,7 @@ protected void writeTo(OutputStream os) throws IOException { /** * Method declaration + * * @see */ public String toString() { diff --git a/src/jade/imtp/leap/http/HTTPPeer.java b/src/jade/imtp/leap/http/HTTPPeer.java index 7f99098..90e12cf 100644 --- a/src/jade/imtp/leap/http/HTTPPeer.java +++ b/src/jade/imtp/leap/http/HTTPPeer.java @@ -46,19 +46,20 @@ /** * Class declaration + * * @author Giovanni Caire - TILAB */ public class HTTPPeer extends JICPPeer { /** - Re-define the getProtocol() method to return the HTTPProtocol + * Re-define the getProtocol() method to return the HTTPProtocol */ public TransportProtocol getProtocol() { return HTTPProtocol.getInstance(); } /** - Re-define the getConnectionFactory + * Re-define the getConnectionFactory */ public ConnectionFactory getConnectionFactory() { return new ConnectionFactory() { diff --git a/src/jade/imtp/leap/http/HTTPProtocol.java b/src/jade/imtp/leap/http/HTTPProtocol.java index d360d95..9b156c4 100644 --- a/src/jade/imtp/leap/http/HTTPProtocol.java +++ b/src/jade/imtp/leap/http/HTTPProtocol.java @@ -42,6 +42,7 @@ /** * Class declaration + * * @author Giovanni Caire - TILAB * @author Ronnie Taib - Motorola * @author Steffen Rusitschka - Siemens @@ -61,6 +62,7 @@ public static HTTPProtocol getInstance() { } /** + * */ public String addrToString(TransportAddress ta) throws ICPException { @@ -77,6 +79,7 @@ public String addrToString(TransportAddress ta) throws ICPException { } /** + * */ public TransportAddress stringToAddr(String s) throws ICPException { Vector addressFields = parseURL(s); @@ -95,6 +98,7 @@ public TransportAddress stringToAddr(String s) throws ICPException { } /** + * */ public TransportAddress buildAddress(String host, String port, String file, String anchor) { return new HTTPAddress(host, port, file, anchor); @@ -102,6 +106,7 @@ public TransportAddress buildAddress(String host, String port, String file, Stri /** * Method declaration + * * @return * @see */ diff --git a/src/jade/imtp/leap/http/HTTPRequest.java b/src/jade/imtp/leap/http/HTTPRequest.java index b4bd5db..2cdb332 100644 --- a/src/jade/imtp/leap/http/HTTPRequest.java +++ b/src/jade/imtp/leap/http/HTTPRequest.java @@ -73,6 +73,7 @@ public void setFile(String f) { /** * Method declaration + * * @see */ public void readFrom(InputStream is) throws IOException { @@ -85,6 +86,7 @@ public void readFrom(InputStream is) throws IOException { /** * Method declaration + * * @see */ protected void writeTo(OutputStream os) throws IOException { @@ -94,6 +96,7 @@ protected void writeTo(OutputStream os) throws IOException { /** * Method declaration + * * @see */ public String toString() { diff --git a/src/jade/imtp/leap/http/HTTPResponse.java b/src/jade/imtp/leap/http/HTTPResponse.java index 27fd55b..f5689b5 100644 --- a/src/jade/imtp/leap/http/HTTPResponse.java +++ b/src/jade/imtp/leap/http/HTTPResponse.java @@ -84,6 +84,7 @@ protected void readFrom(InputStream is) throws IOException { /** * Method declaration + * * @see */ public void writeTo(OutputStream os) throws IOException { @@ -93,6 +94,7 @@ public void writeTo(OutputStream os) throws IOException { /** * Method declaration + * * @see */ public String toString() { diff --git a/src/jade/imtp/leap/http/HTTPServerConnection.java b/src/jade/imtp/leap/http/HTTPServerConnection.java index 219ee79..f470a27 100644 --- a/src/jade/imtp/leap/http/HTTPServerConnection.java +++ b/src/jade/imtp/leap/http/HTTPServerConnection.java @@ -42,12 +42,13 @@ import java.net.Socket; /** - * Connection class to handle HTTP requests/responses on + * Connection class to handle HTTP requests/responses on * the server side. - * Note that unlike the HTTPClientConnection that "looks - * like" a permanent pipe where several request/response sessions + * Note that unlike the HTTPClientConnection that "looks + * like" a permanent pipe where several request/response sessions * can occur, the HTTPServerConnection handles a single * request/response session. + * * @author Giovanni Caire - TILAB */ class HTTPServerConnection extends Connection { @@ -102,6 +103,7 @@ public int writePacket(JICPPacket pkt) throws IOException { } /** + * */ public void close() throws IOException { readAvailable = false; @@ -124,6 +126,7 @@ public void close() throws IOException { } /** + * */ public String getRemoteHost() throws Exception { return sc.getInetAddress().getHostAddress(); diff --git a/src/jade/imtp/leap/nio/BEManagementService.java b/src/jade/imtp/leap/nio/BEManagementService.java index 191460d..5e60fb0 100644 --- a/src/jade/imtp/leap/nio/BEManagementService.java +++ b/src/jade/imtp/leap/nio/BEManagementService.java @@ -101,14 +101,15 @@ public class BEManagementService extends BaseService { public static final String NAME = "BEManagement"; - + public static final String ADDITIONAL_SERVICES = "additional-services"; + public static final String INCOMING_CONNECTION = "Incoming-Connection"; + /** + * this property can be used to set how many bytes will be used when nio buffer need to be increased + */ + public static final String BUFFERINCREASE = "bufferincrease"; private static final String PREFIX = "jade_imtp_leap_nio_BEManagementService_"; - public static final String ACCEPT = PREFIX + "accept"; public static final String SERVERS = PREFIX + "servers"; - - public static final String ADDITIONAL_SERVICES = "additional-services"; - private static final int DEFAULT_PORT = 2099; private static final int DEFAULT_POOL_SIZE = 5; private static final int INIT_STATE = 0; @@ -116,21 +117,12 @@ public class BEManagementService extends BaseService { private static final int TERMINATING_STATE = 2; private static final int TERMINATED_STATE = 3; private static final int ERROR_STATE = -1; - - public static final String INCOMING_CONNECTION = "Incoming-Connection"; - - // since this is the only service dealing with NIO it is ok to set the size used for enlarging buffers here - private static int bufferIncreaseSize = 1024; - /** - * this property can be used to set how many bytes will be used when nio buffer need to be increased - */ - public static final String BUFFERINCREASE = "bufferincrease"; - private static final String[] OWNED_COMMANDS = new String[]{ INCOMING_CONNECTION }; - private static final Map> protocolManagers = new HashMap<>(); + // since this is the only service dealing with NIO it is ok to set the size used for enlarging buffers here + private static int bufferIncreaseSize = 1024; static { protocolManagers.put(MicroRuntime.SOCKET_PROTOCOL, NIOJICPPeer.class); @@ -139,20 +131,18 @@ public class BEManagementService extends BaseService { protocolManagers.put(MicroRuntime.HTTPS_PROTOCOL, NIOHTTPSPeer.class); } - private final Hashtable servers = new Hashtable(2); - private Ticker myTicker; - private ServiceHelper myHelper; - private String platformName; + private final Hashtable servers = new Hashtable<>(2); // The list of addresses considered malicious. Connections from // these addresses will be rejected. // FIXME: The mechanism for filling/clearing this list is not yet // defined/implemented - private final Vector maliciousAddresses = new Vector(); - + private final Vector maliciousAddresses = new Vector<>(); private final String configOptionsFileName = "feOptions.properties"; - + private final Logger myLogger = Logger.getJADELogger(getClass().getName()); + private Ticker myTicker; + private ServiceHelper myHelper; + private String platformName; private AgentContainer myContainer; - // SAM related variables private long createMediatorCounter = 0; private long connectMediatorCounter = 0; @@ -167,7 +157,9 @@ public class BEManagementService extends BaseService { private AverageMeasureProviderImpl dataProcessingTimeProvider = null; private AverageMeasureProviderImpl waitForDataTimeProvider = null; - private final Logger myLogger = Logger.getJADELogger(getClass().getName()); + public static final int getBufferIncreaseSize() { + return bufferIncreaseSize; + } /** * @return The name of this service. @@ -177,10 +169,6 @@ public String getName() { return className.substring(0, className.indexOf("Service")); } - public static final int getBufferIncreaseSize() { - return bufferIncreaseSize; - } - public String[] getOwnedCommands() { return OWNED_COMMANDS; } @@ -352,8 +340,8 @@ public boolean isDifferential() { // Number of active BackEnds samHelper.addEntityMeasureProvider("BackEnd_Number", () -> { int cnt = 0; - for (Object o : servers.values()) { - cnt += ((IOEventServer) o).mediators.values().size(); + for (IOEventServer o : servers.values()) { + cnt += o.mediators.values().size(); } return cnt; }); @@ -361,8 +349,8 @@ public boolean isDifferential() { // Number of opened socket samHelper.addEntityMeasureProvider("Socket_Number", () -> { int cnt = 0; - for (Object o : servers.values()) { - cnt += ((IOEventServer) o).getSocketCnt(); + for (IOEventServer o : servers.values()) { + cnt += o.getSocketCnt(); } return cnt; }); @@ -486,6 +474,40 @@ private String encodeConfigOptionsResponse() throws Exception { return FrontEndStub.encodeProperties(pp); } + /////////////////////////////////////// + // Utility methods + /////////////////////////////////////// + private void mergeProperties(Properties p1, Properties p2) { + Enumeration e = (Enumeration) p2.propertyNames(); + while (e.hasMoreElements()) { + String key = e.nextElement(); + p1.setProperty(key, p2.getProperty(key)); + } + } + + private void waitABit(long t) { + try { + Thread.sleep(t); + } catch (InterruptedException ie) { + } + } + + /** + * Check that the address of the initiator of a new connection + * is not in the list of addresses considered as malicious. + */ + private void checkAddress(SocketChannel sc) throws JADESecurityException { + Socket s = sc.socket(); + InetAddress address = s.getInetAddress(); + if (maliciousAddresses.contains(address)) { + try { + sc.close(); + } catch (Exception e) { + } + throw new JADESecurityException(address.toString()); + } + } + /** * Inner class IOEventServer. * This class asynchronously manages a server socket and all IO Events @@ -494,16 +516,16 @@ private String encodeConfigOptionsResponse() throws Exception { */ private class IOEventServer implements PDPContextManager, PDPContextManager.Listener, JICPMediatorManager { + private final int state = INIT_STATE; + private final Hashtable mediators = new Hashtable<>(); + private final Vector deregisteredMediators = new Vector<>(); + private final Properties leapProps = new Properties(); private String myID; private String myLogPrefix; - private final int state = INIT_STATE; private ServerSocketChannel mySSChannel; private long mediatorCnt = 1; - private final Hashtable mediators = new Hashtable<>(); - private final Vector deregisteredMediators = new Vector<>(); private String host; private int port; - private final Properties leapProps = new Properties(); private PDPContextManager myPDPContextManager; private TransportProtocol myProtocol; private ConnectionFactory myConnectionFactory; @@ -800,7 +822,6 @@ public void servePacket(KeyManager mgr, JICPPacket pkt) { // Respond sending back the current time encoded as a String myLogger.log(Logger.INFO, myLogPrefix + "GET_SERVER_TIME request received from " + address + ":" + port); reply = new JICPPacket(JICPProtocol.RESPONSE_TYPE, JICPProtocol.DEFAULT_INFO, String.valueOf(System.currentTimeMillis()).getBytes()); - break; } case JICPProtocol.GET_ADDRESS_TYPE -> { // Respond sending back the caller address and (if requested) port @@ -810,14 +831,12 @@ public void servePacket(KeyManager mgr, JICPPacket pkt) { addressStr += ":" + port; } reply = new JICPPacket(JICPProtocol.RESPONSE_TYPE, JICPProtocol.DEFAULT_INFO, addressStr.getBytes()); - break; } case JICPProtocol.GET_CONFIG_OPTIONS_TYPE -> { // Respond sending back the configuration options myLogger.log(Logger.INFO, myLogPrefix + "GET_CONFIGURATION_OPTIONS request received from " + address + ":" + port); String replyMsg = encodeConfigOptionsResponse(); reply = new JICPPacket(JICPProtocol.RESPONSE_TYPE, JICPProtocol.DEFAULT_INFO, replyMsg.getBytes()); - break; } case JICPProtocol.CREATE_MEDIATOR_TYPE -> { createMediatorCounter++; @@ -912,7 +931,6 @@ public void servePacket(KeyManager mgr, JICPPacket pkt) { myLogger.log(Logger.WARNING, myLogPrefix + "CREATE_MEDIATOR request received on a connection already linked to an existing mediator"); reply = new JICPPacket("Unexpected packet type", null); } - break; } case JICPProtocol.CONNECT_MEDIATOR_TYPE -> { connectMediatorCounter++; @@ -960,7 +978,6 @@ public void servePacket(KeyManager mgr, JICPPacket pkt) { myLogger.log(Logger.WARNING, myLogPrefix + "CONNECT_MEDIATOR request received on a connection already linked to an existing mediator"); reply = new JICPPacket("Unexpected packet type", null); } - break; } default -> { // Pass all other JICP packets (commands, responses, keep-alives ...) to the proper mediator. @@ -1262,7 +1279,6 @@ public int getSocketCnt() { } } // END of inner class IOEventServer - /** * Inner class KeyManager * Keep a SelectionKey together with the information associated to it @@ -1273,8 +1289,8 @@ private class KeyManager { private final SelectionKey key; private final NIOJICPConnectionWrapper connection; - private NIOMediator mediator; private final IOEventServer server; + private NIOMediator mediator; public KeyManager(SelectionKey k, NIOJICPConnectionWrapper c, IOEventServer s) { key = k; @@ -1328,11 +1344,11 @@ private class LoopManager implements Runnable { private final int myIndex; private final String displayId; - private int state = INIT_STATE; private final int replaceCnt; + private final IOEventServer myServer; + private int state = INIT_STATE; private Selector mySelector; private Thread myThread; - private final IOEventServer myServer; private boolean pendingChannelPresent = false; private List pendingChannels = new ArrayList<>(); @@ -1675,39 +1691,5 @@ private NIOMediator findMediatorGlobally(String id) { return null; } } // END of inner class BEManagementHelperImpl - - /////////////////////////////////////// - // Utility methods - /////////////////////////////////////// - private void mergeProperties(Properties p1, Properties p2) { - Enumeration e = (Enumeration) p2.propertyNames(); - while (e.hasMoreElements()) { - String key = e.nextElement(); - p1.setProperty(key, p2.getProperty(key)); - } - } - - private void waitABit(long t) { - try { - Thread.sleep(t); - } catch (InterruptedException ie) { - } - } - - /** - * Check that the address of the initiator of a new connection - * is not in the list of addresses considered as malicious. - */ - private void checkAddress(SocketChannel sc) throws JADESecurityException { - Socket s = sc.socket(); - InetAddress address = s.getInetAddress(); - if (maliciousAddresses.contains(address)) { - try { - sc.close(); - } catch (Exception e) { - } - throw new JADESecurityException(address.toString()); - } - } } diff --git a/src/jade/imtp/leap/nio/BackEndDispatcher.java b/src/jade/imtp/leap/nio/BackEndDispatcher.java index edf8b71..b41b2d7 100644 --- a/src/jade/imtp/leap/nio/BackEndDispatcher.java +++ b/src/jade/imtp/leap/nio/BackEndDispatcher.java @@ -20,6 +20,12 @@ */ public class BackEndDispatcher implements NIOMediator, BEConnectionManager, Dispatcher { + private final Object writeLock = new Object(); + private final Logger myLogger = Logger.getMyLogger(getClass().getName()); + // Local variable only used in the kill() method + private final Object shutdownLock = new Object(); + protected InputManager inpManager; + protected OutputManager outManager; private long responseTimeoutOffset; private double responseTimeoutMultiplicativeFactor; private long keepAliveTime; @@ -30,18 +36,11 @@ public class BackEndDispatcher implements NIOMediator, BEConnectionManager, Disp private boolean peerActive = true; private boolean connectionDropped = false; private long dropTimeStamp = -1; - private JICPMediatorManager myMediatorManager; private String myID; private Properties myProperties; private BackEndContainer myContainer = null; - private Connection myConnection = null; - private final Object writeLock = new Object(); - protected InputManager inpManager; - protected OutputManager outManager; - - private final Logger myLogger = Logger.getMyLogger(getClass().getName()); /** * Retrieve the ID of this mediator. Returns null if this mediator @@ -108,7 +107,7 @@ public void init(JICPMediatorManager mgr, String id, Properties props) throws IC // Keep default } myLogger.log(Logger.CONFIG, "Next command for FE will have sessionID " + inpCnt); - + /* lastSid int lastSid = 0x0f; try { @@ -151,9 +150,6 @@ protected final BackEndSkel startBackEndContainer(Properties props) throws ICPEx } } - // Local variable only used in the kill() method - private final Object shutdownLock = new Object(); - /** * Kill the above container. * This may be called by the JICPMediatorManager or when @@ -502,18 +498,42 @@ private void updateConnectedState() { myProperties.put(BEManagementHelper.CONNECTED, (isConnected() ? "true" : "false")); } + private synchronized void setExpirationDeadline() { + expirationDeadline = System.currentTimeMillis() + maxDisconnectionTime; + } + + private synchronized boolean checkMaxDisconnectionTime(long currentTime) { + return (!isConnected()) && (currentTime > expirationDeadline); + } + + private boolean checkTerminatedInfo(JICPPacket pkt) { + if ((pkt.getInfo() & JICPProtocol.TERMINATED_INFO) != 0) { + // In some mysterious cases we receive dirty data from the network + // If the second byte has bit 7 = 1, we may confuse such dirty data with a + // termination packet --> Check that the packet is valid + int type = pkt.getType(); + if (type == JICPProtocol.COMMAND_TYPE || type == JICPProtocol.RESPONSE_TYPE || type == JICPProtocol.CONNECT_MEDIATOR_TYPE) { + peerActive = false; + myLogger.log(Logger.INFO, myID + ": Peer termination notification received"); + if (pkt.getType() == JICPProtocol.COMMAND_TYPE) { + // Spontaneous FE termination. Unblock any Thread waiting for a response. It will behave as if the response timeout was expired + inpManager.notifyIncomingResponseReceived(null); + } + } + } + return peerActive; + } /** * Inner class InputManager. * This class manages the delivery of commands to the FrontEnd */ protected class InputManager { + private final FrontEndStub myStub; private boolean dispatching = false; private boolean waitingForFlush; private JICPPacket lastIncomingResponse; - private int inpCnt; - private final FrontEndStub myStub; InputManager(int c, FrontEndStub s) { inpCnt = c; @@ -637,16 +657,15 @@ private synchronized void notifyIncomingResponseReceived(JICPPacket rsp) { } } // END of inner class InputManager - /** * Inner class OutputManager * This class manages the reception of commands and keep-alive * packets from the FrontEnd. */ protected class OutputManager { + private final BackEndSkel mySkel; private JICPPacket lastResponse; private int lastSid; - private final BackEndSkel mySkel; OutputManager(int n, BackEndSkel s) { lastSid = n; @@ -687,32 +706,5 @@ final JICPPacket handleKeepAlive(JICPPacket command) throws ICPException { return new JICPPacket(JICPProtocol.RESPONSE_TYPE, JICPProtocol.DEFAULT_INFO, null); } } // END of inner class OutputManager - - - private synchronized void setExpirationDeadline() { - expirationDeadline = System.currentTimeMillis() + maxDisconnectionTime; - } - - private synchronized boolean checkMaxDisconnectionTime(long currentTime) { - return (!isConnected()) && (currentTime > expirationDeadline); - } - - private boolean checkTerminatedInfo(JICPPacket pkt) { - if ((pkt.getInfo() & JICPProtocol.TERMINATED_INFO) != 0) { - // In some mysterious cases we receive dirty data from the network - // If the second byte has bit 7 = 1, we may confuse such dirty data with a - // termination packet --> Check that the packet is valid - int type = pkt.getType(); - if (type == JICPProtocol.COMMAND_TYPE || type == JICPProtocol.RESPONSE_TYPE || type == JICPProtocol.CONNECT_MEDIATOR_TYPE) { - peerActive = false; - myLogger.log(Logger.INFO, myID + ": Peer termination notification received"); - if (pkt.getType() == JICPProtocol.COMMAND_TYPE) { - // Spontaneous FE termination. Unblock any Thread waiting for a response. It will behave as if the response timeout was expired - inpManager.notifyIncomingResponseReceived(null); - } - } - } - return peerActive; - } } diff --git a/src/jade/imtp/leap/nio/NIOBEDispatcher.java b/src/jade/imtp/leap/nio/NIOBEDispatcher.java index a90a916..dc3ff21 100644 --- a/src/jade/imtp/leap/nio/NIOBEDispatcher.java +++ b/src/jade/imtp/leap/nio/NIOBEDispatcher.java @@ -21,6 +21,11 @@ public class NIOBEDispatcher implements NIOMediator, BEConnectionManager, Dispatcher { private static final long RESPONSE_TIMEOUT = 60000; + private final Logger myLogger = Logger.getMyLogger(getClass().getName()); + // Local variable only used in the kill() method + private final Object shutdownLock = new Object(); + protected InputManager inpManager; + protected OutputManager outManager; private long keepAliveTime; private boolean enableServerKeepAlive; private long lastReceivedTime; @@ -31,9 +36,6 @@ public class NIOBEDispatcher implements NIOMediator, BEConnectionManager, Dispat private String myID; private Properties myProperties; private BackEndContainer myContainer = null; - protected InputManager inpManager; - protected OutputManager outManager; - private final Logger myLogger = Logger.getMyLogger(getClass().getName()); /** * Retrieve the ID of this mediator. Returns null if this mediator @@ -131,9 +133,6 @@ protected final BackEndSkel startBackEndContainer(Properties props) throws ICPEx } } - // Local variable only used in the kill() method - private final Object shutdownLock = new Object(); - /** * Kill the above container. * This may be called by the JICPMediatorManager or when @@ -442,21 +441,46 @@ private void updateConnectedState() { myProperties.put(BEManagementHelper.CONNECTED, (isConnected() ? "true" : "false")); } + private byte getReconnectInfo() { + byte info = JICPProtocol.DEFAULT_INFO; + // If the inpConnection is null request the FrontEnd to reconnect + if (!inpManager.isConnected()) { + info |= JICPProtocol.RECONNECT_INFO; + } + return info; + } + + private void checkTerminatedInfo(JICPPacket pkt) { + if ((pkt.getInfo() & JICPProtocol.TERMINATED_INFO) != 0) { + peerActive = false; + if (myLogger.isLoggable(Logger.INFO)) { + myLogger.log(Logger.INFO, myID + ": Peer termination notification received"); + } + } + } + + private void close(Connection c) { + try { + c.close(); + } catch (IOException ioe) { + } + } + /** * Inner class InputManager. * This class manages the delivery of commands to the FrontEnd */ protected class InputManager { + private final Object dispatchLock = new Object(); + private final FrontEndStub myStub; private NIOJICPConnection myConnection; private boolean dispatching = false; private boolean connectionRefreshed; private boolean waitingForFlush; private long readStartTime = -1; private JICPPacket currentReply; - private final Object dispatchLock = new Object(); private int inpCnt; - private final FrontEndStub myStub; InputManager(int c, FrontEndStub s) { inpCnt = c; @@ -651,11 +675,11 @@ private synchronized JICPPacket waitForReply(long timeout) throws ICPException, */ protected class OutputManager { + private final BackEndSkel mySkel; + private final long maxDisconnectionTime; private Connection myConnection; private JICPPacket lastResponse; private int lastSid; - private final BackEndSkel mySkel; - private final long maxDisconnectionTime; private long expirationDeadline; OutputManager(int n, BackEndSkel s, long t) { @@ -738,30 +762,5 @@ final synchronized boolean checkMaxDisconnectionTime(long currentTime) { return (!isConnected()) && (currentTime > expirationDeadline); } } // END of inner class OutputManager - - private byte getReconnectInfo() { - byte info = JICPProtocol.DEFAULT_INFO; - // If the inpConnection is null request the FrontEnd to reconnect - if (!inpManager.isConnected()) { - info |= JICPProtocol.RECONNECT_INFO; - } - return info; - } - - private void checkTerminatedInfo(JICPPacket pkt) { - if ((pkt.getInfo() & JICPProtocol.TERMINATED_INFO) != 0) { - peerActive = false; - if (myLogger.isLoggable(Logger.INFO)) { - myLogger.log(Logger.INFO, myID + ": Peer termination notification received"); - } - } - } - - private void close(Connection c) { - try { - c.close(); - } catch (IOException ioe) { - } - } } diff --git a/src/jade/imtp/leap/nio/NIOHTTPBEDispatcher.java b/src/jade/imtp/leap/nio/NIOHTTPBEDispatcher.java index 123bbbd..3ff6fad 100644 --- a/src/jade/imtp/leap/nio/NIOHTTPBEDispatcher.java +++ b/src/jade/imtp/leap/nio/NIOHTTPBEDispatcher.java @@ -33,31 +33,26 @@ public class NIOHTTPBEDispatcher implements NIOMediator, Dispatcher, BEConnectio private static final long RESPONSE_TIMEOUT_INCREMENT = 100; // 100 msec private static final int MAX_SID = 0x0f; - + private final Object outgoingCommandsConnectionLock = new Object(); + private final Object responseToLastOutgoingCommandLock = new Object(); + private final Logger myLogger = Logger.getMyLogger(getClass().getName()); private JICPMediatorManager myMediatorManager; private String myID; private MicroSkeleton mySkel = null; private FrontEndStub myStub = null; private BackEndContainer myContainer = null; - private int status = ACTIVE; private int frontEndStatus = CONNECTING; private long maxDisconnectionTime; private Timer maxDisconnectionTimer = null; private long keepAliveTime; private Timer keepAliveTimer = null; - private JICPPacket lastResponse = null; private byte lastIncomingCommandSid; - private boolean waitingForFlush = false; private Connection outgoingCommandsConnection = null; - private final Object outgoingCommandsConnectionLock = new Object(); private int nextOutgoingCommandSid; private JICPPacket responseToLastOutgoingCommand = null; - private final Object responseToLastOutgoingCommandLock = new Object(); - - private final Logger myLogger = Logger.getMyLogger(getClass().getName()); ////////////////////////////////////////// // NIOMediator interface implementation diff --git a/src/jade/imtp/leap/nio/NIOHTTPConnection.java b/src/jade/imtp/leap/nio/NIOHTTPConnection.java index 7aed17e..d22f2f8 100644 --- a/src/jade/imtp/leap/nio/NIOHTTPConnection.java +++ b/src/jade/imtp/leap/nio/NIOHTTPConnection.java @@ -15,6 +15,7 @@ */ public class NIOHTTPConnection extends NIOJICPConnection { + private static final Logger log = Logger.getLogger(NIOHTTPConnection.class.getName()); private NIOHTTPHelper helper; @Override @@ -24,6 +25,4 @@ void init(SocketChannel channel) throws ICPException { addBufferTransformer(helper); } - private static final Logger log = Logger.getLogger(NIOHTTPConnection.class.getName()); - } diff --git a/src/jade/imtp/leap/nio/NIOHTTPHelper.java b/src/jade/imtp/leap/nio/NIOHTTPHelper.java index 8e2fdb1..7b8894b 100644 --- a/src/jade/imtp/leap/nio/NIOHTTPHelper.java +++ b/src/jade/imtp/leap/nio/NIOHTTPHelper.java @@ -16,11 +16,15 @@ */ public class NIOHTTPHelper extends HTTPHelper implements BufferTransformer { + private static final Logger log = Logger.getLogger(NIOHTTPHelper.class.getName()); //private boolean needToRead = false; NIOJICPConnection connection; - private static final Logger log = Logger.getLogger(NIOHTTPHelper.class.getName()); + public NIOHTTPHelper(NIOJICPConnection connection) { + this.connection = connection; + } + public static ByteBuffer readByteBufferFromHttp(InputStream is) throws IOException { HTTPRequest request = new HTTPRequest(); request.readFrom(is); @@ -50,10 +54,6 @@ public static ByteBuffer readByteBufferFromHttp(InputStream is) throws IOExcepti } } - public NIOHTTPHelper(NIOJICPConnection connection) { - this.connection = connection; - } - private static ByteBuffer wrapInHttpResponse(ByteBuffer pkt) throws IOException { byte[] b = new byte[pkt.remaining()]; pkt.get(b, 0, pkt.remaining()); diff --git a/src/jade/imtp/leap/nio/NIOHTTPSConnection.java b/src/jade/imtp/leap/nio/NIOHTTPSConnection.java index 4128c14..b6023b2 100644 --- a/src/jade/imtp/leap/nio/NIOHTTPSConnection.java +++ b/src/jade/imtp/leap/nio/NIOHTTPSConnection.java @@ -16,8 +16,8 @@ * @author eduard */ public class NIOHTTPSConnection extends NIOHTTPConnection { - private SSLEngineHelper helper = null; private static final Logger log = Logger.getLogger(NIOHTTPSConnection.class.getName()); + private SSLEngineHelper helper = null; @Override public void close() throws IOException { diff --git a/src/jade/imtp/leap/nio/NIOHelper.java b/src/jade/imtp/leap/nio/NIOHelper.java index ff1e980..de2f0f6 100644 --- a/src/jade/imtp/leap/nio/NIOHelper.java +++ b/src/jade/imtp/leap/nio/NIOHelper.java @@ -17,12 +17,11 @@ */ public class NIOHelper { public static final ByteBuffer EMPTY_BUFFER = ByteBuffer.allocateDirect(0); + private static final Logger log = Logger.getLogger(NIOHelper.class.getName()); private NIOHelper() { } - private static final Logger log = Logger.getLogger(NIOHelper.class.getName()); - /** * logs info on a bytebuffer at level FINE with name "unknown" * diff --git a/src/jade/imtp/leap/nio/NIOJICPConnection.java b/src/jade/imtp/leap/nio/NIOJICPConnection.java index d7a7653..1856d0b 100644 --- a/src/jade/imtp/leap/nio/NIOJICPConnection.java +++ b/src/jade/imtp/leap/nio/NIOJICPConnection.java @@ -25,24 +25,19 @@ public class NIOJICPConnection extends Connection { public static final int MAX_HEADER_SIZE = 263; // TODO 1k, why? configurable? public static final int INITIAL_BUFFER_SIZE = 1024; - + private static final Logger log = Logger.getLogger(NIOJICPConnection.class.getName()); private SocketChannel myChannel; private ByteBuffer socketData; private ByteBuffer payloadBuf; private ByteBuffer unmanagedJicpData = null; - private byte type; private byte info; private byte sessionID; private String recipientID; - private boolean headerReceived = false; private boolean closed = false; - private List transformers; - private static final Logger log = Logger.getLogger(NIOJICPConnection.class.getName()); - public NIOJICPConnection() { socketData = ByteBuffer.allocateDirect(INITIAL_BUFFER_SIZE); payloadBuf = ByteBuffer.allocateDirect(INITIAL_BUFFER_SIZE); diff --git a/src/jade/imtp/leap/nio/NIOJICPSConnection.java b/src/jade/imtp/leap/nio/NIOJICPSConnection.java index 561fde3..961a772 100644 --- a/src/jade/imtp/leap/nio/NIOJICPSConnection.java +++ b/src/jade/imtp/leap/nio/NIOJICPSConnection.java @@ -25,8 +25,8 @@ */ public class NIOJICPSConnection extends NIOJICPConnection { - private SSLEngineHelper helper = null; private static final Logger log = Logger.getLogger(NIOJICPSConnection.class.getName()); + private SSLEngineHelper helper = null; public NIOJICPSConnection() { } diff --git a/src/jade/imtp/leap/nio/SSLEngineHelper.java b/src/jade/imtp/leap/nio/SSLEngineHelper.java index f3f2868..ba76ff6 100644 --- a/src/jade/imtp/leap/nio/SSLEngineHelper.java +++ b/src/jade/imtp/leap/nio/SSLEngineHelper.java @@ -25,16 +25,12 @@ public final class SSLEngineHelper implements BufferTransformer { public static final ByteBuffer EMPTY_BUFFER = NIOHelper.EMPTY_BUFFER; - + private static final Logger log = Logger.getLogger(SSLEngineHelper.class.getName()); private SSLEngine ssle = null; - private ByteBuffer wrapData; private ByteBuffer unwrapData; - private NIOJICPConnection connection = null; - private static final Logger log = Logger.getLogger(SSLEngineHelper.class.getName()); - /** * Creates and initializes ByteBuffers and SSLEngine necessary for ssl/nio. * see NIOHelper diff --git a/src/jade/imtp/leap/sms/Boot.java b/src/jade/imtp/leap/sms/Boot.java index 06647bd..b47a2aa 100644 --- a/src/jade/imtp/leap/sms/Boot.java +++ b/src/jade/imtp/leap/sms/Boot.java @@ -30,9 +30,10 @@ import jade.core.Runtime; /** - Utility class that boots the JADE runtime system and automatically - starts the SMSManager. - @author Giovanni Caire - TILAB + * Utility class that boots the JADE runtime system and automatically + * starts the SMSManager. + * + * @author Giovanni Caire - TILAB */ public class Boot extends jade.Boot { public static void main(String[] args) { diff --git a/src/jade/imtp/leap/sms/PhoneBasedSMSManager.java b/src/jade/imtp/leap/sms/PhoneBasedSMSManager.java index 06ada76..ebdc99e 100644 --- a/src/jade/imtp/leap/sms/PhoneBasedSMSManager.java +++ b/src/jade/imtp/leap/sms/PhoneBasedSMSManager.java @@ -46,13 +46,10 @@ public class PhoneBasedSMSManager extends SMSManager { private static final int IDLE = 0; private static final int CONNECTED = 1; private static final int TERMINATED = 2; - + private final Logger myLogger = Logger.getMyLogger(getClass().getName()); private int status = IDLE; - private Connection myConnection; - private final Logger myLogger = Logger.getMyLogger(getClass().getName()); - protected void init(Properties pp) throws ICPException { super.init(pp); diff --git a/src/jade/imtp/leap/sms/SMSBEDispatcher.java b/src/jade/imtp/leap/sms/SMSBEDispatcher.java index 6a08a8a..6b24d1a 100644 --- a/src/jade/imtp/leap/sms/SMSBEDispatcher.java +++ b/src/jade/imtp/leap/sms/SMSBEDispatcher.java @@ -43,10 +43,10 @@ */ public class SMSBEDispatcher extends NIOBEDispatcher { + private final Logger myLogger = Logger.getMyLogger(getClass().getName()); private SMSManager theSMSManager; private int smsPort; private String msisdn; - private final Logger myLogger = Logger.getMyLogger(getClass().getName()); public void init(JICPMediatorManager mgr, String id, Properties props) throws ICPException { // Get the msisdn diff --git a/src/jade/imtp/leap/sms/SMSManagerGui.java b/src/jade/imtp/leap/sms/SMSManagerGui.java index 88a23f8..d12e631 100644 --- a/src/jade/imtp/leap/sms/SMSManagerGui.java +++ b/src/jade/imtp/leap/sms/SMSManagerGui.java @@ -22,6 +22,21 @@ public SMSManagerGui() { super("SMS Manager GUI"); } + public static void main(String[] args) { + if (args != null && args.length == 1) { + try { + Properties pp = new Properties(); + pp.load(new FileReader(args[0])); + SMSManagerGui gui = new SMSManagerGui(); + gui.init(pp); + } catch (IOException ioe) { + ioe.printStackTrace(); + } + } else { + System.out.println("USAGE: java SMSManagerGui "); + } + } + public void init(Properties pp) { theSMSManager = SMSManager.getInstance(pp); @@ -97,20 +112,5 @@ private Dimension getProperSize(int maxX, int maxY) { int y = (Math.min(screenSize.height, maxY)); return new Dimension(x, y); } - - public static void main(String[] args) { - if (args != null && args.length == 1) { - try { - Properties pp = new Properties(); - pp.load(new FileReader(args[0])); - SMSManagerGui gui = new SMSManagerGui(); - gui.init(pp); - } catch (IOException ioe) { - ioe.printStackTrace(); - } - } else { - System.out.println("USAGE: java SMSManagerGui "); - } - } } \ No newline at end of file diff --git a/src/jade/imtp/rmi/NodeAdapter.java b/src/jade/imtp/rmi/NodeAdapter.java index 5b419a9..f527ac5 100644 --- a/src/jade/imtp/rmi/NodeAdapter.java +++ b/src/jade/imtp/rmi/NodeAdapter.java @@ -41,6 +41,8 @@ */ class NodeAdapter extends BaseNode { + private NodeRMI adaptee; + public NodeAdapter(String name, boolean hasSM, int port, RMIIMTPManager mgr) throws RemoteException { super(name, hasSM); try { @@ -100,6 +102,4 @@ public void platformManagerDead(String deadPmAddress, String notifyingPmAddr) th } } - private NodeRMI adaptee; - } diff --git a/src/jade/imtp/rmi/NodeRMIImpl.java b/src/jade/imtp/rmi/NodeRMIImpl.java index 5db1ba2..a0e52e1 100644 --- a/src/jade/imtp/rmi/NodeRMIImpl.java +++ b/src/jade/imtp/rmi/NodeRMIImpl.java @@ -37,6 +37,12 @@ */ class NodeRMIImpl extends UnicastRemoteObject implements NodeRMI { + // This monitor is used to hang a remote ping() call in order to + // detect node failures. + private final Object terminationLock = new Object(); + private final NodeAdapter myNode; + private boolean terminating = false; + public NodeRMIImpl(NodeAdapter impl, int port, RMIIMTPManager mgr) throws RemoteException { super(port, mgr.getClientSocketFactory(), mgr.getServerSocketFactory()); myNode = impl; @@ -95,12 +101,4 @@ private void notifyTermination() { } } - - // This monitor is used to hang a remote ping() call in order to - // detect node failures. - private final Object terminationLock = new Object(); - private boolean terminating = false; - - private final NodeAdapter myNode; - } diff --git a/src/jade/imtp/rmi/RMIAddress.java b/src/jade/imtp/rmi/RMIAddress.java index 083e5e0..b7c3d3f 100644 --- a/src/jade/imtp/rmi/RMIAddress.java +++ b/src/jade/imtp/rmi/RMIAddress.java @@ -32,6 +32,7 @@ /** * Class declaration + * * @author LEAP */ public class RMIAddress implements TransportAddress { @@ -48,6 +49,7 @@ public RMIAddress() { /** * Constructor declaration + * * @param host * @param port * @param file @@ -62,6 +64,7 @@ public RMIAddress(String host, String port, String file, String anchor) { /** * Method declaration + * * @return * @see */ @@ -71,6 +74,7 @@ public String getProto() { /** * Method declaration + * * @return * @see */ @@ -80,6 +84,7 @@ public String getHost() { /** * Method declaration + * * @return * @see */ @@ -89,6 +94,7 @@ public String getPort() { /** * Method declaration + * * @return * @see */ @@ -98,6 +104,7 @@ public String getFile() { /** * Method declaration + * * @return * @see */ diff --git a/src/jade/imtp/rmi/RMIIMTPManager.java b/src/jade/imtp/rmi/RMIIMTPManager.java index 447e94f..af85bca 100644 --- a/src/jade/imtp/rmi/RMIIMTPManager.java +++ b/src/jade/imtp/rmi/RMIIMTPManager.java @@ -66,40 +66,33 @@ public class RMIIMTPManager implements IMTPManager { public static final String ENABLE_RMI_LOG = "jade_imtp_rmi_RMIIMTPManager_enablermilog"; private static final int DEFAULT_RMI_PORT = 1099; - - + private static final char SLASH = '/'; + private static final char COLON = ':'; + private static final char DIESIS = '#'; + private final Logger myLogger = Logger.getMyLogger(getClass().getName()); private Profile myProfile; - // Host and port where the original RMI Registry is listening private String mainHost; private int mainPort; - // Host and port where the local RMI Registry (if any) is listening private String localHost; private int localPort; - // Port where the local Service Manager (if any) is listening private int localSvcMgrPort; - // Port where the local RMI Node is listening private int localNodePort; - // The RMI URL where the Service Manager is to be. If there is a // locally installed one, this string points to it, otherwise it // points to the Service Manager of the original one. //private String baseRMI; private String localAddr; - - // The RMI URL where the original (i.e. the first replica) Service // Manager is to be found. //private String originalRMI; private String originalPMAddr; - private NodeAdapter localNode; private ServiceManagerRMIImpl myRMIServiceManager; - private final Logger myLogger = Logger.getMyLogger(getClass().getName()); public RMIIMTPManager() { } @@ -187,7 +180,6 @@ public void initialize(Profile p) throws IMTPException { } } - /** * Get the RMIRegistry. If a registry is already active on this host * and the given portNumber, then that registry is returned, @@ -213,7 +205,6 @@ private Registry getRmiRegistry(String host, int portNumber) throws RemoteExcept } // END getRmiRegistry() - public void exportPlatformManager(PlatformManager mgr) throws IMTPException { try { String svcMgrName = localAddr + SERVICE_MANAGER_NAME; @@ -243,7 +234,7 @@ public void exportPlatformManager(PlatformManager mgr) throws IMTPException { throw new IMTPException("Cannot attach to the original PlatformManager.", se); } catch (IMTPException imtpe) { Throwable t = imtpe.getNested(); - if ((t != null) && (t instanceof ConnectException)) { + if ((t instanceof ConnectException)) { // The master main container does not exist. Become the leader myLogger.log(Logger.INFO, "No master Main Container found at address " + originalPMAddr + ". Take the leadership"); originalPMAddr = null; @@ -275,7 +266,6 @@ public void exportPlatformManager(PlatformManager mgr) throws IMTPException { } } - public void unexportPlatformManager(PlatformManager mgr) throws IMTPException { if (myRMIServiceManager != null && myRMIServiceManager.getPlatformManager().equals(mgr)) { // Unexport the PlatformManager we are currently exporting @@ -293,7 +283,6 @@ public void unexportPlatformManager(PlatformManager mgr) throws IMTPException { } } - public PlatformManager getPlatformManagerProxy() throws IMTPException { return getPlatformManagerProxy("rmi://" + mainHost + ":" + mainPort + "/"); } @@ -366,7 +355,6 @@ public boolean compareAddresses(String addr1, String addr2) { return addr1.equalsIgnoreCase(addr2); } - /** * Creates the client socket factory, which will be used * to instantiate a UnicastRemoteObject. @@ -387,10 +375,6 @@ public RMIServerSocketFactory getServerSocketFactory() { return null; } - private static final char SLASH = '/'; - private static final char COLON = ':'; - private static final char DIESIS = '#'; - public TransportAddress stringToAddr(String url) throws IMTPException { // FIXME: Refactor this code with jade.imtp.leap.TrasportProtocol.parseURL() if (url == null) { diff --git a/src/jade/lang/acl/ACLCodec.java b/src/jade/lang/acl/ACLCodec.java index 75c07b7..6c26666 100644 --- a/src/jade/lang/acl/ACLCodec.java +++ b/src/jade/lang/acl/ACLCodec.java @@ -40,6 +40,38 @@ public interface ACLCodec { public static final String DEFAULT_CHARSET = "ISO-8859-1"; #DOTNET_INCLUDE_END*/ + /** + * Encodes an ACLMessage object into a byte sequence, + * according to the specific message representation. + * + * @param msg The ACL message to encode. + * @param charset Charset encoding to use (e.g. US_ASCII, UTF-8, etc) + * @return a byte array, containing the encoded message. + */ + byte[] encode(ACLMessage msg, String charset); + + /** + * Recovers an ACLMessage object back from raw data, + * using the specific message representation to interpret the byte + * sequence. + * + * @param data The byte sequence containing the encoded message. + * @param charset Charset encoding to use (e.g. US_ASCII, UTF-8, etc) + * @return A new ACLMessage object, built from the raw + * data. + * @throws CodecException If some kind of syntax error occurs. + */ + ACLMessage decode(byte[] data, String charset) throws CodecException; + + /** + * Query the name of the message representation handled by this + * Codec object. The FIPA standard representations have + * a name starting with "fipa.acl.rep.". + * + * @return The name of the handled ACL message representation. + */ + String getName(); + /** * This exception is thrown when some problem occurs in the concrete parsing * subsystem accessed through this interface. If an exception is thrown by the @@ -85,37 +117,4 @@ public void printStackTrace() { } } - - /** - * Encodes an ACLMessage object into a byte sequence, - * according to the specific message representation. - * - * @param msg The ACL message to encode. - * @param charset Charset encoding to use (e.g. US_ASCII, UTF-8, etc) - * @return a byte array, containing the encoded message. - */ - byte[] encode(ACLMessage msg, String charset); - - /** - * Recovers an ACLMessage object back from raw data, - * using the specific message representation to interpret the byte - * sequence. - * - * @param data The byte sequence containing the encoded message. - * @param charset Charset encoding to use (e.g. US_ASCII, UTF-8, etc) - * @return A new ACLMessage object, built from the raw - * data. - * @throws CodecException If some kind of syntax error occurs. - */ - ACLMessage decode(byte[] data, String charset) throws CodecException; - - /** - * Query the name of the message representation handled by this - * Codec object. The FIPA standard representations have - * a name starting with "fipa.acl.rep.". - * - * @return The name of the handled ACL message representation. - */ - String getName(); - } diff --git a/src/jade/lang/acl/ACLMessage.java b/src/jade/lang/acl/ACLMessage.java index 31ad9ce..0c9c2e6 100644 --- a/src/jade/lang/acl/ACLMessage.java +++ b/src/jade/lang/acl/ACLMessage.java @@ -61,14 +61,6 @@ */ //#MIDP_EXCLUDE_BEGIN public class ACLMessage implements Cloneable, Serializable { - //#MIDP_EXCLUDE_END -/*#MIDP_INCLUDE_BEGIN -public class ACLMessage implements Serializable { -#MIDP_INCLUDE_END*/ - // Explicitly set for compatibility between standard and micro version - @Serial - private static final long serialVersionUID = 3945353187608998130L; - /** * constant identifying the FIPA performative **/ @@ -161,47 +153,11 @@ public class ACLMessage implements Serializable { * constant identifying an unknown performative **/ public static final int UNKNOWN = -1; - - /** - * @serial - */ - private int performative; // keeps the performative type of this object - /** - * This array of Strings keeps the names of the performatives - **/ - private static final String[] performatives = new String[22]; - - static { // initialization of the Vector of performatives - performatives[ACCEPT_PROPOSAL] = "ACCEPT-PROPOSAL"; - performatives[AGREE] = "AGREE"; - performatives[CANCEL] = "CANCEL"; - performatives[CFP] = "CFP"; - performatives[CONFIRM] = "CONFIRM"; - performatives[DISCONFIRM] = "DISCONFIRM"; - performatives[FAILURE] = "FAILURE"; - performatives[INFORM] = "INFORM"; - performatives[INFORM_IF] = "INFORM-IF"; - performatives[INFORM_REF] = "INFORM-REF"; - performatives[NOT_UNDERSTOOD] = "NOT-UNDERSTOOD"; - performatives[PROPOSE] = "PROPOSE"; - performatives[QUERY_IF] = "QUERY-IF"; - performatives[QUERY_REF] = "QUERY-REF"; - performatives[REFUSE] = "REFUSE"; - performatives[REJECT_PROPOSAL] = "REJECT-PROPOSAL"; - performatives[REQUEST] = "REQUEST"; - performatives[REQUEST_WHEN] = "REQUEST-WHEN"; - performatives[REQUEST_WHENEVER] = "REQUEST-WHENEVER"; - performatives[SUBSCRIBE] = "SUBSCRIBE"; - performatives[PROXY] = "PROXY"; - performatives[PROPAGATE] = "PROPAGATE"; - } - /** * User defined parameter key specifying, when set to "true", that if the delivery of a * message fails, no failure handling action must be performed. */ public static final String IGNORE_FAILURE = "JADE-ignore-failure"; - /** * User defined parameter key specifying, when set to "true", that if the delivery of a * message fails, no FAILURE notification has to be sent back to the sender. @@ -210,31 +166,26 @@ public class ACLMessage implements Serializable { * delivery of the automatic AMS FAILURE reply. */ public static final String DONT_NOTIFY_FAILURE = "JADE-dont-notify-failure"; - /** * User defined parameter key specifying that the JADE tracing mechanism should be activated for this message. */ public static final String TRACE = "JADE-trace"; - /** * User defined parameter key specifying that this message does not need to be cloned by the message delivery service. * This should be used ONLY when the message object will not be modified after being sent */ public static final String NO_CLONE = "JADE-no-clone"; - /** * User defined parameter key specifying that this message must be delivered synchronously. It should * be noticed that when using synchronous delivery message order is not guaranteed. */ public static final String SYNCH_DELIVERY = "JADE-synch-delivery"; - /** * User defined parameter key specifying the AID of the real sender of a message. This is automatically * set by the MessagingService when posting a message where the sender field is different than the real * sender. */ public static final String REAL_SENDER = "JADE-real-sender"; - /** * User defined parameter key specifying that this message must be stored for a * given timeout (in ms) in case it is sent to/from a temporarily disconnected split @@ -243,7 +194,6 @@ public class ACLMessage implements Serializable { * -1 means infinite timeout */ public static final String SF_TIMEOUT = "JADE-SF-timeout"; - /** * AMS failure reasons */ @@ -254,13 +204,17 @@ public class ACLMessage implements Serializable { public static final String AMS_FAILURE_FOREIGN_AGENT_UNREACHABLE = "Foreign agent unreachable"; public static final String AMS_FAILURE_FOREIGN_AGENT_NO_ADDRESS = "Foreign agent with no address"; public static final String AMS_FAILURE_UNEXPECTED_ERROR = "Unexpected error"; - - + //#MIDP_EXCLUDE_END +/*#MIDP_INCLUDE_BEGIN +public class ACLMessage implements Serializable { +#MIDP_INCLUDE_END*/ + // Explicitly set for compatibility between standard and micro version + @Serial + private static final long serialVersionUID = 3945353187608998130L; /** - * @serial - */ - private AID source = null; - + * This array of Strings keeps the names of the performatives + **/ + private static final String[] performatives = new String[22]; /** * These constants represent the expected size of the 2 array lists * used by this class @@ -268,6 +222,39 @@ public class ACLMessage implements Serializable { private static final int RECEIVERS_EXPECTED_SIZE = 1; private static final int REPLYTO_EXPECTED_SIZE = 1; + static { // initialization of the Vector of performatives + performatives[ACCEPT_PROPOSAL] = "ACCEPT-PROPOSAL"; + performatives[AGREE] = "AGREE"; + performatives[CANCEL] = "CANCEL"; + performatives[CFP] = "CFP"; + performatives[CONFIRM] = "CONFIRM"; + performatives[DISCONFIRM] = "DISCONFIRM"; + performatives[FAILURE] = "FAILURE"; + performatives[INFORM] = "INFORM"; + performatives[INFORM_IF] = "INFORM-IF"; + performatives[INFORM_REF] = "INFORM-REF"; + performatives[NOT_UNDERSTOOD] = "NOT-UNDERSTOOD"; + performatives[PROPOSE] = "PROPOSE"; + performatives[QUERY_IF] = "QUERY-IF"; + performatives[QUERY_REF] = "QUERY-REF"; + performatives[REFUSE] = "REFUSE"; + performatives[REJECT_PROPOSAL] = "REJECT-PROPOSAL"; + performatives[REQUEST] = "REQUEST"; + performatives[REQUEST_WHEN] = "REQUEST-WHEN"; + performatives[REQUEST_WHENEVER] = "REQUEST-WHENEVER"; + performatives[SUBSCRIBE] = "SUBSCRIBE"; + performatives[PROXY] = "PROXY"; + performatives[PROPAGATE] = "PROPAGATE"; + } + + /** + * @serial + */ + private int performative; // keeps the performative type of this object + /** + * @serial + */ + private AID source = null; //#MIDP_EXCLUDE_BEGIN private ArrayList dests = new ArrayList<>(RECEIVERS_EXPECTED_SIZE); private ArrayList reply_to = null; @@ -333,13 +320,8 @@ public class ACLMessage implements Serializable { //#CUSTOM_EXCLUDE_BEGIN private Envelope messageEnvelope; //#CUSTOM_EXCLUDE_END - - /** - * Returns the list of the communicative acts as an array of String. - */ - public static String[] getAllPerformativeNames() { - return performatives; - } + // For persistence service + private Long persistentID; /** * @see ACLMessage#ACLMessage(int) @@ -364,14 +346,37 @@ public ACLMessage(int perf) { } /** - * Writes the :sender slot. Warning: no - * checks are made to validate the slot value. + * Returns the list of the communicative acts as an array of String. + */ + public static String[] getAllPerformativeNames() { + return performatives; + } + + /** + * Returns the string corresponding to the integer for the performative * - * @param s The new value for the slot. - * @see ACLMessage#getSender() + * @return the string corresponding to the integer for the performative; + * "NOT-UNDERSTOOD" if the integer is out of range. */ - public void setSender(AID s) { - source = s; + public static String getPerformative(int perf) { + try { + return performatives[perf]; + } catch (Exception e) { + return performatives[NOT_UNDERSTOOD]; + } + } + + /** + * Returns the integer corresponding to the performative + * + * @return the integer corresponding to the performative; -1 otherwise + */ + public static int getInteger(String perf) { + String tmp = perf.toUpperCase(); + for (int i = 0; i < performatives.length; i++) + if (performatives[i].equals(tmp)) + return i; + return -1; } /** @@ -391,25 +396,35 @@ public void addReceiver(AID r) { } } - /**add a receiver - * @param localName the local name of the receiver*/ + /** + * add a receiver + * + * @param localName the local name of the receiver + */ public void addReceiver(String localName) { if (localName != null) { dests.add(new AID(localName, false)); } } - /**add some receivers - * @param localNames the local names of the receivers*/ - public void addReceivers(String ... localNames) { + /** + * add some receivers + * + * @param localNames the local names of the receivers + */ + public void addReceivers(String... localNames) { if (localNames != null) { - for(String localName:localNames) + for (String localName : localNames) dests.add(new AID(localName, false)); } } - /**add some receivers - * @param aids the aid of the receivers*/ - public void addReceivers(AID ... aids) { + + /** + * add some receivers + * + * @param aids the aid of the receivers + */ + public void addReceivers(AID... aids) { if (aids != null) { Collections.addAll(dests, aids); } @@ -450,7 +465,6 @@ public void clearAllReceiver() { #MIDP_INCLUDE_END*/ } - /** * Adds a value to :reply-to slot. Warning: * no checks are made to validate the slot value. @@ -507,87 +521,6 @@ public void clearAllReplyTo() { } } - /** - * set the performative of this ACL message object to the passed constant. - * Remind to - * use the set of constants (i.e. INFORM, REQUEST, ... ) - * defined in this class - */ - public void setPerformative(int perf) { - performative = perf; - } - - /** - * Writes the :content slot. Warning: no - * checks are made to validate the slot value.

- *

Notice that, in general, setting a String content and getting - * back a byte sequence content - or viceversa - does not return - * the same value, i.e. the following relation does not hold - * - * getByteSequenceContent(setByteSequenceContent(getContent().getBytes())) - * is equal to getByteSequenceContent() - * - * - * @param content The new value for the slot. - * @see ACLMessage#getContent() - * @see ACLMessage#setByteSequenceContent(byte[]) - */ - public void setContent(String content) { - byteSequenceContent = null; - if (content != null) { - this.content = new StringBuffer(content); - } else { - this.content = null; - } - } - - /** - * Writes the :content slot. Warning: no - * checks are made to validate the slot value.

- *

Notice that, in general, setting a String content and getting - * back a byte sequence content - or viceversa - does not return - * the same value, i.e. the following relation does not hold - * - * getByteSequenceContent(setByteSequenceContent(getContent().getBytes())) - * is equal to getByteSequenceContent() - * - * - * @param byteSequenceContent The new value for the slot. - * @see ACLMessage#setContent(String s) - * @see ACLMessage#getByteSequenceContent() - */ - public void setByteSequenceContent(byte[] byteSequenceContent) { - content = null; - this.byteSequenceContent = byteSequenceContent; - } - - - //#MIDP_EXCLUDE_BEGIN - - /** - * This method sets the content of this ACLMessage to a Java object. - * It is not FIPA compliant so its usage is not encouraged. - * For example:
- *

-     * ACLMessage msg = new ACLMessage(ACLMessage.INFORM);
-     * Date d = new Date();
-     * try{
-     * msg.setContentObject(d);
-     * }catch(IOException e){}
-     * 
- * - * @param s the object that will be used to set the content of the ACLMessage. - * @throws IOException if an I/O error occurs. - */ - public void setContentObject(Serializable s) throws IOException { - ByteArrayOutputStream c = new ByteArrayOutputStream(); - ObjectOutputStream oos = new ObjectOutputStream(c); - oos.writeObject(s); - oos.flush(); - setByteSequenceContent(c.toByteArray()); - } - - /** * This method returns the content of this ACLMessage when they have * been written via the method setContentObject. @@ -616,98 +549,33 @@ public Serializable getContentObject() throws UnreadableException { } } - //#MIDP_EXCLUDE_END - - /** - * Writes the :reply-with slot. Warning: no - * checks are made to validate the slot value. - * - * @param reply The new value for the slot. - * @see ACLMessage#getReplyWith() - */ - public void setReplyWith(String reply) { - reply_with = reply; - } - - /** - * Writes the :in-reply-to slot. Warning: no - * checks are made to validate the slot value. - * - * @param reply The new value for the slot. - * @see ACLMessage#getInReplyTo() - */ - public void setInReplyTo(String reply) { - in_reply_to = reply; - } - - /** - * Writes the :encoding slot. Warning: no - * checks are made to validate the slot value. - * - * @param str The new value for the slot. - * @see ACLMessage#getEncoding() - */ - public void setEncoding(String str) { - encoding = str; - } - - /** - * Writes the :language slot. Warning: no - * checks are made to validate the slot value. - * - * @param str The new value for the slot. - * @see ACLMessage#getLanguage() - */ - public void setLanguage(String str) { - language = str; - } - - /** - * Writes the :ontology slot. Warning: no - * checks are made to validate the slot value. - * - * @param str The new value for the slot. - * @see ACLMessage#getOntology() - */ - public void setOntology(String str) { - ontology = str; - } - - /** - * Writes the :reply-by slot. Warning: no - * checks are made to validate the slot value. - * - * @param date The new value for the slot. - * @see ACLMessage#getReplyByDate() - */ - public void setReplyByDate(Date date) { - reply_byInMillisec = (date == null ? 0 : date.getTime()); - } - /** - * Writes the :protocol slot. Warning: no - * checks are made to validate the slot value. - * - * @param str The new value for the slot. - * @see ACLMessage#getProtocol() - */ - public void setProtocol(String str) { - protocol = str; - } + //#MIDP_EXCLUDE_BEGIN /** - * Writes the :conversation-id slot. Warning: no - * checks are made to validate the slot value. + * This method sets the content of this ACLMessage to a Java object. + * It is not FIPA compliant so its usage is not encouraged. + * For example:
+ *
+     * ACLMessage msg = new ACLMessage(ACLMessage.INFORM);
+     * Date d = new Date();
+     * try{
+     * msg.setContentObject(d);
+     * }catch(IOException e){}
+     * 
* - * @param str The new value for the slot. - * @see ACLMessage#getConversationId() + * @param s the object that will be used to set the content of the ACLMessage. + * @throws IOException if an I/O error occurs. */ - public void setConversationId(String str) { - conversation_id = str; + public void setContentObject(Serializable s) throws IOException { + ByteArrayOutputStream c = new ByteArrayOutputStream(); + ObjectOutputStream oos = new ObjectOutputStream(c); + oos.writeObject(s); + oos.flush(); + setByteSequenceContent(c.toByteArray()); } - /** * Reads :receiver slot. * @@ -722,6 +590,7 @@ public Iterator getAllReceiver() { return new EnumIterator(dests.elements()); #MIDP_INCLUDE_END*/ } + //#MIDP_EXCLUDE_END /** * Reads :reply_to slot. @@ -763,40 +632,33 @@ public AID getSender() { } /** - * Returns the string corresponding to the integer for the performative + * Writes the :sender slot. Warning: no + * checks are made to validate the slot value. * - * @return the string corresponding to the integer for the performative; - * "NOT-UNDERSTOOD" if the integer is out of range. + * @param s The new value for the slot. + * @see ACLMessage#getSender() */ - public static String getPerformative(int perf) { - try { - return performatives[perf]; - } catch (Exception e) { - return performatives[NOT_UNDERSTOOD]; - } + public void setSender(AID s) { + source = s; } /** - * Returns the integer corresponding to the performative + * return the integer representing the performative of this object * - * @return the integer corresponding to the performative; -1 otherwise + * @return an integer representing the performative of this object */ - public static int getInteger(String perf) { - String tmp = perf.toUpperCase(); - for (int i = 0; i < performatives.length; i++) - if (performatives[i].equals(tmp)) - return i; - return -1; + public int getPerformative() { + return performative; } - /** - * return the integer representing the performative of this object - * - * @return an integer representing the performative of this object + * set the performative of this ACL message object to the passed constant. + * Remind to + * use the set of constants (i.e. INFORM, REQUEST, ... ) + * defined in this class */ - public int getPerformative() { - return performative; + public void setPerformative(int perf) { + performative = perf; } /** @@ -832,6 +694,30 @@ else if (byteSequenceContent != null) return null; } + /** + * Writes the :content slot. Warning: no + * checks are made to validate the slot value.

+ *

Notice that, in general, setting a String content and getting + * back a byte sequence content - or viceversa - does not return + * the same value, i.e. the following relation does not hold + * + * getByteSequenceContent(setByteSequenceContent(getContent().getBytes())) + * is equal to getByteSequenceContent() + * + * + * @param content The new value for the slot. + * @see ACLMessage#getContent() + * @see ACLMessage#setByteSequenceContent(byte[]) + */ + public void setContent(String content) { + byteSequenceContent = null; + if (content != null) { + this.content = new StringBuffer(content); + } else { + this.content = null; + } + } + /** * Reads :content slot.

*

Notice that, in general, setting a String content and getting @@ -855,6 +741,26 @@ else if (byteSequenceContent != null) return null; } + /** + * Writes the :content slot. Warning: no + * checks are made to validate the slot value.

+ *

Notice that, in general, setting a String content and getting + * back a byte sequence content - or viceversa - does not return + * the same value, i.e. the following relation does not hold + * + * getByteSequenceContent(setByteSequenceContent(getContent().getBytes())) + * is equal to getByteSequenceContent() + * + * + * @param byteSequenceContent The new value for the slot. + * @see ACLMessage#setContent(String s) + * @see ACLMessage#getByteSequenceContent() + */ + public void setByteSequenceContent(byte[] byteSequenceContent) { + content = null; + this.byteSequenceContent = byteSequenceContent; + } + /** * Reads :reply-with slot. * @@ -865,6 +771,17 @@ public String getReplyWith() { return reply_with; } + /** + * Writes the :reply-with slot. Warning: no + * checks are made to validate the slot value. + * + * @param reply The new value for the slot. + * @see ACLMessage#getReplyWith() + */ + public void setReplyWith(String reply) { + reply_with = reply; + } + /** * Reads :reply-to slot. * @@ -875,6 +792,16 @@ public String getInReplyTo() { return in_reply_to; } + /** + * Writes the :in-reply-to slot. Warning: no + * checks are made to validate the slot value. + * + * @param reply The new value for the slot. + * @see ACLMessage#getInReplyTo() + */ + public void setInReplyTo(String reply) { + in_reply_to = reply; + } /** * Reads :encoding slot. @@ -886,6 +813,17 @@ public String getEncoding() { return encoding; } + /** + * Writes the :encoding slot. Warning: no + * checks are made to validate the slot value. + * + * @param str The new value for the slot. + * @see ACLMessage#getEncoding() + */ + public void setEncoding(String str) { + encoding = str; + } + /** * Reads :language slot. * @@ -896,6 +834,17 @@ public String getLanguage() { return language; } + /** + * Writes the :language slot. Warning: no + * checks are made to validate the slot value. + * + * @param str The new value for the slot. + * @see ACLMessage#getLanguage() + */ + public void setLanguage(String str) { + language = str; + } + /** * Reads :ontology slot. * @@ -906,7 +855,16 @@ public String getOntology() { return ontology; } - //#MIDP_EXCLUDE_BEGIN + /** + * Writes the :ontology slot. Warning: no + * checks are made to validate the slot value. + * + * @param str The new value for the slot. + * @see ACLMessage#getOntology() + */ + public void setOntology(String str) { + ontology = str; + } /** * Reads :reply-by slot. @@ -922,7 +880,6 @@ public String getReplyBy() { else return null; } - //#MIDP_EXCLUDE_END /** * Reads :reply-by slot. @@ -938,6 +895,20 @@ public Date getReplyByDate() { return null; } + //#MIDP_EXCLUDE_BEGIN + + /** + * Writes the :reply-by slot. Warning: no + * checks are made to validate the slot value. + * + * @param date The new value for the slot. + * @see ACLMessage#getReplyByDate() + */ + public void setReplyByDate(Date date) { + reply_byInMillisec = (date == null ? 0 : date.getTime()); + } + //#MIDP_EXCLUDE_END + /** * Reads :protocol slot. * @@ -948,6 +919,17 @@ public String getProtocol() { return protocol; } + /** + * Writes the :protocol slot. Warning: no + * checks are made to validate the slot value. + * + * @param str The new value for the slot. + * @see ACLMessage#getProtocol() + */ + public void setProtocol(String str) { + protocol = str; + } + /** * Reads :conversation-id slot. * @@ -958,6 +940,16 @@ public String getConversationId() { return conversation_id; } + /** + * Writes the :conversation-id slot. Warning: no + * checks are made to validate the slot value. + * + * @param str The new value for the slot. + * @see ACLMessage#getConversationId() + */ + public void setConversationId(String str) { + conversation_id = str; + } /** * Add a new user defined parameter to this ACLMessage. @@ -1029,28 +1021,16 @@ public Object clearUserDefinedParameter(String key) { return userDefProps.remove(key); } - public void setPostTimeStamp(long time) { - postTimeStamp = time; - } - public long getPostTimeStamp() { return postTimeStamp; } // #CUSTOM_EXCLUDE_BEGIN - /** - * Attaches an envelope to this message. The envelope is used by the - * ACC for inter-platform messaging. - * - * @param e The Envelope object to attach to this - * message. - */ - public void setEnvelope(Envelope e) { - messageEnvelope = e; + public void setPostTimeStamp(long time) { + postTimeStamp = time; } - /** * Writes the message envelope for this message, using the * :sender and :receiver message slots to @@ -1083,6 +1063,18 @@ public Envelope getEnvelope() { //#MIDP_EXCLUDE_BEGIN + /** + * Attaches an envelope to this message. The envelope is used by the + * ACC for inter-platform messaging. + * + * @param e The Envelope object to attach to this + * message. + */ + public void setEnvelope(Envelope e) { + messageEnvelope = e; + } + //#MIDP_EXCLUDE_END + /** * Convert an ACL message to its string representation. This method * writes a representation of this ACLMessage into a @@ -1096,6 +1088,38 @@ public String toString() { return StringACLCodec.toString(this); } //#MIDP_EXCLUDE_END + /*#MIDP_INCLUDE_BEGIN + public synchronized Object clone() { + ACLMessage result = new ACLMessage(NOT_UNDERSTOOD); + result.performative = performative; + result.source = source; + result.content = content; + result.byteSequenceContent = byteSequenceContent; + result.reply_with = reply_with; + result.in_reply_to = in_reply_to; + result.encoding = encoding; + result.language = language; + result.ontology = ontology; + result.reply_byInMillisec = reply_byInMillisec; + result.protocol = protocol; + result.conversation_id = conversation_id; + result.userDefProps = userDefProps; + //#CUSTOM_EXCLUDE_BEGIN + if(messageEnvelope != null) { + result.messageEnvelope = (Envelope)messageEnvelope.clone(); + } + //#CUSTOM_EXCLUDE_END + result.dests = new Vector(dests.size()); + for (int i=0; iACLMessage object. @@ -1144,39 +1168,6 @@ public synchronized Object clone() { return result; } - //#MIDP_EXCLUDE_END - /*#MIDP_INCLUDE_BEGIN - public synchronized Object clone() { - ACLMessage result = new ACLMessage(NOT_UNDERSTOOD); - result.performative = performative; - result.source = source; - result.content = content; - result.byteSequenceContent = byteSequenceContent; - result.reply_with = reply_with; - result.in_reply_to = in_reply_to; - result.encoding = encoding; - result.language = language; - result.ontology = ontology; - result.reply_byInMillisec = reply_byInMillisec; - result.protocol = protocol; - result.conversation_id = conversation_id; - result.userDefProps = userDefProps; - //#CUSTOM_EXCLUDE_BEGIN - if(messageEnvelope != null) { - result.messageEnvelope = (Envelope)messageEnvelope.clone(); - } - //#CUSTOM_EXCLUDE_END - result.dests = new Vector(dests.size()); - for (int i=0; i getAllIntendedReceiver() { return it; } - //#MIDP_EXCLUDE_BEGIN - - - // For persistence service - private Long persistentID; - // For persistence service private Long getPersistentID() { return persistentID; @@ -1332,6 +1319,10 @@ private void setPersistentID(Long l) { persistentID = l; } + // For persistence service + private ArrayList getReceivers() { + return dests; + } // For persistence service private void setReceivers(ArrayList al) { @@ -1339,8 +1330,8 @@ private void setReceivers(ArrayList al) { } // For persistence service - private ArrayList getReceivers() { - return dests; + private ArrayList getReplyTo() { + return reply_to; } // For persistence service @@ -1349,8 +1340,8 @@ private void setReplyTo(ArrayList al) { } // For persistence service - private ArrayList getReplyTo() { - return reply_to; + private Serializable getUserDefinedProperties() { + return userDefProps; } // For persistence service @@ -1358,11 +1349,6 @@ private void setUserDefinedProperties(Serializable p) { userDefProps = (Properties) p; } - // For persistence service - private Serializable getUserDefinedProperties() { - return userDefProps; - } - //#MIDP_EXCLUDE_END diff --git a/src/jade/lang/acl/ACLParserTokenManager.java b/src/jade/lang/acl/ACLParserTokenManager.java index 75a0e86..c85dc7f 100644 --- a/src/jade/lang/acl/ACLParserTokenManager.java +++ b/src/jade/lang/acl/ACLParserTokenManager.java @@ -7,7 +7,74 @@ import java.io.PrintStream; public class ACLParserTokenManager implements ACLParserConstants { + public static final String[] jjstrLiteralImages = { + "", null, null, null, null, "\50", null, null, null, null, null, null, null, + null, null, null, null, null, null, null, null, null, null, null, null, null, null, + null, "\51", null, null, null, null, null, null, null, null, null, null, null, null, + "\51", "\50", null, null, null, null, null, null, null, null, null, null, null, + "\51", "\50",}; + public static final String[] lexStateNames = { + "DEFAULT", + "MESSAGETYPESTATE", + "MESSAGEPARAMETERSTATE", + "CONTENTSTATE", + "AIDSTATE", + }; + public static final int[] jjnewLexState = { + -1, -1, -1, -1, -1, 1, -1, -1, -1, -1, 2, -1, -1, -1, -1, 4, 4, 3, 3, 3, 3, 4, 3, 3, 3, + 3, 3, 3, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + 3, -1, -1, 3, -1, -1, + }; + static final long[] jjbitVec0 = { + 0xfffffffffffffffeL, 0xffffffffffffffffL, 0xffffffffffffffffL, 0xffffffffffffffffL + }; + static final long[] jjbitVec2 = { + 0x0L, 0x0L, 0xffffffffffffffffL, 0xffffffffffffffffL + }; + static final int[] jjnextStates = { + 22, 40, 46, 47, 49, 11, 41, 42, 21, 40, 11, 41, 45, 3, 4, 6, + 3, 4, 8, 6, 46, 47, 49, 11, 5, 7, 9, 14, 15, 43, 44, 125, + 138, 144, 155, 170, 113, 120, 95, 99, 106, 73, 81, 89, 61, 63, 68, 53, + 56, + }; + static final long[] jjtoToken = { + 0xff87fe1fff8421L, + }; + static final long[] jjtoSkip = { + 0x7801e0007bdeL, + }; + private final int[] jjrounds = new int[171]; + private final int[] jjstateSet = new int[342]; public PrintStream debugStream = System.out; + protected SimpleCharStream input_stream; + protected char curChar; + StringBuffer image; + int jjimageLen; + int lengthOfMatch; + int curLexState = 0; + int defaultLexState = 0; + int jjnewStateCnt; + int jjround; + int jjmatchedPos; + int jjmatchedKind; + + public ACLParserTokenManager(SimpleCharStream stream) { + if (SimpleCharStream.staticFlag) + throw new Error("ERROR: Cannot use a static CharStream class with a non-static lexical analyzer."); + input_stream = stream; + } + + public ACLParserTokenManager(SimpleCharStream stream, int lexState) { + this(stream); + SwitchTo(lexState); + } + + private static boolean jjCanMove_0(int hiByte, int i1, int i2, long l1, long l2) { + if (hiByte == 0) { + return ((jjbitVec2[i2] & l2) != 0L); + } + return (jjbitVec0[i1] & l1) != 0L; + } public void setDebugStream(PrintStream ds) { debugStream = ds; @@ -62,24 +129,13 @@ private int jjMoveStringLiteralDfa1_4(long active0) { return 1; } switch (curChar) { - case 65: - case 97: - return jjMoveStringLiteralDfa2_4(active0, 0x8000000000000L); - case 69: - case 101: - return jjMoveStringLiteralDfa2_4(active0, 0x1800000000000L); - case 71: - case 103: - return jjMoveStringLiteralDfa2_4(active0, 0x2000000000000L); - case 78: - case 110: - return jjMoveStringLiteralDfa2_4(active0, 0x4000000000000L); - case 82: - case 114: - return jjMoveStringLiteralDfa2_4(active0, 0x10000000000000L); - default: - break; - } + case 65, 97 -> {return jjMoveStringLiteralDfa2_4(active0, 0x8000000000000L);} + case 69, 101 -> {return jjMoveStringLiteralDfa2_4(active0, 0x1800000000000L);} + case 71, 103 -> {return jjMoveStringLiteralDfa2_4(active0, 0x2000000000000L);} + case 78, 110 -> {return jjMoveStringLiteralDfa2_4(active0, 0x4000000000000L);} + case 82, 114 -> {return jjMoveStringLiteralDfa2_4(active0, 0x10000000000000L);} + default -> {} + } return jjStartNfa_4(0, active0); } @@ -93,25 +149,13 @@ private int jjMoveStringLiteralDfa2_4(long old0, long active0) { return 2; } switch (curChar) { - case 65: - case 97: - return jjMoveStringLiteralDfa3_4(active0, 0x4000000000000L); - case 68: - case 100: - return jjMoveStringLiteralDfa3_4(active0, 0x8000000000000L); - case 69: - case 101: - return jjMoveStringLiteralDfa3_4(active0, 0x12000000000000L); - case 81: - case 113: - return jjMoveStringLiteralDfa3_4(active0, 0x1000000000000L); - case 84: - case 116: - if ((active0 & 0x800000000000L) != 0L) - return jjStopAtPos(2, 47); - break; - default: - break; + case 65, 97 -> { return jjMoveStringLiteralDfa3_4(active0, 0x4000000000000L);} + case 68, 100 -> { return jjMoveStringLiteralDfa3_4(active0, 0x8000000000000L);} + case 69, 101 -> { return jjMoveStringLiteralDfa3_4(active0, 0x12000000000000L);} + case 81, 113 -> { return jjMoveStringLiteralDfa3_4(active0, 0x1000000000000L);} + case 84, 116 -> { if ((active0 & 0x800000000000L) != 0L) return jjStopAtPos(2, 47);} + default -> { + } } return jjStartNfa_4(1, active0); } @@ -452,13 +496,6 @@ private void jjCheckNAddStates(int start) { jjCheckNAdd(jjnextStates[start + 1]); } - static final long[] jjbitVec0 = { - 0xfffffffffffffffeL, 0xffffffffffffffffL, 0xffffffffffffffffL, 0xffffffffffffffffL - }; - static final long[] jjbitVec2 = { - 0x0L, 0x0L, 0xffffffffffffffffL, 0xffffffffffffffffL - }; - private int jjMoveNfa_4(int startState, int curPos) { int[] nextStates; int startsAt = 0; @@ -1308,13 +1345,13 @@ private int jjMoveStringLiteralDfa11_2(long old0, long active0) { return 11; } switch (curChar) { - case 79: - case 111: + case 79, 111 -> { if ((active0 & 0x100000L) != 0L) return jjStopAtPos(11, 20); return jjMoveStringLiteralDfa12_2(active0, 0x4000000L); - default: - break; + } + default -> { + } } return jjStartNfa_2(10, active0); } @@ -2222,8 +2259,8 @@ else if ((0x1000000010L & l) != 0L) MatchLoop: do { switch (jjstateSet[--i]) { - default: - break; + default -> { + } } } while (i != startsAt); } @@ -2243,63 +2280,6 @@ else if ((0x1000000010L & l) != 0L) } } - static final int[] jjnextStates = { - 22, 40, 46, 47, 49, 11, 41, 42, 21, 40, 11, 41, 45, 3, 4, 6, - 3, 4, 8, 6, 46, 47, 49, 11, 5, 7, 9, 14, 15, 43, 44, 125, - 138, 144, 155, 170, 113, 120, 95, 99, 106, 73, 81, 89, 61, 63, 68, 53, - 56, - }; - - private static boolean jjCanMove_0(int hiByte, int i1, int i2, long l1, long l2) { - if (hiByte == 0) { - return ((jjbitVec2[i2] & l2) != 0L); - } - return (jjbitVec0[i1] & l1) != 0L; - } - - public static final String[] jjstrLiteralImages = { - "", null, null, null, null, "\50", null, null, null, null, null, null, null, - null, null, null, null, null, null, null, null, null, null, null, null, null, null, - null, "\51", null, null, null, null, null, null, null, null, null, null, null, null, - "\51", "\50", null, null, null, null, null, null, null, null, null, null, null, - "\51", "\50",}; - public static final String[] lexStateNames = { - "DEFAULT", - "MESSAGETYPESTATE", - "MESSAGEPARAMETERSTATE", - "CONTENTSTATE", - "AIDSTATE", - }; - public static final int[] jjnewLexState = { - -1, -1, -1, -1, -1, 1, -1, -1, -1, -1, 2, -1, -1, -1, -1, 4, 4, 3, 3, 3, 3, 4, 3, 3, 3, - 3, 3, 3, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - 3, -1, -1, 3, -1, -1, - }; - static final long[] jjtoToken = { - 0xff87fe1fff8421L, - }; - static final long[] jjtoSkip = { - 0x7801e0007bdeL, - }; - protected SimpleCharStream input_stream; - private final int[] jjrounds = new int[171]; - private final int[] jjstateSet = new int[342]; - StringBuffer image; - int jjimageLen; - int lengthOfMatch; - protected char curChar; - - public ACLParserTokenManager(SimpleCharStream stream) { - if (SimpleCharStream.staticFlag) - throw new Error("ERROR: Cannot use a static CharStream class with a non-static lexical analyzer."); - input_stream = stream; - } - - public ACLParserTokenManager(SimpleCharStream stream, int lexState) { - this(stream); - SwitchTo(lexState); - } - public void ReInit(SimpleCharStream stream) { jjmatchedPos = jjnewStateCnt = 0; curLexState = defaultLexState; @@ -2338,13 +2318,6 @@ protected Token jjFillToken() { return t; } - int curLexState = 0; - int defaultLexState = 0; - int jjnewStateCnt; - int jjround; - int jjmatchedPos; - int jjmatchedKind; - public Token getNextToken() { int kind; Token specialToken = null; diff --git a/src/jade/lang/acl/ConversationList.java b/src/jade/lang/acl/ConversationList.java index cc7e971..561d68d 100644 --- a/src/jade/lang/acl/ConversationList.java +++ b/src/jade/lang/acl/ConversationList.java @@ -14,13 +14,12 @@ */ public class ConversationList implements Serializable { private final HashSet conversations = new HashSet<>(); - protected Agent myAgent = null; - protected int cnt = 0; - private final MessageTemplate myTemplate = new MessageTemplate((MessageTemplate.MatchExpression) msg -> { String convId = msg.getConversationId(); return (convId == null || (!conversations.contains(convId))); }); + protected Agent myAgent = null; + protected int cnt = 0; /** * Construct a ConversationList to be used inside a given agent. diff --git a/src/jade/lang/acl/ISO8601.java b/src/jade/lang/acl/ISO8601.java index cf17e95..b919d98 100644 --- a/src/jade/lang/acl/ISO8601.java +++ b/src/jade/lang/acl/ISO8601.java @@ -63,6 +63,23 @@ public class ISO8601 { private static final Calendar localCal = Calendar.getInstance(); private static final Calendar utcCal = Calendar.getInstance(TimeZone.getTimeZone("GMT")); + // set of constants used by the next method + private static final char plus = '+'; + private static final char minus = '-'; + private static final String z = "Z"; + private static final char t = 'T'; + // + private final static long year = 365 * 24 * 60 * 60 * 1000L; + private final static long month = 30 * 24 * 60 * 60 * 1000L; + private final static long day = 24 * 60 * 60 * 1000; + private final static long hour = 60 * 60 * 1000; + private final static long minute = 60 * 1000; + private final static long sec = 1000; + /** + * Default constructor. + */ + public ISO8601() { + } /** * parse a date time token in UTC format (i.e. ending with a Z) @@ -103,7 +120,6 @@ private static String formatlocalDate(Date d) { return subFormatDate(localCal); } - private static String formatutcDate(Date d) { utcCal.setTime(d); return subFormatDate(utcCal) + z; @@ -111,37 +127,16 @@ private static String formatutcDate(Date d) { private static String subFormatDate(Calendar cal) { // Format time - StringBuffer formatedDate = new StringBuffer(); - - formatedDate.append(zeroPaddingNumber(cal.get(Calendar.YEAR), 4)); - formatedDate.append(zeroPaddingNumber(cal.get(Calendar.MONTH) + 1, 2)); - formatedDate.append(zeroPaddingNumber(cal.get(Calendar.DATE), 2)); - formatedDate.append(t); - formatedDate.append(zeroPaddingNumber(cal.get(Calendar.HOUR_OF_DAY), 2)); - formatedDate.append(zeroPaddingNumber(cal.get(Calendar.MINUTE), 2)); - formatedDate.append(zeroPaddingNumber(cal.get(Calendar.SECOND), 2)); - formatedDate.append(zeroPaddingNumber(cal.get(Calendar.MILLISECOND), 3)); - return formatedDate.toString(); - } - - // set of constants used by the next method - private static final char plus = '+'; - private static final char minus = '-'; - private static final String z = "Z"; - private static final char t = 'T'; - // - private final static long year = 365 * 24 * 60 * 60 * 1000L; - private final static long month = 30 * 24 * 60 * 60 * 1000L; - private final static long day = 24 * 60 * 60 * 1000; - private final static long hour = 60 * 60 * 1000; - private final static long minute = 60 * 1000; - private final static long sec = 1000; - - /** - * Default constructor. - */ - public ISO8601() { + String formatedDate = zeroPaddingNumber(cal.get(Calendar.YEAR), 4) + + zeroPaddingNumber(cal.get(Calendar.MONTH) + 1, 2) + + zeroPaddingNumber(cal.get(Calendar.DATE), 2) + + t + + zeroPaddingNumber(cal.get(Calendar.HOUR_OF_DAY), 2) + + zeroPaddingNumber(cal.get(Calendar.MINUTE), 2) + + zeroPaddingNumber(cal.get(Calendar.SECOND), 2) + + zeroPaddingNumber(cal.get(Calendar.MILLISECOND), 3); + return formatedDate; } /** @@ -221,7 +216,7 @@ public static String toString(Date d) { * from now */ public static String toRelativeTimeString(long millisec) { - StringBuffer str = new StringBuffer(); + StringBuilder str = new StringBuilder(); if (millisec > 0) str.append(plus); diff --git a/src/jade/lang/acl/LEAPACLCodec.java b/src/jade/lang/acl/LEAPACLCodec.java index 6e77334..092d45e 100644 --- a/src/jade/lang/acl/LEAPACLCodec.java +++ b/src/jade/lang/acl/LEAPACLCodec.java @@ -42,58 +42,6 @@ public class LEAPACLCodec implements ACLCodec { public static final String NAME = "leap.acl.rep"; - /** - * Encodes an ACLMessage object into a byte sequence, - * according to the specific message representation. - * - * @param msg The ACL message to encode. - * @param charset This parameter is not taken into account - * @return a byte array, containing the encoded message. - */ - public byte[] encode(ACLMessage msg, String charset) { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - DataOutputStream dos = new DataOutputStream(baos); - try { - serializeACL(msg, dos); - return baos.toByteArray(); - } catch (IOException ioe) { - ioe.printStackTrace(); - } - return new byte[0]; - } - - /** - * Recovers an ACLMessage object back from raw data, - * using the specific message representation to interpret the byte - * sequence. - * - * @param data The byte sequence containing the encoded message. - * @param charset This parameter is not taken into account - * @return A new ACLMessage object, built from the raw - * data. - * @throws CodecException If some kind of syntax error occurs. - */ - public ACLMessage decode(byte[] data, String charset) throws CodecException { - DataInputStream din = new DataInputStream(new ByteArrayInputStream(data)); - try { - return deserializeACL(din); - } catch (IOException ioe) { - throw new CodecException(getName() + " ACLMessage decoding exception", ioe); - } - } - - /** - * Query the name of the message representation handled by this - * Codec object. The FIPA standard representations have - * a name starting with "fipa.acl.rep.". - * - * @return The name of the handled ACL message representation. - */ - public String getName() { - return NAME; - } - - /** * */ @@ -287,7 +235,6 @@ public final static ACLMessage deserializeACL(DataInputStream dis) throws IOExce return msg; } - public final static void serializeAID(AID id, DataOutputStream dos) throws IOException { byte presence = 0; String name = id.getName(); @@ -360,4 +307,55 @@ private static void serializeProperties(Properties props, DataOutputStream dos) dos.writeUTF(props.getProperty(key)); } } + + /** + * Encodes an ACLMessage object into a byte sequence, + * according to the specific message representation. + * + * @param msg The ACL message to encode. + * @param charset This parameter is not taken into account + * @return a byte array, containing the encoded message. + */ + public byte[] encode(ACLMessage msg, String charset) { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + DataOutputStream dos = new DataOutputStream(baos); + try { + serializeACL(msg, dos); + return baos.toByteArray(); + } catch (IOException ioe) { + ioe.printStackTrace(); + } + return new byte[0]; + } + + /** + * Recovers an ACLMessage object back from raw data, + * using the specific message representation to interpret the byte + * sequence. + * + * @param data The byte sequence containing the encoded message. + * @param charset This parameter is not taken into account + * @return A new ACLMessage object, built from the raw + * data. + * @throws CodecException If some kind of syntax error occurs. + */ + public ACLMessage decode(byte[] data, String charset) throws CodecException { + DataInputStream din = new DataInputStream(new ByteArrayInputStream(data)); + try { + return deserializeACL(din); + } catch (IOException ioe) { + throw new CodecException(getName() + " ACLMessage decoding exception", ioe); + } + } + + /** + * Query the name of the message representation handled by this + * Codec object. The FIPA standard representations have + * a name starting with "fipa.acl.rep.". + * + * @return The name of the handled ACL message representation. + */ + public String getName() { + return NAME; + } } diff --git a/src/jade/lang/acl/MessageTemplate.java b/src/jade/lang/acl/MessageTemplate.java index 4428cb9..b41b585 100644 --- a/src/jade/lang/acl/MessageTemplate.java +++ b/src/jade/lang/acl/MessageTemplate.java @@ -68,109 +68,402 @@ public class MessageTemplate implements Serializable { private static final int CONTENT = 12; private static final int SENDER = 13; private static final int REPLY_BY_DATE = 14; - /** - * This interface must be overriden in order to define an application - * specific MessageTemplate. - * In particular in the method match() the programmer - * should realize the necessary checks on the ACLMessage in order - * to return true if the message match with the application - * specific requirements false otherwise. + * @serial */ - public interface MatchExpression extends Serializable { - /** - * Check whether a given ACL message matches this - * template. Concrete implementations of this interface will - * have this method called to accept or refuse an ACL message. - * - * @param msg The ACL message to match against this message - * template. - * @return A compliant implementation will return - * true if the parameter ACL message matches the - * template, and false otherwise. - */ - boolean match(ACLMessage msg); - } - - private static class AndExpression implements MatchExpression { - - private final MatchExpression op1; - private final MatchExpression op2; + private final MatchExpression toMatch; - public AndExpression(MatchExpression e1, MatchExpression e2) { - op1 = e1; - op2 = e2; - } + /** + * Public constructor to use when the user needs to define + * an application specific pattern. + */ - public boolean match(ACLMessage msg) { - return op1.match(msg) && op2.match(msg); - } + public MessageTemplate(MatchExpression e) { + toMatch = e; + } - public String toString() { - return "(" + op1.toString() + " AND " + op2.toString() + ")"; - } + /** + * This Factory Method returns a message template that + * matches any message. + * + * @return A new MessageTemplate matching any given + * value. + */ - } // End of AndExpression class + public static MessageTemplate MatchAll() { + return new MessageTemplate(new MatchAllLiteral()); + } - private static class OrExpression implements MatchExpression { + /** + * This Factory Method returns a message template that + * matches any message with a given :sender slot. + * + * @param value The value the message slot will be matched against. + * @return A new MessageTemplate matching the given + * value. + */ + public static MessageTemplate MatchSender(AID value) { + return new MessageTemplate(new Literal(value)); + } - private final MatchExpression op1; - private final MatchExpression op2; + /** + * This Factory Method returns a message template that + * matches any message with a given :receiver slot. + * + * @param values An array of Agent IDs against which the + * value of the message slot will be matched. + * @return A new MessageTemplate matching the given + * value. + */ + public static MessageTemplate MatchReceiver(AID[] values) { + return new MessageTemplate(new Literal(values, RECEIVER)); + } - public OrExpression(MatchExpression e1, MatchExpression e2) { - op1 = e1; - op2 = e2; - } + /** + * This Factory Method returns a message template that + * matches any message about a given topic. + * + * @param topic An AID representing the topic to be matched + * @return A new MessageTemplate matching messages about the given topic + */ + public static MessageTemplate MatchTopic(AID topic) { + return new MessageTemplate(new MatchTopic(topic)); + } - public boolean match(ACLMessage msg) { - return op1.match(msg) || op2.match(msg); - } + /** + * This Factory Method returns a message template that + * matches any message with a given :content slot. + * + * @param value The value the message slot will be matched against. + * @return A new MessageTemplate matching the given + * value. + */ + public static MessageTemplate MatchContent(String value) { + return new MessageTemplate(new Literal(value, CONTENT)); + } - //only for debug - public String toString() { - return "(" + op1.toString() + " OR " + op2.toString() + ")"; - } + /** + * This Factory Method returns a message template that + * matches any message with a given :reply-with slot. + * + * @param value The value the message slot will be matched against. + * @return A new MessageTemplate matching the given + * value. + */ + public static MessageTemplate MatchReplyWith(String value) { + return new MessageTemplate(new Literal(value, REPLY_WITH)); + } - } // End of OrExpression class + /** + * This Factory Method returns a message template that + * matches any message with a given :in-reply-to slot. + * + * @param value The value the message slot will be matched against. + * @return A new MessageTemplate matching the given + * value. + */ + public static MessageTemplate MatchInReplyTo(String value) { + return new MessageTemplate(new Literal(value, IN_REPLY_TO)); + } - private static class NotExpression implements MatchExpression { - private final MatchExpression op; + /** + * This Factory Method returns a message template that + * matches any message with a given :reply-to slot. + * + * @param values An array of Agent IDs against which the + * value of the message slot will be matched. + * @return A new MessageTemplate matching the given + * value. + */ + public static MessageTemplate MatchReplyTo(AID[] values) { + return new MessageTemplate(new Literal(values, REPLY_TO)); + } - public NotExpression(MatchExpression e) { - op = e; - } + /** + * This Factory Method returns a message template that + * matches any message with a given :language slot. + * + * @param value The value the message slot will be matched against. + * @return A new MessageTemplate matching the given + * value. + */ + public static MessageTemplate MatchLanguage(String value) { + return new MessageTemplate(new Literal(value, LANGUAGE)); + } - public boolean match(ACLMessage msg) { - return !op.match(msg); - } + /** + * This Factory Method returns a message template that + * matches any message with a given :encoding slot. + * + * @param value The value the message slot will be matched against. + * @return A new MessageTemplate matching the given + * value. + */ + public static MessageTemplate MatchEncoding(String value) { + return new MessageTemplate(new Literal(value, ENCODING)); + } - //only for debug - public String toString() { - return "(NOT " + op.toString() + ")"; - } - } // End of NotExpression class + /** + * This Factory Method returns a message template that + * matches any message with a given :ontology slot. + * + * @param value The value the message slot will be matched against. + * @return A new MessageTemplate matching the given + * value. + */ + public static MessageTemplate MatchOntology(String value) { + return new MessageTemplate(new Literal(value, ONTOLOGY)); + } - private static class Literal implements MatchExpression { + /** + * This Factory Method returns a message template that + * matches any message with a given :reply-by slot. + * + * @param value The Date the message slot will be matched against. + * @return A new MessageTemplate matching the given + * value. + **/ + public static MessageTemplate MatchReplyByDate(Date value) { + return new MessageTemplate(new Literal(value)); + } - Object matchValue; - int perfValue; - int slotName; + /** + * This Factory Method returns a message template that + * matches any message with a given :protocol slot. + * + * @param value The value the message slot will be matched against. + * @return A new MessageTemplate matching the given + * value. + */ + public static MessageTemplate MatchProtocol(String value) { + return new MessageTemplate(new Literal(value, PROTOCOL)); + } - //Literal for all the string value to match: language, ontology,encoding... - Literal(String matchValue, int slotName) { - this.matchValue = matchValue; - this.slotName = slotName; - } + /** + * This Factory Method returns a message template that + * matches any message with a given :conversation-id slot. + * + * @param value The value the message slot will be matched against. + * @return A new MessageTemplate matching the given + * value. + */ + public static MessageTemplate MatchConversationId(String value) { + return new MessageTemplate(new Literal(value, CONVERSATION_ID)); + } - //Literal for the sender value - Literal(AID matchValue) { - this.matchValue = matchValue; - this.slotName = SENDER; - } + /** + * This Factory Method returns a message template that + * matches any message with a given performative. + * + * @param value The value the message slot will be matched against. + * @return A new MessageTenplatematching the given + * value. + */ + public static MessageTemplate MatchPerformative(int value) { + return new MessageTemplate(new Literal(value)); + } - //Literal for the receiver and replyTo slot. - Literal(AID[] matchValue, int slotName) { - this.matchValue = matchValue; + /** + * This Factory Method returns a message template that + * matches ACL messages against a given one, passed as + * parameter. The following algorithm is used: + * When the given ACLMessage has a non + * null slot, subsequent messages must have the same + * slot value in that slot to have a match. + * When the given ACLMessage has a null + * slot, subsequent messages can have any value for that slot and + * still match the template. + * In short, a null value for a slot means don't + * care. + * + * @param msg The ACLMessage used to build a custom + * message template. + * @param matchPerformative a bool value. When + * true, the performative of the msg will + * be considered as a part of the template (i.e. the message + * template will match only ACL messages with the same performativa + * as msg). + * When , the performative of msg is ignored and + * the resulting message template will not consider it when matching + * messages. + * @return A new MessageTemplate, matching the given + * message according to the above algorithm. + */ + public static MessageTemplate MatchCustom(ACLMessage msg, boolean matchPerformative) { + ACLMessage message = (ACLMessage) msg.clone(); + return new MessageTemplate(new CustomMsgLiteral(message, matchPerformative)); + } + + /** + * Logical and between two MessageTemplate + * objects. This method creates a new message template that is + * matched by those ACL messages matching both + * message templates given as operands. + * + * @param op1 The first and operand. + * @param op2 The second and operand. + * @return A new MessageTemplate object. + * @see MessageTemplate#or(MessageTemplate op1, MessageTemplate op2) + */ + public static MessageTemplate and(MessageTemplate op1, MessageTemplate op2) { + AndExpression e = new AndExpression(op1.toMatch, op2.toMatch); + return new MessageTemplate(e); + } + + /** + * Logical or between two MessageTemplate + * objects. This method creates a new message template that is + * matched by those ACL messages matching any of the + * two message templates given as operands. + * + * @param op1 The first or operand. + * @param op2 The second or operand. + * @return A new MessageTemplate object. + * @see MessageTemplate#and(MessageTemplate op1, MessageTemplate op2) + */ + public static MessageTemplate or(MessageTemplate op1, MessageTemplate op2) { + OrExpression e = new OrExpression(op1.toMatch, op2.toMatch); + return new MessageTemplate(e); + } + + /** + * Logical not of a MessageTemplate object. This + * method creates a new message template that is matched by those + * ACL messages not matching the message template + * given as operand. + * + * @param op The not operand. + * @return A new MessageTemplate object. + */ + public static MessageTemplate not(MessageTemplate op) { + NotExpression e = new NotExpression(op.toMatch); + return new MessageTemplate(e); + } + + /** + * Matches an ACL message against this MessageTemplate + * object. + * + * @param msg The ACLMessage to check for matching. + * @return true if the ACL message matches this + * template, false otherwise. + */ + public boolean match(ACLMessage msg) { + return toMatch.match(msg); + } + + /** + * Retrieve a string representation of this message template. + * + * @return A string describing the syntactic structure of this + * message template. + */ + public String toString() { + return toMatch.toString(); + } + + /** + * This interface must be overriden in order to define an application + * specific MessageTemplate. + * In particular in the method match() the programmer + * should realize the necessary checks on the ACLMessage in order + * to return true if the message match with the application + * specific requirements false otherwise. + */ + public interface MatchExpression extends Serializable { + /** + * Check whether a given ACL message matches this + * template. Concrete implementations of this interface will + * have this method called to accept or refuse an ACL message. + * + * @param msg The ACL message to match against this message + * template. + * @return A compliant implementation will return + * true if the parameter ACL message matches the + * template, and false otherwise. + */ + boolean match(ACLMessage msg); + } + + private static class AndExpression implements MatchExpression { + + private final MatchExpression op1; + private final MatchExpression op2; + + public AndExpression(MatchExpression e1, MatchExpression e2) { + op1 = e1; + op2 = e2; + } + + public boolean match(ACLMessage msg) { + return op1.match(msg) && op2.match(msg); + } + + public String toString() { + return "(" + op1.toString() + " AND " + op2.toString() + ")"; + } + + } // End of AndExpression class + + private static class OrExpression implements MatchExpression { + + private final MatchExpression op1; + private final MatchExpression op2; + + public OrExpression(MatchExpression e1, MatchExpression e2) { + op1 = e1; + op2 = e2; + } + + public boolean match(ACLMessage msg) { + return op1.match(msg) || op2.match(msg); + } + + //only for debug + public String toString() { + return "(" + op1.toString() + " OR " + op2.toString() + ")"; + } + + } // End of OrExpression class + + private static class NotExpression implements MatchExpression { + private final MatchExpression op; + + public NotExpression(MatchExpression e) { + op = e; + } + + public boolean match(ACLMessage msg) { + return !op.match(msg); + } + + //only for debug + public String toString() { + return "(NOT " + op.toString() + ")"; + } + } // End of NotExpression class + + private static class Literal implements MatchExpression { + + Object matchValue; + int perfValue; + int slotName; + + //Literal for all the string value to match: language, ontology,encoding... + Literal(String matchValue, int slotName) { + this.matchValue = matchValue; + this.slotName = slotName; + } + + //Literal for the sender value + Literal(AID matchValue) { + this.matchValue = matchValue; + this.slotName = SENDER; + } + + //Literal for the receiver and replyTo slot. + Literal(AID[] matchValue, int slotName) { + this.matchValue = matchValue; this.slotName = slotName; } @@ -493,298 +786,4 @@ public String toString() { return "( Topic: " + name + " )"; } } - - /** - * @serial - */ - private final MatchExpression toMatch; - - /** - * Public constructor to use when the user needs to define - * an application specific pattern. - */ - - public MessageTemplate(MatchExpression e) { - toMatch = e; - } - - /** - * This Factory Method returns a message template that - * matches any message. - * - * @return A new MessageTemplate matching any given - * value. - */ - - public static MessageTemplate MatchAll() { - return new MessageTemplate(new MatchAllLiteral()); - } - - /** - * This Factory Method returns a message template that - * matches any message with a given :sender slot. - * - * @param value The value the message slot will be matched against. - * @return A new MessageTemplate matching the given - * value. - */ - public static MessageTemplate MatchSender(AID value) { - return new MessageTemplate(new Literal(value)); - } - - /** - * This Factory Method returns a message template that - * matches any message with a given :receiver slot. - * - * @param values An array of Agent IDs against which the - * value of the message slot will be matched. - * @return A new MessageTemplate matching the given - * value. - */ - public static MessageTemplate MatchReceiver(AID[] values) { - return new MessageTemplate(new Literal(values, RECEIVER)); - } - - /** - * This Factory Method returns a message template that - * matches any message about a given topic. - * - * @param topic An AID representing the topic to be matched - * @return A new MessageTemplate matching messages about the given topic - */ - public static MessageTemplate MatchTopic(AID topic) { - return new MessageTemplate(new MatchTopic(topic)); - } - - /** - * This Factory Method returns a message template that - * matches any message with a given :content slot. - * - * @param value The value the message slot will be matched against. - * @return A new MessageTemplate matching the given - * value. - */ - public static MessageTemplate MatchContent(String value) { - return new MessageTemplate(new Literal(value, CONTENT)); - } - - /** - * This Factory Method returns a message template that - * matches any message with a given :reply-with slot. - * - * @param value The value the message slot will be matched against. - * @return A new MessageTemplate matching the given - * value. - */ - public static MessageTemplate MatchReplyWith(String value) { - return new MessageTemplate(new Literal(value, REPLY_WITH)); - } - - /** - * This Factory Method returns a message template that - * matches any message with a given :in-reply-to slot. - * - * @param value The value the message slot will be matched against. - * @return A new MessageTemplate matching the given - * value. - */ - public static MessageTemplate MatchInReplyTo(String value) { - return new MessageTemplate(new Literal(value, IN_REPLY_TO)); - } - - /** - * This Factory Method returns a message template that - * matches any message with a given :reply-to slot. - * - * @param values An array of Agent IDs against which the - * value of the message slot will be matched. - * @return A new MessageTemplate matching the given - * value. - */ - public static MessageTemplate MatchReplyTo(AID[] values) { - return new MessageTemplate(new Literal(values, REPLY_TO)); - } - - /** - * This Factory Method returns a message template that - * matches any message with a given :language slot. - * - * @param value The value the message slot will be matched against. - * @return A new MessageTemplate matching the given - * value. - */ - public static MessageTemplate MatchLanguage(String value) { - return new MessageTemplate(new Literal(value, LANGUAGE)); - } - - /** - * This Factory Method returns a message template that - * matches any message with a given :encoding slot. - * - * @param value The value the message slot will be matched against. - * @return A new MessageTemplate matching the given - * value. - */ - public static MessageTemplate MatchEncoding(String value) { - return new MessageTemplate(new Literal(value, ENCODING)); - } - - /** - * This Factory Method returns a message template that - * matches any message with a given :ontology slot. - * - * @param value The value the message slot will be matched against. - * @return A new MessageTemplate matching the given - * value. - */ - public static MessageTemplate MatchOntology(String value) { - return new MessageTemplate(new Literal(value, ONTOLOGY)); - } - - /** - * This Factory Method returns a message template that - * matches any message with a given :reply-by slot. - * - * @param value The Date the message slot will be matched against. - * @return A new MessageTemplate matching the given - * value. - **/ - public static MessageTemplate MatchReplyByDate(Date value) { - return new MessageTemplate(new Literal(value)); - } - - /** - * This Factory Method returns a message template that - * matches any message with a given :protocol slot. - * - * @param value The value the message slot will be matched against. - * @return A new MessageTemplate matching the given - * value. - */ - public static MessageTemplate MatchProtocol(String value) { - return new MessageTemplate(new Literal(value, PROTOCOL)); - } - - /** - * This Factory Method returns a message template that - * matches any message with a given :conversation-id slot. - * - * @param value The value the message slot will be matched against. - * @return A new MessageTemplate matching the given - * value. - */ - public static MessageTemplate MatchConversationId(String value) { - return new MessageTemplate(new Literal(value, CONVERSATION_ID)); - } - - /** - * This Factory Method returns a message template that - * matches any message with a given performative. - * - * @param value The value the message slot will be matched against. - * @return A new MessageTenplatematching the given - * value. - */ - public static MessageTemplate MatchPerformative(int value) { - return new MessageTemplate(new Literal(value)); - } - - /** - * This Factory Method returns a message template that - * matches ACL messages against a given one, passed as - * parameter. The following algorithm is used: - * When the given ACLMessage has a non - * null slot, subsequent messages must have the same - * slot value in that slot to have a match. - * When the given ACLMessage has a null - * slot, subsequent messages can have any value for that slot and - * still match the template. - * In short, a null value for a slot means don't - * care. - * - * @param msg The ACLMessage used to build a custom - * message template. - * @param matchPerformative a bool value. When - * true, the performative of the msg will - * be considered as a part of the template (i.e. the message - * template will match only ACL messages with the same performativa - * as msg). - * When , the performative of msg is ignored and - * the resulting message template will not consider it when matching - * messages. - * @return A new MessageTemplate, matching the given - * message according to the above algorithm. - */ - public static MessageTemplate MatchCustom(ACLMessage msg, boolean matchPerformative) { - ACLMessage message = (ACLMessage) msg.clone(); - return new MessageTemplate(new CustomMsgLiteral(message, matchPerformative)); - } - - /** - * Logical and between two MessageTemplate - * objects. This method creates a new message template that is - * matched by those ACL messages matching both - * message templates given as operands. - * - * @param op1 The first and operand. - * @param op2 The second and operand. - * @return A new MessageTemplate object. - * @see MessageTemplate#or(MessageTemplate op1, MessageTemplate op2) - */ - public static MessageTemplate and(MessageTemplate op1, MessageTemplate op2) { - AndExpression e = new AndExpression(op1.toMatch, op2.toMatch); - return new MessageTemplate(e); - } - - /** - * Logical or between two MessageTemplate - * objects. This method creates a new message template that is - * matched by those ACL messages matching any of the - * two message templates given as operands. - * - * @param op1 The first or operand. - * @param op2 The second or operand. - * @return A new MessageTemplate object. - * @see MessageTemplate#and(MessageTemplate op1, MessageTemplate op2) - */ - public static MessageTemplate or(MessageTemplate op1, MessageTemplate op2) { - OrExpression e = new OrExpression(op1.toMatch, op2.toMatch); - return new MessageTemplate(e); - } - - /** - * Logical not of a MessageTemplate object. This - * method creates a new message template that is matched by those - * ACL messages not matching the message template - * given as operand. - * - * @param op The not operand. - * @return A new MessageTemplate object. - */ - public static MessageTemplate not(MessageTemplate op) { - NotExpression e = new NotExpression(op.toMatch); - return new MessageTemplate(e); - } - - /** - * Matches an ACL message against this MessageTemplate - * object. - * - * @param msg The ACLMessage to check for matching. - * @return true if the ACL message matches this - * template, false otherwise. - */ - public boolean match(ACLMessage msg) { - return toMatch.match(msg); - } - - /** - * Retrieve a string representation of this message template. - * - * @return A string describing the syntactic structure of this - * message template. - */ - public String toString() { - return toMatch.toString(); - } } diff --git a/src/jade/lang/acl/ParseException.java b/src/jade/lang/acl/ParseException.java index 4f01182..441dcf5 100644 --- a/src/jade/lang/acl/ParseException.java +++ b/src/jade/lang/acl/ParseException.java @@ -12,6 +12,35 @@ */ public class ParseException extends Exception { + /** + * This is the last token that has been consumed successfully. If + * this object has been created due to a parse error, the token + * followng this token will (therefore) be the first error token. + */ + public Token currentToken; + /** + * Each entry in this array is an array of integers. Each array + * of integers represents a sequence of tokens (by their ordinal + * values) that is expected at this point of the parse. + */ + public int[][] expectedTokenSequences; + /** + * This is a reference to the "tokenImage" array of the generated + * parser within which the parse error occurred. This array is + * defined in the generated ...Constants interface. + */ + public String[] tokenImage; + /** + * This variable determines which constructor was used to create + * this object and thereby affects the semantics of the + * "getMessage" method (see below). + */ + protected boolean specialConstructor; + /** + * The end of line string for this machine. + */ + protected String eol = System.getProperty("line.separator", "\n"); + /** * This constructor is used by the method "generateParseException" * in the generated parser. Calling this constructor generates @@ -55,34 +84,6 @@ public ParseException(String message) { specialConstructor = false; } - /** - * This variable determines which constructor was used to create - * this object and thereby affects the semantics of the - * "getMessage" method (see below). - */ - protected boolean specialConstructor; - - /** - * This is the last token that has been consumed successfully. If - * this object has been created due to a parse error, the token - * followng this token will (therefore) be the first error token. - */ - public Token currentToken; - - /** - * Each entry in this array is an array of integers. Each array - * of integers represents a sequence of tokens (by their ordinal - * values) that is expected at this point of the parse. - */ - public int[][] expectedTokenSequences; - - /** - * This is a reference to the "tokenImage" array of the generated - * parser within which the parse error occurred. This array is - * defined in the generated ...Constants interface. - */ - public String[] tokenImage; - /** * This method has the standard behavior when this object has been * created using the standard constructors. Otherwise, it uses @@ -103,8 +104,8 @@ public String getMessage() { if (maxSize < expectedTokenSequence.length) { maxSize = expectedTokenSequence.length; } - for (int j = 0; j < expectedTokenSequence.length; j++) { - expected.append(tokenImage[expectedTokenSequence[j]]).append(" "); + for (int i : expectedTokenSequence) { + expected.append(tokenImage[i]).append(" "); } if (expectedTokenSequence[expectedTokenSequence.length - 1] != 0) { expected.append("..."); @@ -133,18 +134,13 @@ public String getMessage() { return retval.toString(); } - /** - * The end of line string for this machine. - */ - protected String eol = System.getProperty("line.separator", "\n"); - /** * Used to convert raw characters to their escaped version * when these raw version cannot be used as part of an ASCII * string literal. */ protected String add_escapes(String str) { - StringBuffer retval = new StringBuffer(); + StringBuilder retval = new StringBuilder(); char ch; for (int i = 0; i < str.length(); i++) { switch (str.charAt(i)) { diff --git a/src/jade/lang/acl/SimpleCharStream.java b/src/jade/lang/acl/SimpleCharStream.java index c26bfde..a796337 100644 --- a/src/jade/lang/acl/SimpleCharStream.java +++ b/src/jade/lang/acl/SimpleCharStream.java @@ -8,24 +8,55 @@ public class SimpleCharStream { public static final boolean staticFlag = false; - int bufsize; - int available; - int tokenBegin; public int bufpos = -1; protected int[] bufline; protected int[] bufcolumn; - protected int column = 0; protected int line = 1; - protected boolean prevCharIsCR = false; protected boolean prevCharIsLF = false; - protected java.io.Reader inputStream; - protected char[] buffer; protected int maxNextCharInd = 0; protected int inBuf = 0; + int bufsize; + int available; + int tokenBegin; + + public SimpleCharStream(java.io.Reader dstream, int startline, + int startcolumn, int buffersize) { + inputStream = dstream; + line = startline; + column = startcolumn - 1; + + available = bufsize = buffersize; + buffer = new char[buffersize]; + bufline = new int[buffersize]; + bufcolumn = new int[buffersize]; + } + + public SimpleCharStream(java.io.Reader dstream, int startline, + int startcolumn) { + this(dstream, startline, startcolumn, 4096); + } + + public SimpleCharStream(java.io.Reader dstream) { + this(dstream, 1, 1, 4096); + } + + public SimpleCharStream(java.io.InputStream dstream, int startline, + int startcolumn, int buffersize) { + this(new java.io.InputStreamReader(dstream), startline, startcolumn, 4096); + } + + public SimpleCharStream(java.io.InputStream dstream, int startline, + int startcolumn) { + this(dstream, startline, startcolumn, 4096); + } + + public SimpleCharStream(java.io.InputStream dstream) { + this(dstream, 1, 1, 4096); + } protected void ExpandBuff(boolean wrapAround) { char[] newbuffer = new char[bufsize + 2048]; @@ -129,18 +160,14 @@ protected void UpdateLineColumn(char c) { } switch (c) { - case '\r': - prevCharIsCR = true; - break; - case '\n': - prevCharIsLF = true; - break; - case '\t': + case '\r' -> prevCharIsCR = true; + case '\n' -> prevCharIsLF = true; + case '\t' -> { column--; column += (8 - (column & 07)); - break; - default: - break; + } + default -> { + } } bufline[bufpos] = line; @@ -207,27 +234,6 @@ public void backup(int amount) { bufpos += bufsize; } - public SimpleCharStream(java.io.Reader dstream, int startline, - int startcolumn, int buffersize) { - inputStream = dstream; - line = startline; - column = startcolumn - 1; - - available = bufsize = buffersize; - buffer = new char[buffersize]; - bufline = new int[buffersize]; - bufcolumn = new int[buffersize]; - } - - public SimpleCharStream(java.io.Reader dstream, int startline, - int startcolumn) { - this(dstream, startline, startcolumn, 4096); - } - - public SimpleCharStream(java.io.Reader dstream) { - this(dstream, 1, 1, 4096); - } - public void ReInit(java.io.Reader dstream, int startline, int startcolumn, int buffersize) { inputStream = dstream; @@ -254,20 +260,6 @@ public void ReInit(java.io.Reader dstream) { ReInit(dstream, 1, 1, 4096); } - public SimpleCharStream(java.io.InputStream dstream, int startline, - int startcolumn, int buffersize) { - this(new java.io.InputStreamReader(dstream), startline, startcolumn, 4096); - } - - public SimpleCharStream(java.io.InputStream dstream, int startline, - int startcolumn) { - this(dstream, startline, startcolumn, 4096); - } - - public SimpleCharStream(java.io.InputStream dstream) { - this(dstream, 1, 1, 4096); - } - public void ReInit(java.io.InputStream dstream, int startline, int startcolumn, int buffersize) { ReInit(new java.io.InputStreamReader(dstream), startline, startcolumn, 4096); diff --git a/src/jade/lang/acl/StringACLCodec.java b/src/jade/lang/acl/StringACLCodec.java index 79a0f56..3114845 100644 --- a/src/jade/lang/acl/StringACLCodec.java +++ b/src/jade/lang/acl/StringACLCodec.java @@ -77,10 +77,11 @@ public class StringACLCodec implements ACLCodec { private static final String REPLY_BY = " :reply-by "; private static final String PROTOCOL = " :protocol "; private static final String CONVERSATION_ID = " :conversation-id "; - + private static final String illegalFirstChar = "#0123456789-"; ACLParser parser = null; Writer out = null; + /** * constructor for the codec. * The standard input is used as an input stream of ACL messages. @@ -107,86 +108,6 @@ public StringACLCodec(Reader r, Writer w) { out = w; } - - /** - * if there was an automatical Base64 encoding, then it performs - * automatic decoding. - **/ - private void checkBase64Encoding(ACLMessage msg) { - String encoding = msg.getUserDefinedParameter(BASE64ENCODING_KEY); - if (CaseInsensitiveString.equalsIgnoreCase(BASE64ENCODING_VALUE, encoding)) { - try { // decode Base64 - String content = msg.getContent(); - if ((content != null) && (content.length() > 0)) { - msg.setByteSequenceContent(Base64.decodeBase64(content.getBytes(StandardCharsets.US_ASCII))); - msg.removeUserDefinedParameter(BASE64ENCODING_KEY); // reset the slot value for encoding - } - } catch (StringIndexOutOfBoundsException | NullPointerException e) { - e.printStackTrace(); - } catch (NoClassDefFoundError jlncdfe) { - System.err.println("\t\t===== E R R O R !!! =======\n"); - System.err.println("Missing support for Base64 conversions"); - System.err.println("Please refer to the documentation for details."); - System.err.println("=============================================\n\n"); - try { - Thread.sleep(3000); - } catch (InterruptedException ignored) { - } - } - } //end of if CaseInsensitiveString - } - - /** - * decode and parses the next message from the Reader passed in the - * constructor. - * - * @return the ACLMessage - * @throws CodecException if any Exception occurs during the - * parsing/reading operation - */ - public ACLMessage decode() throws CodecException { - try { - ACLMessage msg = parser.Message(); - checkBase64Encoding(msg); - return msg; - } catch (TokenMgrError e1) { - throw new CodecException(getName() + " ACLMessage decoding token exception", e1); - } catch (Exception e) { - throw new CodecException(getName() + " ACLMessage decoding exception", e); - } - } - - /** - * Parse an agent identifier, without it being included within an - * ACL message. - */ - public AID decodeAID() throws CodecException { - try { - return parser.parseAID(null); - } catch (TokenMgrError e1) { - throw new CodecException(getName() + " AID decoding token exception", e1); - } catch (Exception e) { - e.printStackTrace(); - throw new CodecException(getName() + " AID decoding exception", e); - } - } - - /** - * encodes the message and writes it into the Writer passed in the - * constructor. - * Notice that this method does not call flush on the writer. - * - * @ param msg is the ACLMessage to encode and write into - */ - public void write(ACLMessage msg) { - try { - out.write(toString(msg)); - } catch (Exception e) { - e.printStackTrace(); - } - } - - static private String escape(String s) { // Make the stringBuffer a little larger than strictly // necessary in case we need to insert any additional @@ -298,44 +219,6 @@ static String toString(ACLMessage msg) { return str.toString(); } - /** - * If the content of the message is a byteSequence, then this - * method encodes the content in Base64 and automatically sets the value - * of the encoding slot. - * see ACLCodec#encode(ACLMessage msg) - */ - public byte[] encode(ACLMessage msg, String charset) { - try { - return toString(msg).getBytes(charset); - } catch (IOException ioe) { - ioe.printStackTrace(); - return new byte[0]; - } - } - - - /** - * see ACLCodec#decode(byte[] data) - */ - public ACLMessage decode(byte[] data, String charset) throws CodecException { - try { - ACLMessage msg = ACLParser.create().parse(new InputStreamReader(new ByteArrayInputStream(data), charset)); - checkBase64Encoding(msg); - return msg; - } catch (TokenMgrError e1) { - throw new CodecException(getName() + " ACLMessage decoding token exception", e1); - } catch (Exception e2) { - throw new CodecException(getName() + " ACLMessage decoding exception", e2); - } - } - - /** - * @return the name of this encoding according to the FIPA specifications - */ - public String getName() { - return NAME; - } - /** * append to the passed StringBuffer the slot name and value separated * by a blank char and followed by a newline. @@ -358,9 +241,6 @@ static public void appendACLExpression(StringBuffer str, String slotName, String } } - - private static final String illegalFirstChar = "#0123456789-"; - /** * Test if the given string is a legal word using the FIPA ACL spec. * In addition to FIPA's restrictions, place the additional restriction @@ -383,5 +263,120 @@ static private boolean isAWord(String s) { return true; } + /** + * if there was an automatical Base64 encoding, then it performs + * automatic decoding. + **/ + private void checkBase64Encoding(ACLMessage msg) { + String encoding = msg.getUserDefinedParameter(BASE64ENCODING_KEY); + if (CaseInsensitiveString.equalsIgnoreCase(BASE64ENCODING_VALUE, encoding)) { + try { // decode Base64 + String content = msg.getContent(); + if ((content != null) && (content.length() > 0)) { + msg.setByteSequenceContent(Base64.decodeBase64(content.getBytes(StandardCharsets.US_ASCII))); + msg.removeUserDefinedParameter(BASE64ENCODING_KEY); // reset the slot value for encoding + } + } catch (StringIndexOutOfBoundsException | NullPointerException e) { + e.printStackTrace(); + } catch (NoClassDefFoundError jlncdfe) { + System.err.println("\t\t===== E R R O R !!! =======\n"); + System.err.println("Missing support for Base64 conversions"); + System.err.println("Please refer to the documentation for details."); + System.err.println("=============================================\n\n"); + try { + Thread.sleep(3000); + } catch (InterruptedException ignored) { + } + } + } //end of if CaseInsensitiveString + } + + /** + * decode and parses the next message from the Reader passed in the + * constructor. + * + * @return the ACLMessage + * @throws CodecException if any Exception occurs during the + * parsing/reading operation + */ + public ACLMessage decode() throws CodecException { + try { + ACLMessage msg = parser.Message(); + checkBase64Encoding(msg); + return msg; + } catch (TokenMgrError e1) { + throw new CodecException(getName() + " ACLMessage decoding token exception", e1); + } catch (Exception e) { + throw new CodecException(getName() + " ACLMessage decoding exception", e); + } + } + + /** + * Parse an agent identifier, without it being included within an + * ACL message. + */ + public AID decodeAID() throws CodecException { + try { + return parser.parseAID(null); + } catch (TokenMgrError e1) { + throw new CodecException(getName() + " AID decoding token exception", e1); + } catch (Exception e) { + e.printStackTrace(); + throw new CodecException(getName() + " AID decoding exception", e); + } + } + + /** + * encodes the message and writes it into the Writer passed in the + * constructor. + * Notice that this method does not call flush on the writer. + * + * @ param msg is the ACLMessage to encode and write into + */ + public void write(ACLMessage msg) { + try { + out.write(toString(msg)); + } catch (Exception e) { + e.printStackTrace(); + } + } + + /** + * If the content of the message is a byteSequence, then this + * method encodes the content in Base64 and automatically sets the value + * of the encoding slot. + * see ACLCodec#encode(ACLMessage msg) + */ + public byte[] encode(ACLMessage msg, String charset) { + try { + return toString(msg).getBytes(charset); + } catch (IOException ioe) { + ioe.printStackTrace(); + return new byte[0]; + } + } + + /** + * see ACLCodec#decode(byte[] data) + */ + public ACLMessage decode(byte[] data, String charset) throws CodecException { + try { + ACLMessage msg = ACLParser.create().parse(new InputStreamReader(new ByteArrayInputStream(data), charset)); + checkBase64Encoding(msg); + return msg; + } catch (TokenMgrError e1) { + throw new CodecException(getName() + " ACLMessage decoding token exception", e1); + } catch (Exception e2) { + throw new CodecException(getName() + " ACLMessage decoding exception", e2); + } + } + + /** + * @return the name of this encoding according to the FIPA specifications + */ + public String getName() { + return NAME; + } + } diff --git a/src/jade/lang/acl/Token.java b/src/jade/lang/acl/Token.java index 6f5c391..8ebc904 100644 --- a/src/jade/lang/acl/Token.java +++ b/src/jade/lang/acl/Token.java @@ -50,13 +50,6 @@ public class Token { */ public Token specialToken; - /** - * Returns the image. - */ - public String toString() { - return image; - } - /** * Returns a new Token object, by default. However, if you want, you * can create and return subclass objects based on the value of ofKind. @@ -73,4 +66,11 @@ public static final Token newToken(int ofKind) { return new Token(); } + /** + * Returns the image. + */ + public String toString() { + return image; + } + } diff --git a/src/jade/lang/acl/TokenMgrError.java b/src/jade/lang/acl/TokenMgrError.java index 66d0d51..988f67a 100644 --- a/src/jade/lang/acl/TokenMgrError.java +++ b/src/jade/lang/acl/TokenMgrError.java @@ -32,12 +32,28 @@ public class TokenMgrError extends Error { */ int errorCode; + public TokenMgrError() { + } + + public TokenMgrError(String message, int reason) { + super(message); + errorCode = reason; + } + + public TokenMgrError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar, int reason) { + this(LexicalError(EOFSeen, lexState, errorLine, errorColumn, errorAfter, curChar), reason); + } + + /* + * Constructors of various flavors follow. + */ + /** * Replaces unprintable characters by their espaced (or unicode escaped) * equivalents in the given string */ protected static final String addEscapes(String str) { - StringBuffer retval = new StringBuffer(); + StringBuilder retval = new StringBuilder(); char ch; for (int i = 0; i < str.length(); i++) { switch (str.charAt(i)) { @@ -112,20 +128,4 @@ protected static String LexicalError(boolean EOFSeen, int lexState, int errorLin public String getMessage() { return super.getMessage(); } - - /* - * Constructors of various flavors follow. - */ - - public TokenMgrError() { - } - - public TokenMgrError(String message, int reason) { - super(message); - errorCode = reason; - } - - public TokenMgrError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar, int reason) { - this(LexicalError(EOFSeen, lexState, errorLine, errorColumn, errorAfter, curChar), reason); - } } diff --git a/src/jade/mtp/InChannel.java b/src/jade/mtp/InChannel.java index 1f43ab4..a62ae53 100644 --- a/src/jade/mtp/InChannel.java +++ b/src/jade/mtp/InChannel.java @@ -31,14 +31,6 @@ */ public interface InChannel { - /** - * Callback interface to be notified of message arrivals over this - * Message Transport Protocol. - */ - interface Dispatcher { - void dispatchMessage(Envelope env, byte[] payload); - } - /** * Activates an MTP handler for incoming messages on a default * address. @@ -82,4 +74,12 @@ interface Dispatcher { */ void deactivate() throws MTPException; + /** + * Callback interface to be notified of message arrivals over this + * Message Transport Protocol. + */ + interface Dispatcher { + void dispatchMessage(Envelope env, byte[] payload); + } + } diff --git a/src/jade/mtp/MTPDescriptor.java b/src/jade/mtp/MTPDescriptor.java index 26cef49..470e3e4 100644 --- a/src/jade/mtp/MTPDescriptor.java +++ b/src/jade/mtp/MTPDescriptor.java @@ -35,6 +35,8 @@ public class MTPDescriptor implements Serializable { private String className; private String[] addresses; private String[] protoNames; + // For persistence service + private Long persistentID; public MTPDescriptor(String n, String cn, String[] a, String[] pn) { name = n; @@ -43,22 +45,47 @@ public MTPDescriptor(String n, String cn, String[] a, String[] pn) { protoNames = pn; } + //#MIDP_EXCLUDE_BEGIN + // For persistence service + private MTPDescriptor() { + } + public String getName() { return name; } + // For persistence service + private void setName(String n) { + name = n; + } + public String getClassName() { return className; } + // For persistence service + private void setClassName(String cn) { + className = cn; + } + public String[] getAddresses() { return addresses; } + // For persistence service + private void setAddresses(String[] a) { + addresses = a; + } + public String[] getSupportedProtocols() { return protoNames; } + // For persistence service + private void setSupportedProtocols(String[] sp) { + protoNames = sp; + } + public boolean equals(Object obj) { try { MTPDescriptor toBeCompared = (MTPDescriptor) obj; @@ -95,35 +122,6 @@ public String toString() { return "(MTP :name " + name + " :class-name" + className + " :addresses " + Arrays.toString(addresses) + ")"; } - //#MIDP_EXCLUDE_BEGIN - // For persistence service - private MTPDescriptor() { - } - - // For persistence service - private void setName(String n) { - name = n; - } - - // For persistence service - private void setClassName(String cn) { - className = cn; - } - - // For persistence service - private void setAddresses(String[] a) { - addresses = a; - } - - // For persistence service - private void setSupportedProtocols(String[] sp) { - protoNames = sp; - } - - - // For persistence service - private Long persistentID; - // For persistence service private Long getPersistentID() { return persistentID; diff --git a/src/jade/mtp/http/BasicFipaDateTime.java b/src/jade/mtp/http/BasicFipaDateTime.java index 191e732..8c84578 100644 --- a/src/jade/mtp/http/BasicFipaDateTime.java +++ b/src/jade/mtp/http/BasicFipaDateTime.java @@ -62,6 +62,7 @@ public BasicFipaDateTime(String str) { /** * Get the value of year. + * * @return Value of year. */ public short getYear() { @@ -70,7 +71,8 @@ public short getYear() { /** * Set the value of year. - * @param v Value to assign to year. + * + * @param v Value to assign to year. */ public void setYear(short v) { cal.set(Calendar.YEAR, v); @@ -78,6 +80,7 @@ public void setYear(short v) { /** * Get the value of month. + * * @return Value of month. */ public short getMonth() { @@ -86,7 +89,8 @@ public short getMonth() { /** * Set the value of month. - * @param v Value to assign to month. + * + * @param v Value to assign to month. */ public void setMonth(short v) { cal.set(Calendar.MONTH, v - 1); @@ -94,6 +98,7 @@ public void setMonth(short v) { /** * Get the value of day. + * * @return Value of day. */ public short getDay() { @@ -102,7 +107,8 @@ public short getDay() { /** * Set the value of day. - * @param v Value to assign to day. + * + * @param v Value to assign to day. */ public void setDay(short v) { cal.set(Calendar.DAY_OF_MONTH, v); @@ -110,6 +116,7 @@ public void setDay(short v) { /** * Get the value of hour. + * * @return Value of hour. */ public short getHour() { @@ -118,7 +125,8 @@ public short getHour() { /** * Set the value of hour. - * @param v Value to assign to hour. + * + * @param v Value to assign to hour. */ public void setHour(short v) { cal.set(Calendar.HOUR_OF_DAY, v); @@ -126,6 +134,7 @@ public void setHour(short v) { /** * Get the value of minutes. + * * @return Value of minutes. */ public short getMinutes() { @@ -134,7 +143,8 @@ public short getMinutes() { /** * Set the value of minutes. - * @param v Value to assign to minutes. + * + * @param v Value to assign to minutes. */ public void setMinutes(short v) { cal.set(Calendar.MINUTE, v); @@ -142,6 +152,7 @@ public void setMinutes(short v) { /** * Get the value of seconds. + * * @return Value of seconds. */ public short getSeconds() { @@ -150,7 +161,8 @@ public short getSeconds() { /** * Set the value of seconds. - * @param v Value to assign to seconds. + * + * @param v Value to assign to seconds. */ public void setSeconds(short v) { cal.set(Calendar.SECOND, v); @@ -158,6 +170,7 @@ public void setSeconds(short v) { /** * Get the value of milliseconds. + * * @return Value of milliseconds. */ public short getMilliseconds() { @@ -166,7 +179,8 @@ public short getMilliseconds() { /** * Set the value of milliseconds. - * @param v Value to assign to milliseconds. + * + * @param v Value to assign to milliseconds. */ public void setMilliseconds(short v) { cal.set(Calendar.MILLISECOND, v); @@ -174,6 +188,7 @@ public void setMilliseconds(short v) { /** * Get the value of typeDesignator. + * * @return Value of typeDesignator. */ public char getTypeDesignator() { @@ -182,7 +197,8 @@ public char getTypeDesignator() { /** * Set the value of typeDesignator. - * @param v Value to assign to typeDesignator. + * + * @param v Value to assign to typeDesignator. */ public void setTypeDesignator(char v) { this.typeDesignator = v; diff --git a/src/jade/mtp/http/HTTPIO.java b/src/jade/mtp/http/HTTPIO.java index 1a38adf..f61b6bd 100644 --- a/src/jade/mtp/http/HTTPIO.java +++ b/src/jade/mtp/http/HTTPIO.java @@ -57,6 +57,8 @@ public class HTTPIO { // Response codes public static final String OK = "200 OK"; + public static final String CLOSE = "close"; + public static final String KA = "Keep-Alive"; private static final String ERROR = "406 Not Acceptable"; //private static final String UNAV = "503 Service Unavailable"; // HTTP constants @@ -78,8 +80,6 @@ public class HTTPIO { private static final byte[] APPLI = {(byte) 'a', (byte) 'p', (byte) 'p', (byte) 'l', (byte) 'i', (byte) 'c', (byte) 'a', (byte) 't', (byte) 'i', (byte) 'o', (byte) 'n', (byte) '/'}; private static final byte[] CONN = {(byte) 'C', (byte) 'o', (byte) 'n', (byte) 'n', (byte) 'e', (byte) 'c', (byte) 't', (byte) 'i', (byte) 'o', (byte) 'n', (byte) ':', (byte) ' '}; private static final String CONN_STR = "Connection: "; - public static final String CLOSE = "close"; - public static final String KA = "Keep-Alive"; private static final byte[] HTTP = {(byte) 'H', (byte) 'T', (byte) 'T', (byte) 'P', (byte) '/', (byte) '1', (byte) '.', (byte) '1'}; private static final byte[] CACHE = {(byte) 'C', (byte) 'a', (byte) 'c', (byte) 'h', (byte) 'e', (byte) '-', (byte) 'C', (byte) 'o', (byte) 'n', (byte) 't', (byte) 'r', (byte) 'o', (byte) 'l', (byte) ':', (byte) ' ', (byte) 'n', (byte) 'o', (byte) '-', (byte) 'c', (byte) 'a', (byte) 'c', (byte) 'h', (byte) 'e'}; @@ -276,6 +276,7 @@ public static String blockOnRead(BufferedReader br) throws IOException { /** * Parse the input message, this message is received from the master server + * * @param type return type of connection: close or Keep-Alive */ public static String readAll(InputStream input, StringBuffer xml, OutputStream acl, StringBuffer type) @@ -490,11 +491,11 @@ private static String processLine(String line) * with pattern. If the specified pattern was not found until the input stream reaches at end, output * all byte sequence up to end of input stream and returns false. * - * @param input specified input stream. - * @param output specified output stream. + * @param input specified input stream. + * @param output specified output stream. * @param pattern specified pattern byte seqence. * @return Whether the specified pattern was found or not. - * @throws IOException If an I/O error occurs. + * @throws IOException If an I/O error occurs. * @throws IllegalArgumentException If pattern is null or pattern is empty. * @author mminagawa */ @@ -537,8 +538,8 @@ private static boolean readBytesUpTo(InputStream input, OutputStream output, byt * * @param input specified input stream to read from. * @return A String containing the contents of the line, not including any line-termination - * characters, or null if the end of the stream has been reached. - * @throws IOException If an I/O error occurs. + * characters, or null if the end of the stream has been reached. + * @throws IOException If an I/O error occurs. * @author mminagawa */ private static String readLineFromInputStream(InputStream input) throws IOException { @@ -588,7 +589,7 @@ private static String readLineFromInputStream(InputStream input) throws IOExcept * * @param output specified output stream. * @param string specified string to output. - * @throws IOException If an I/O error occurs. + * @throws IOException If an I/O error occurs. * @author mminagawa */ private static void writeLowBytes(OutputStream output, String string) throws IOException { diff --git a/src/jade/mtp/http/HTTPServer.java b/src/jade/mtp/http/HTTPServer.java index 698e1d8..b1e19c3 100644 --- a/src/jade/mtp/http/HTTPServer.java +++ b/src/jade/mtp/http/HTTPServer.java @@ -34,6 +34,13 @@ * @version 0.1 * @author Nicolas Lhuillier (Motorola Labs) * @version 1.0 + *

+ * HTTPServer.java + * @author Jose Antonio Exposito + * @author MARISM-A Development group ( marisma-info@ccd.uab.es ) + * @version 0.1 + * @author Nicolas Lhuillier (Motorola Labs) + * @version 1.0 */ /** @@ -64,26 +71,21 @@ public class HTTPServer extends Thread { // Codec class + //logging + private static final Logger logger = Logger.getMyLogger(HTTPServer.class.getName()); + //attribute for synchronized + private static final Object lock = new Object(); //static String CODEC = "org.apache.xerces.parsers.SAXParser"; static String CODEC = "org.apache.crimson.parser.XMLReaderImpl"; - private final String address; private final int port; private final Dispatcher dispatcher; private final int maxKA; private final int timeout; - private ServerSocket server; - - //logging - private static final Logger logger = Logger.getMyLogger(HTTPServer.class.getName()); - private final Vector threads; // for keep alive connections - - //attribute for synchronized - private static final Object lock = new Object(); - // the flag that shows if the server is active or not boolean active = true; + private ServerSocket server; /** Constructor: Store the information*/ public HTTPServer(String interfaceAddress, int p, Dispatcher d, int m, String s, int t, boolean changePortIfBusy) throws IOException { @@ -210,9 +212,9 @@ public void run() { public static class ServerThread extends Thread { private final HTTPServer father; private final Socket client; + private final Dispatcher dispatcher; private InputStream input; private OutputStream output; - private final Dispatcher dispatcher; private XMLCodec codec; private boolean keepAlive = false; private boolean active = false; diff --git a/src/jade/mtp/http/HTTPSocketFactory.java b/src/jade/mtp/http/HTTPSocketFactory.java index 28a6f7b..be2b861 100644 --- a/src/jade/mtp/http/HTTPSocketFactory.java +++ b/src/jade/mtp/http/HTTPSocketFactory.java @@ -55,6 +55,18 @@ Implementation Copyright (C) 2000, Laboratoire d'Intelligence */ public class HTTPSocketFactory { + private static final String PREFIX = "jade_mtp_http_https_"; + private static final String MTP_HTTP_PREFIX = "jade_mtp_http_"; + private static final int DEFAULT_CONNECT_TIMEOUT = -1; + private static HTTPSocketFactory _instance; + private SocketFactory _socketFactory; + private ServerSocketFactory _serverSocketFactory; + private boolean _needClientAuth = false; + private boolean _usingHttps = false; + private int connectTimeout; + private HTTPSocketFactory() { + } + public static HTTPSocketFactory getInstance() { if (_instance == null) _instance = new HTTPSocketFactory(); @@ -166,17 +178,4 @@ public ServerSocket createServerSocket(String interfaceAddress, int port) throws //#DOTNET_EXCLUDE_END return ss; } - - private HTTPSocketFactory() { - } - - private static HTTPSocketFactory _instance; - private static final String PREFIX = "jade_mtp_http_https_"; - private static final String MTP_HTTP_PREFIX = "jade_mtp_http_"; - private static final int DEFAULT_CONNECT_TIMEOUT = -1; - private SocketFactory _socketFactory; - private ServerSocketFactory _serverSocketFactory; - private boolean _needClientAuth = false; - private boolean _usingHttps = false; - private int connectTimeout; } diff --git a/src/jade/mtp/http/KeepAlive.java b/src/jade/mtp/http/KeepAlive.java index 3f17973..f47f3fe 100644 --- a/src/jade/mtp/http/KeepAlive.java +++ b/src/jade/mtp/http/KeepAlive.java @@ -34,6 +34,13 @@ * @version 0.1 * @author Nicolas Lhuillier (Motorola Labs) * @version 1.0 + *

+ * KeepAlive.java + * @author Jose Antonio Exposito + * @author MARISM-A Development group ( marisma-info@ccd.uab.es ) + * @version 0.1 + * @author Nicolas Lhuillier (Motorola Labs) + * @version 1.0 */ /** @@ -65,119 +72,11 @@ public class KeepAlive { private static final Logger logger = Logger.getMyLogger(KeepAlive.class.getName()); - - /* - * Inner structure to contain all connection information - */ - public static class KAConnection { - private OutputStream out; - private InputStream in; - private final HTTPAddress address; - private Vector connections; - private final int outPort; - - KAConnection(HTTPAddress a, int outPort) { - address = a; - this.outPort = outPort; - } - - public void open() throws IOException { - // The address is new or the KA connection was closed - //HTTPAddress is new or cached missed; - // Open a new connection - Socket client; - //#PJAVA_EXCLUDE_BEGIN - HTTPSocketFactory sfac = HTTPSocketFactory.getInstance(); - if (outPort > 0) { - client = sfac.createSocket(address.getHost(), address.getPortNo(), InetAddress.getLocalHost(), outPort); - } else { - client = sfac.createSocket(address.getHost(), address.getPortNo()); - } - - //#PJAVA_EXCLUDE_END - /*#PJAVA_INCLUDE_BEGIN - if (outPort > 0) - { - client = new Socket(address.getHost(),address.getPortNo(),InetAddress.getLocalHost(),outPort); - } - else { - client = new Socket(address.getHost(),address.getPortNo()); - } - #PJAVA_INCLUDE_END*/ - out = new BufferedOutputStream(client.getOutputStream()); - in = new BufferedInputStream(client.getInputStream()); - } - - OutputStream getOut() { - return out; - } - - InputStream getIn() { - return in; - } - - public HTTPAddress getAddress() { - return address; - } - - public boolean equals(HTTPAddress a) { - return address.equals(a); - } - - - void close() { - if (isOpen()) { - try { - in.close(); - out.close(); - } catch (IOException ioe) { - if (logger.isLoggable(Logger.WARNING)) - logger.log(Logger.WARNING, "Exception while closing KA connection: " + ioe); - } - in = null; - out = null; - } - } - - boolean isOpen() { - return in != null; - } - - void send(byte[] req) throws MTPException { - try { - if (logger.isLoggable(Logger.FINER)) - logger.log(Logger.FINER, "Sending HTTP message to: " + address); - HTTPIO.writeAll(out, req); - //Capture the HTTPresponse - StringBuffer typeConnection = new StringBuffer(); - int code = HTTPIO.getResponseCode(in, typeConnection); - if (!HTTPIO.KA.equals(typeConnection.toString())) { - // Close the connection - if (logger.isLoggable(Logger.FINER)) - logger.log(Logger.FINER, "Closing " + typeConnection + " connection to " + address); - close(); - } - if (code != 200) { - if (logger.isLoggable(Logger.FINER)) - logger.log(Logger.FINER, "Not OK: " + code + ", Closing connection to " + address); - close(); - throw new MTPException("Description: ResponseMessage is not OK"); - } - } catch (IOException e) { - close(); - throw new MTPException(e.getMessage(), e); - } - } - - - } // End of KAConnection inner class - private final Vector connections; private final int dim; private final int outPort; private final boolean agressive; private final HashMap locks = new HashMap<>(); - /** Constructor */ public KeepAlive(int dim, int outPort, boolean agressive) { connections = new Vector<>(dim); @@ -223,7 +122,6 @@ public synchronized void remove(KAConnection ka) { connections.removeElement(ka); } - /** get the socket of the connection when addr make matching */ private KAConnection getConnection(int pos) { return connections.elementAt(pos); @@ -287,7 +185,6 @@ public synchronized void swap(KAConnection c) { } } - public void send(HTTPAddress url, byte[] request) throws MTPException { Object lock = getLock(url); synchronized (lock) { @@ -348,14 +245,116 @@ private Object getLock(final HTTPAddress url) { Object lock = locks.get(url.getHost()); if (lock == null) { synchronized (this) { - lock = locks.get(url.getHost()); - if (lock == null) { - lock = new Object(); - locks.put(url.getHost(), lock); - } + lock = locks.computeIfAbsent(url.getHost(), k -> new Object()); } } return lock; } + /* + * Inner structure to contain all connection information + */ + public static class KAConnection { + private final HTTPAddress address; + private final int outPort; + private OutputStream out; + private InputStream in; + private Vector connections; + + KAConnection(HTTPAddress a, int outPort) { + address = a; + this.outPort = outPort; + } + + public void open() throws IOException { + // The address is new or the KA connection was closed + //HTTPAddress is new or cached missed; + // Open a new connection + Socket client; + //#PJAVA_EXCLUDE_BEGIN + HTTPSocketFactory sfac = HTTPSocketFactory.getInstance(); + if (outPort > 0) { + client = sfac.createSocket(address.getHost(), address.getPortNo(), InetAddress.getLocalHost(), outPort); + } else { + client = sfac.createSocket(address.getHost(), address.getPortNo()); + } + + //#PJAVA_EXCLUDE_END + /*#PJAVA_INCLUDE_BEGIN + if (outPort > 0) + { + client = new Socket(address.getHost(),address.getPortNo(),InetAddress.getLocalHost(),outPort); + } + else { + client = new Socket(address.getHost(),address.getPortNo()); + } + #PJAVA_INCLUDE_END*/ + out = new BufferedOutputStream(client.getOutputStream()); + in = new BufferedInputStream(client.getInputStream()); + } + + OutputStream getOut() { + return out; + } + + InputStream getIn() { + return in; + } + + public HTTPAddress getAddress() { + return address; + } + + public boolean equals(HTTPAddress a) { + return address.equals(a); + } + + + void close() { + if (isOpen()) { + try { + in.close(); + out.close(); + } catch (IOException ioe) { + if (logger.isLoggable(Logger.WARNING)) + logger.log(Logger.WARNING, "Exception while closing KA connection: " + ioe); + } + in = null; + out = null; + } + } + + boolean isOpen() { + return in != null; + } + + void send(byte[] req) throws MTPException { + try { + if (logger.isLoggable(Logger.FINER)) + logger.log(Logger.FINER, "Sending HTTP message to: " + address); + HTTPIO.writeAll(out, req); + //Capture the HTTPresponse + StringBuffer typeConnection = new StringBuffer(); + int code = HTTPIO.getResponseCode(in, typeConnection); + if (!HTTPIO.KA.equals(typeConnection.toString())) { + // Close the connection + if (logger.isLoggable(Logger.FINER)) + logger.log(Logger.FINER, "Closing " + typeConnection + " connection to " + address); + close(); + } + if (code != 200) { + if (logger.isLoggable(Logger.FINER)) + logger.log(Logger.FINER, "Not OK: " + code + ", Closing connection to " + address); + close(); + throw new MTPException("Description: ResponseMessage is not OK"); + } + } catch (IOException e) { + close(); + throw new MTPException(e.getMessage(), e); + } + } + + + } // End of KAConnection inner class + } //End of class KeepAlive diff --git a/src/jade/mtp/http/MessageTransportProtocol.java b/src/jade/mtp/http/MessageTransportProtocol.java index 80548d8..4cf0d21 100644 --- a/src/jade/mtp/http/MessageTransportProtocol.java +++ b/src/jade/mtp/http/MessageTransportProtocol.java @@ -34,6 +34,13 @@ * @version 0.1 * @author Nicolas Lhuillier (Motorola Labs) * @version 1.0 + *

+ * MessageTransportProtocol.java + * @author Jose Antonio Exposito + * @author MARISM-A Development group ( marisma-info@ccd.uab.es ) + * @version 0.1 + * @author Nicolas Lhuillier (Motorola Labs) + * @version 1.0 */ /** @@ -76,7 +83,8 @@ public class MessageTransportProtocol implements MTP { private static final String POLICY = "conservative"; //conservative or aggressive private static final String PREFIX = "jade_mtp_http_"; private static final String TIMEOUT = "60000"; // 60 seconds - + private final String FIPA_NAME = "fipa.mts.mtp.http.std"; + private final Hashtable addr2srv = new Hashtable<>(); private int numKA; private String proxyHost; private int proxyPort; @@ -85,11 +93,7 @@ public class MessageTransportProtocol implements MTP { private boolean policy; private boolean keepAlive = false; private boolean useProxy = false; - private String[] protocols = {}; - private final String FIPA_NAME = "fipa.mts.mtp.http.std"; - private final Hashtable addr2srv = new Hashtable<>(); - //Object Keep-Alive connections private KeepAlive ka; diff --git a/src/jade/mtp/http/XMLCodec.java b/src/jade/mtp/http/XMLCodec.java index ab99b64..3344b0d 100644 --- a/src/jade/mtp/http/XMLCodec.java +++ b/src/jade/mtp/http/XMLCodec.java @@ -105,14 +105,14 @@ public class XMLCodec extends DefaultHandler { public final static char[] badChars = { '\r', '\n', ' ' }; public final static String CHARS_CODEC = "ISO-8859-1"; #DOTNET_INCLUDE_END*/ - - //#DOTNET_EXCLUDE_BEGIN - private final XMLReader parser; + //logging + private static final Logger logger = Logger.getMyLogger(XMLCodec.class.getName()); //#DOTNET_EXCLUDE_END /*#DOTNET_INCLUDE_BEGIN private XmlTextReader parser = null; #DOTNET_INCLUDE_END*/ - + //#DOTNET_EXCLUDE_BEGIN + private final XMLReader parser; private Envelope env = null; private ReceivedObject ro = null; private AID aid = null; @@ -120,8 +120,6 @@ public class XMLCodec extends DefaultHandler { // Accumulate parsed text private StringBuffer accumulator; private String propType; - //logging - private static final Logger logger = Logger.getMyLogger(XMLCodec.class.getName()); //var for detected tag to then origin=0, or tag from then origin=1 //private int origin; @@ -142,6 +140,7 @@ public class XMLCodec extends DefaultHandler { /** * Constructor: + * * @param parserClass the SAX parser class to use */ public XMLCodec(String parserClass) throws MTPException { @@ -166,7 +165,9 @@ public XMLCodec() throws MTPException {} // * Encoding methods * // *************************************************** - /** Encode the information of Agent, Tags To and From **/ + /** + * Encode the information of Agent, Tags To and From + **/ private static void encodeAid(StringBuffer sb, AID aid) { sb.append(OT).append(AID_TAG).append(CT); encodeTag(sb, AID_NAME, aid.getName()); @@ -195,7 +196,6 @@ private static void encodeTag(StringBuffer sb, String tag, String content) { /** * A user-defined property (String name, Object value) is encoded the following way: * value - * */ private static void encodeProp(StringBuffer sb, Property p) { String v = null; @@ -230,32 +230,14 @@ private static void encodeProp(StringBuffer sb, Property p) { sb.append(ET).append(PROP_TAG).append(CT); } - private void decodeProp(StringBuffer acc, Property p) { - if (propType.equals(PROP_SER_TYPE)) { - try { - byte[] serdata = acc.toString().getBytes(StandardCharsets.US_ASCII); - ObjectInputStream ois = new ObjectInputStream( - new ByteArrayInputStream(Base64.decodeBase64(serdata))); - p.setValue(ois.readObject()); - } catch (Exception e) { - // nothing, we leave value of this property as null; - } - } else if (propType.equals(PROP_BYTE_TYPE)) { - byte[] bytes; - bytes = acc.toString().getBytes(StandardCharsets.US_ASCII); - p.setValue(Base64.decodeBase64(bytes)); - } else { - p.setValue(acc.toString()); - } - propType = null; - } - private static void encodeOneLineTag(StringBuffer sb, String tag1, String tag2, String value) { sb.append(OT).append(tag1).append(" "); sb.append(tag2).append("=\"").append(value).append("\"/>"); } - /** General Encoding of the envelope */ + /** + * General Encoding of the envelope + */ public static synchronized String encodeXML(Envelope env) { //Create the message XML @@ -311,7 +293,7 @@ public static synchronized String encodeXML(Envelope env) { //Create tag encrypted (NL: not sure it is still in FIPA) /* for (i=env.getAllEncrypted();i.hasNext();) { - encodeTag(sb,ENCRYPTED_TAG,i.next().toString()); + encodeTag(sb,ENCRYPTED_TAG,i.next().toString()); } */ @@ -361,23 +343,49 @@ public static synchronized String encodeXML(Envelope env) { return sb.toString(); } + private void decodeProp(StringBuffer acc, Property p) { + if (propType.equals(PROP_SER_TYPE)) { + try { + byte[] serdata = acc.toString().getBytes(StandardCharsets.US_ASCII); + ObjectInputStream ois = new ObjectInputStream( + new ByteArrayInputStream(Base64.decodeBase64(serdata))); + p.setValue(ois.readObject()); + } catch (Exception e) { + // nothing, we leave value of this property as null; + } + } else if (propType.equals(PROP_BYTE_TYPE)) { + byte[] bytes; + bytes = acc.toString().getBytes(StandardCharsets.US_ASCII); + p.setValue(Base64.decodeBase64(bytes)); + } else { + p.setValue(acc.toString()); + } + propType = null; + } + // *************************************************** // * Decoding methods * // *************************************************** - /** This method is called when start the document XML*/ + /** + * This method is called when start the document XML + */ public void startDocument() { env = new Envelope(); } - /** This method is called at the end of parsing */ + /** + * This method is called at the end of parsing + */ public void endDocument() { //Put the ro object in to envelope //env.setReceived(ro); } - /** This method is called when jmp event of begin element.*/ + /** + * This method is called when jmp event of begin element. + */ public void startElement(String uri, String localName, String rawName, Attributes attributes) { //Detection of the begin of to or from tags @@ -414,7 +422,9 @@ public void startElement(String uri, String localName, String rawName, Attribute } } - /** This method is called the end of element */ + /** + * This method is called the end of element + */ public void endElement(String namespaceURL, String localName, String qname) { //Capture the value the attributes of class @@ -446,12 +456,16 @@ else if (ENCRYPTED_TAG.equalsIgnoreCase(localName)) { */ } - /** This method is called when exist characters in the elements*/ + /** + * This method is called when exist characters in the elements + */ public void characters(char[] buffer, int start, int length) { accumulator.append(buffer, start, length); } - /** This method is called when warning occur*/ + /** + * This method is called when warning occur + */ //#DOTNET_EXCLUDE_BEGIN public void warning(SAXParseException exception) { //#DOTNET_EXCLUDE_END @@ -469,7 +483,9 @@ public void warning(ParseException exception) { #DOTNET_INCLUDE_END*/ } - /** This method is called when errors occur*/ + /** + * This method is called when errors occur + */ //#DOTNET_EXCLUDE_BEGIN public void error(SAXParseException exception) { //#DOTNET_EXCLUDE_END @@ -487,7 +503,9 @@ public void error(ParseException exception) { #DOTNET_INCLUDE_END*/ } - /** This method is called when non-recoverable errors occur.*/ + /** + * This method is called when non-recoverable errors occur. + */ //#DOTNET_EXCLUDE_BEGIN public void fatalError(SAXParseException exception) throws SAXException { //#DOTNET_EXCLUDE_END diff --git a/src/jade/mtp/http/https/FriendListAuthentication.java b/src/jade/mtp/http/https/FriendListAuthentication.java index 3dbc947..e4027a4 100644 --- a/src/jade/mtp/http/https/FriendListAuthentication.java +++ b/src/jade/mtp/http/https/FriendListAuthentication.java @@ -53,6 +53,8 @@ */ public class FriendListAuthentication implements HTTPSTrustManager { + private X509TrustManager _tm; + public X509Certificate[] getAcceptedIssuers() { return _tm.getAcceptedIssuers(); } @@ -78,6 +80,4 @@ public void init(Profile profile) throws Exception { _tm = (X509TrustManager) tmf.getTrustManagers()[0]; } - private X509TrustManager _tm; - } diff --git a/src/jade/mtp/http/https/KeyStoreKeyManager.java b/src/jade/mtp/http/https/KeyStoreKeyManager.java index bd53d1f..a3873b5 100644 --- a/src/jade/mtp/http/https/KeyStoreKeyManager.java +++ b/src/jade/mtp/http/https/KeyStoreKeyManager.java @@ -59,6 +59,11 @@ Implementation Copyright (C) 2000, Laboratoire d'Intelligence */ public class KeyStoreKeyManager implements HTTPSKeyManager { + private static final String PREFIX = "jade_mtp_http_https_"; + private PrivateKey privateKey; + private X509Certificate[] cert; + private String alias; + public void init(Profile profile) throws Exception { String pass = profile.getParameter(PREFIX + "keyStorePass", ""); @@ -99,9 +104,4 @@ public String chooseClientAlias( Socket arg2) { return alias; } - - private PrivateKey privateKey; - private X509Certificate[] cert; - private String alias; - private static final String PREFIX = "jade_mtp_http_https_"; } diff --git a/src/jade/mtp/http/https/StrongAuthentication.java b/src/jade/mtp/http/https/StrongAuthentication.java index e95684a..1aecf04 100644 --- a/src/jade/mtp/http/https/StrongAuthentication.java +++ b/src/jade/mtp/http/https/StrongAuthentication.java @@ -54,6 +54,8 @@ Implementation Copyright (C) 2000, Laboratoire d'Intelligence */ public class StrongAuthentication implements HTTPSTrustManager { + private X509TrustManager _tm; + public X509Certificate[] getAcceptedIssuers() { return _tm.getAcceptedIssuers(); } @@ -79,6 +81,4 @@ public void init(Profile profile) throws Exception { tmf.init(ks); _tm = (X509TrustManager) tmf.getTrustManagers()[0]; } - - private X509TrustManager _tm; } diff --git a/src/jade/mtp/iiop/MessageTransportProtocol.java b/src/jade/mtp/iiop/MessageTransportProtocol.java index 80e64f4..ea445f8 100644 --- a/src/jade/mtp/iiop/MessageTransportProtocol.java +++ b/src/jade/mtp/iiop/MessageTransportProtocol.java @@ -60,128 +60,10 @@ public class MessageTransportProtocol implements MTP { - private static class MTSImpl extends FIPA._MTSImplBase { - - private final Dispatcher dispatcher; - - public MTSImpl(Dispatcher disp) { - dispatcher = disp; - } - - public void message(FipaMessage aFipaMessage) { - FIPA.Envelope[] envelopes = aFipaMessage.messageEnvelopes; - byte[] payload = aFipaMessage.messageBody; - - Envelope env = new Envelope(); - - // Read all the envelopes sequentially, so that later slots - // overwrite earlier ones. - for (FIPA.Envelope IDLenv : envelopes) { - // Read in the 'to' slot - if (IDLenv.to.length > 0) - env.clearAllTo(); - for (int i = 0; i < IDLenv.to.length; i++) { - AID id = unmarshalAID(IDLenv.to[i]); - env.addTo(id); - } - - // Read in the 'from' slot - if (IDLenv.from.length > 0) { - AID id = unmarshalAID(IDLenv.from[0]); - env.setFrom(id); - } - - // Read in the 'intended-receiver' slot - if (IDLenv.intendedReceiver.length > 0) - env.clearAllIntendedReceiver(); - for (int i = 0; i < IDLenv.intendedReceiver.length; i++) { - AID id = unmarshalAID(IDLenv.intendedReceiver[i]); - env.addIntendedReceiver(id); - } - - // Read in the 'encrypted' slot - //if(IDLenv.encrypted.length > 0) - // env.clearAllEncrypted(); - //for(int i = 0; i < IDLenv.encrypted.length; i++) { - // String word = IDLenv.encrypted[i]; - // env.addEncrypted(word); - //} - - // Read in the other slots - if (IDLenv.comments.length() > 0) - env.setComments(IDLenv.comments); - if (IDLenv.aclRepresentation.length() > 0) - env.setAclRepresentation(IDLenv.aclRepresentation); - if (IDLenv.payloadLength > 0) - env.setPayloadLength((long) IDLenv.payloadLength); - if (IDLenv.payloadEncoding.length() > 0) - env.setPayloadEncoding(IDLenv.payloadEncoding); - if (IDLenv.date.length > 0) { - Date d = unmarshalDateTime(IDLenv.date[0]); - env.setDate(d); - } - - // Read in the 'received' stamp - if (IDLenv.received.length > 0) - env.addStamp(unmarshalReceivedObj(IDLenv.received[0])); - - // Read in the 'user-defined properties' slot - if (IDLenv.userDefinedProperties.length > 0) - env.clearAllProperties(); - for (int i = 0; i < IDLenv.userDefinedProperties.length; i++) { - env.addProperties(unmarshalProperty(IDLenv.userDefinedProperties[i])); - } - } - - //String tmp = "\n\n"+(new java.util.Date()).toString()+" RECEIVED IIOP MESSAGE"+ "\n" + env.toString() + "\n" + new String(payload); - //System.out.println(tmp); - - - //MessageTransportProtocol.log(tmp); //Write in a log file for iiop incoming message - - // Dispatch the message - dispatcher.dispatchMessage(env, payload); - - } - - - private AID unmarshalAID(AgentID id) { - AID result = new AID(); - result.setName(id.name); - for (int i = 0; i < id.addresses.length; i++) - result.addAddresses(id.addresses[i]); - for (int i = 0; i < id.resolvers.length; i++) - result.addResolvers(unmarshalAID(id.resolvers[i])); - return result; - } - - private Date unmarshalDateTime(FIPA.DateTime d) { - return new Date(); - } - - private Property unmarshalProperty(FIPA.Property p) { - return new Property(p.keyword, p.value.extract_Value()); - } - - private ReceivedObject unmarshalReceivedObj(FIPA.ReceivedObject ro) { - ReceivedObject result = new ReceivedObject(); - result.setBy(ro.by); - result.setFrom(ro.from); - result.setDate(unmarshalDateTime(ro.date)); - result.setId(ro.id); - result.setVia(ro.via); - return result; - } - - } // End of MTSImpl class - - private static final String[] PROTOCOLS = new String[]{"IOR", "corbaloc", "corbaname"}; - + private static PrintWriter logFile; private final ORB myORB; private MTSImpl server; - private static PrintWriter logFile; - public MessageTransportProtocol() { myORB = ORB.init(new String[0], null); @@ -420,6 +302,121 @@ private FIPA.ReceivedObject marshalReceivedObj(ReceivedObject ro) { return result; } + private static class MTSImpl extends FIPA._MTSImplBase { + + private final Dispatcher dispatcher; + + public MTSImpl(Dispatcher disp) { + dispatcher = disp; + } + + public void message(FipaMessage aFipaMessage) { + FIPA.Envelope[] envelopes = aFipaMessage.messageEnvelopes; + byte[] payload = aFipaMessage.messageBody; + + Envelope env = new Envelope(); + + // Read all the envelopes sequentially, so that later slots + // overwrite earlier ones. + for (FIPA.Envelope IDLenv : envelopes) { + // Read in the 'to' slot + if (IDLenv.to.length > 0) + env.clearAllTo(); + for (int i = 0; i < IDLenv.to.length; i++) { + AID id = unmarshalAID(IDLenv.to[i]); + env.addTo(id); + } + + // Read in the 'from' slot + if (IDLenv.from.length > 0) { + AID id = unmarshalAID(IDLenv.from[0]); + env.setFrom(id); + } + + // Read in the 'intended-receiver' slot + if (IDLenv.intendedReceiver.length > 0) + env.clearAllIntendedReceiver(); + for (int i = 0; i < IDLenv.intendedReceiver.length; i++) { + AID id = unmarshalAID(IDLenv.intendedReceiver[i]); + env.addIntendedReceiver(id); + } + + // Read in the 'encrypted' slot + //if(IDLenv.encrypted.length > 0) + // env.clearAllEncrypted(); + //for(int i = 0; i < IDLenv.encrypted.length; i++) { + // String word = IDLenv.encrypted[i]; + // env.addEncrypted(word); + //} + + // Read in the other slots + if (IDLenv.comments.length() > 0) + env.setComments(IDLenv.comments); + if (IDLenv.aclRepresentation.length() > 0) + env.setAclRepresentation(IDLenv.aclRepresentation); + if (IDLenv.payloadLength > 0) + env.setPayloadLength((long) IDLenv.payloadLength); + if (IDLenv.payloadEncoding.length() > 0) + env.setPayloadEncoding(IDLenv.payloadEncoding); + if (IDLenv.date.length > 0) { + Date d = unmarshalDateTime(IDLenv.date[0]); + env.setDate(d); + } + + // Read in the 'received' stamp + if (IDLenv.received.length > 0) + env.addStamp(unmarshalReceivedObj(IDLenv.received[0])); + + // Read in the 'user-defined properties' slot + if (IDLenv.userDefinedProperties.length > 0) + env.clearAllProperties(); + for (int i = 0; i < IDLenv.userDefinedProperties.length; i++) { + env.addProperties(unmarshalProperty(IDLenv.userDefinedProperties[i])); + } + } + + //String tmp = "\n\n"+(new java.util.Date()).toString()+" RECEIVED IIOP MESSAGE"+ "\n" + env.toString() + "\n" + new String(payload); + //System.out.println(tmp); + + + //MessageTransportProtocol.log(tmp); //Write in a log file for iiop incoming message + + // Dispatch the message + dispatcher.dispatchMessage(env, payload); + + } + + + private AID unmarshalAID(AgentID id) { + AID result = new AID(); + result.setName(id.name); + for (int i = 0; i < id.addresses.length; i++) + result.addAddresses(id.addresses[i]); + for (int i = 0; i < id.resolvers.length; i++) + result.addResolvers(unmarshalAID(id.resolvers[i])); + return result; + } + + private Date unmarshalDateTime(FIPA.DateTime d) { + return new Date(); + } + + private Property unmarshalProperty(FIPA.Property p) { + return new Property(p.keyword, p.value.extract_Value()); + } + + private ReceivedObject unmarshalReceivedObj(FIPA.ReceivedObject ro) { + ReceivedObject result = new ReceivedObject(); + result.setBy(ro.by); + result.setFrom(ro.from); + result.setDate(unmarshalDateTime(ro.date)); + result.setId(ro.id); + result.setVia(ro.via); + return result; + } + + } // End of MTSImpl class + //Method to write on a file the iiop message log file /*public static synchronized void log(String str) { @@ -472,20 +469,12 @@ class IIOPAddress implements TransportAddress { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; - - private static byte getASCIIByte(String ch) { - return (ch.getBytes(StandardCharsets.US_ASCII))[0]; - } - - private final ORB orb; - private String ior; private String host; private short port; private String objectKey; private String anchor; - private CDRCodec codecStrategy; public IIOPAddress(ORB anOrb, FIPA.MTS objRef) throws MTPException { @@ -504,6 +493,10 @@ else if (s.toLowerCase().startsWith("corbaname:")) throw new MTPException("Invalid string prefix"); } + private static byte getASCIIByte(String ch) { + return (ch.getBytes(StandardCharsets.US_ASCII))[0]; + } + void initFromIOR(String s) throws MTPException { parseIOR(s, FIPA_2000_TYPE_ID); anchor = ""; @@ -773,6 +766,26 @@ public FIPA.MTS getObject() { return FIPA.MTSHelper.narrow(orb.string_to_object(ior)); } + public String getProto() { + return "iiop"; + } + + public String getHost() { + return host; + } + + public String getPort() { + return Short.toString(port); + } + + public String getFile() { + return objectKey; + } + + public String getAnchor() { + return anchor; + } + private static abstract class CDRCodec { protected byte[] readBuffer; @@ -1006,26 +1019,6 @@ public void writeLongLong(long l) { } // End of LittleEndianCodec class - public String getProto() { - return "iiop"; - } - - public String getHost() { - return host; - } - - public String getPort() { - return Short.toString(port); - } - - public String getFile() { - return objectKey; - } - - public String getAnchor() { - return anchor; - } - } // End of IIOPAddress class diff --git a/src/jade/proto/AchieveREInitiator.java b/src/jade/proto/AchieveREInitiator.java index 3ed4f89..16b0982 100644 --- a/src/jade/proto/AchieveREInitiator.java +++ b/src/jade/proto/AchieveREInitiator.java @@ -155,98 +155,95 @@ public AchieveREInitiator(Agent a, ACLMessage msg) { * AchieveREInitiator * deprecated public AchieveREInitiator(Agent a, ACLMessage msg, HashMap> msgList) { - super(a, msg, msgList); - - // Register the FSM transitions specific to the Achieve-RE protocol - registerTransition(CHECK_IN_SEQ, HANDLE_AGREE, ACLMessage.AGREE); - registerTransition(CHECK_IN_SEQ, HANDLE_INFORM, ACLMessage.INFORM); - registerTransition(CHECK_IN_SEQ, HANDLE_REFUSE, ACLMessage.REFUSE); - registerDefaultTransition(HANDLE_AGREE, CHECK_SESSIONS); - registerDefaultTransition(HANDLE_INFORM, CHECK_SESSIONS); - registerDefaultTransition(HANDLE_REFUSE, CHECK_SESSIONS); - registerTransition(CHECK_SESSIONS, HANDLE_ALL_RESPONSES, ALL_RESPONSES_RECEIVED); - registerTransition(CHECK_SESSIONS, HANDLE_ALL_RESULT_NOTIFICATIONS, ALL_RESULT_NOTIFICATIONS_RECEIVED); - registerDefaultTransition(HANDLE_ALL_RESPONSES, CHECK_AGAIN); - registerTransition(CHECK_AGAIN, HANDLE_ALL_RESULT_NOTIFICATIONS, 0); - registerDefaultTransition(CHECK_AGAIN, RECEIVE_REPLY, toBeReset); - - // Create and register the states specific to the Achieve-RE protocol - Behaviour b; - // HANDLE_AGREE - b = new OneShotBehaviour(myAgent) { - @Serial - private static final long serialVersionUID = 3487495895818003L; - - public void action() { - handleAgree(getMapMessages().get(REPLY_K)); - } - }; - b.setMapMessagesList(getMapMessagesList()); - b.setMapMessages(getMapMessages()); - registerState(b, HANDLE_AGREE); - - // HANDLE_REFUSE - b = new OneShotBehaviour(myAgent) { - @Serial - private static final long serialVersionUID = 3487495895818004L; + super(a, msg, msgList); + + // Register the FSM transitions specific to the Achieve-RE protocol + registerTransition(CHECK_IN_SEQ, HANDLE_AGREE, ACLMessage.AGREE); + registerTransition(CHECK_IN_SEQ, HANDLE_INFORM, ACLMessage.INFORM); + registerTransition(CHECK_IN_SEQ, HANDLE_REFUSE, ACLMessage.REFUSE); + registerDefaultTransition(HANDLE_AGREE, CHECK_SESSIONS); + registerDefaultTransition(HANDLE_INFORM, CHECK_SESSIONS); + registerDefaultTransition(HANDLE_REFUSE, CHECK_SESSIONS); + registerTransition(CHECK_SESSIONS, HANDLE_ALL_RESPONSES, ALL_RESPONSES_RECEIVED); + registerTransition(CHECK_SESSIONS, HANDLE_ALL_RESULT_NOTIFICATIONS, ALL_RESULT_NOTIFICATIONS_RECEIVED); + registerDefaultTransition(HANDLE_ALL_RESPONSES, CHECK_AGAIN); + registerTransition(CHECK_AGAIN, HANDLE_ALL_RESULT_NOTIFICATIONS, 0); + registerDefaultTransition(CHECK_AGAIN, RECEIVE_REPLY, toBeReset); + + // Create and register the states specific to the Achieve-RE protocol + Behaviour b; + // HANDLE_AGREE + b = new OneShotBehaviour(myAgent) { + @Serial private static final long serialVersionUID = 3487495895818003L; + + public void action() { + handleAgree(getMapMessages().get(REPLY_K)); + } + }; + b.setMapMessagesList(getMapMessagesList()); + b.setMapMessages(getMapMessages()); + registerState(b, HANDLE_AGREE); - public void action() { - handleRefuse(getMapMessages().get(REPLY_K)); - } - }; - b.setMapMessagesList(getMapMessagesList()); - b.setMapMessages(getMapMessages()); - registerState(b, HANDLE_REFUSE); + // HANDLE_REFUSE + b = new OneShotBehaviour(myAgent) { + @Serial private static final long serialVersionUID = 3487495895818004L; - // HANDLE_INFORM - b = new OneShotBehaviour(myAgent) { - @Serial - private static final long serialVersionUID = 3487495895818006L; + public void action() { + handleRefuse(getMapMessages().get(REPLY_K)); + } + }; + b.setMapMessagesList(getMapMessagesList()); + b.setMapMessages(getMapMessages()); + registerState(b, HANDLE_REFUSE); - public void action() { - handleInform(getMapMessages().get(REPLY_K)); - } - }; - b.setMapMessagesList(getMapMessagesList()); - b.setMapMessages(getMapMessages()); - registerState(b, HANDLE_INFORM); + // HANDLE_INFORM + b = new OneShotBehaviour(myAgent) { + @Serial private static final long serialVersionUID = 3487495895818006L; - // HANDLE_ALL_RESPONSES - b = new OneShotBehaviour(myAgent) { + public void action() { + handleInform(getMapMessages().get(REPLY_K)); + } + }; + b.setMapMessagesList(getMapMessagesList()); + b.setMapMessages(getMapMessages()); + registerState(b, HANDLE_INFORM); - public void action() { - handleAllResponses(getMapMessagesList().get(ALL_RESPONSES_KEY)); - } - }; - b.setMapMessagesList(getMapMessagesList()); - b.setMapMessages(getMapMessages()); - registerState(b, HANDLE_ALL_RESPONSES); + // HANDLE_ALL_RESPONSES + b = new OneShotBehaviour(myAgent) { - // HANDLE_ALL_RESULT_NOTIFICATIONS - b = new OneShotBehaviour(myAgent) { + public void action() { + handleAllResponses(getMapMessagesList().get(ALL_RESPONSES_KEY)); + } + }; + b.setMapMessagesList(getMapMessagesList()); + b.setMapMessages(getMapMessages()); + registerState(b, HANDLE_ALL_RESPONSES); - public void action() { - handleAllResultNotifications(getMapMessagesList().get(ALL_RESULT_NOTIFICATIONS_KEY)); - } - }; - b.setMapMessagesList(getMapMessagesList()); - b.setMapMessages(getMapMessages()); - registerLastState(b, HANDLE_ALL_RESULT_NOTIFICATIONS); + // HANDLE_ALL_RESULT_NOTIFICATIONS + b = new OneShotBehaviour(myAgent) { - // CHECK_AGAIN - b = new OneShotBehaviour(myAgent) { - public void action() { - } + public void action() { + handleAllResultNotifications(getMapMessagesList().get(ALL_RESULT_NOTIFICATIONS_KEY)); + } + }; + b.setMapMessagesList(getMapMessagesList()); + b.setMapMessages(getMapMessages()); + registerLastState(b, HANDLE_ALL_RESULT_NOTIFICATIONS); + + // CHECK_AGAIN + b = new OneShotBehaviour(myAgent) { + public void action() { + } - public int onEnd() { - return mapSessions.size(); - } - }; - b.setMapMessagesList(getMapMessagesList()); - b.setMapMessages(getMapMessages()); - registerState(b, CHECK_AGAIN); + public int onEnd() { + return mapSessions.size(); } -*/ + }; + b.setMapMessagesList(getMapMessagesList()); + b.setMapMessages(getMapMessages()); + registerState(b, CHECK_AGAIN); + } + */ //#APIDOC_EXCLUDE_BEGIN /** diff --git a/src/jade/proto/AchieveREResponder.java b/src/jade/proto/AchieveREResponder.java index 0fd387f..affa15c 100644 --- a/src/jade/proto/AchieveREResponder.java +++ b/src/jade/proto/AchieveREResponder.java @@ -58,6 +58,12 @@ **/ public class AchieveREResponder extends FSMBehaviour implements FIPANames.InteractionProtocol { + // FSM states names + private static final String RECEIVE_REQUEST = "Receive-request"; + private static final String HANDLE_REQUEST = "Handle-request"; + private static final String SEND_RESPONSE = "Send-response"; + private static final String PREPARE_RESULT_NOTIFICATION = "Prepare-result-notification"; + private static final String SEND_RESULT_NOTIFICATION = "Send-result-notification"; /** * key to retrieve from the HashMap of the behaviour the ACLMessage * object sent by the initiator. @@ -73,129 +79,9 @@ public class AchieveREResponder extends FSMBehaviour implements FIPANames.Intera * object sent as a result notification to the initiator. **/ public final String RESULT_NOTIFICATION_KEY = "__result-notification" + hashCode(); - - // FSM states names - private static final String RECEIVE_REQUEST = "Receive-request"; - private static final String HANDLE_REQUEST = "Handle-request"; - private static final String SEND_RESPONSE = "Send-response"; - private static final String PREPARE_RESULT_NOTIFICATION = "Prepare-result-notification"; - private static final String SEND_RESULT_NOTIFICATION = "Send-result-notification"; - - // The MsgReceiver behaviour used to receive request messages MsgReceiver rec = null; - /** - * This static method can be used - * to set the proper message Template (based on the interaction protocol - * and the performative) - * into the constructor of this behaviour. - * - * @see FIPANames.InteractionProtocol - **/ - public static MessageTemplate createMessageTemplate(String iprotocol) { - - if (CaseInsensitiveString.equalsIgnoreCase(FIPA_REQUEST, iprotocol)) - return MessageTemplate.and(MessageTemplate.MatchProtocol(FIPA_REQUEST), MessageTemplate.MatchPerformative(ACLMessage.REQUEST)); - else if (CaseInsensitiveString.equalsIgnoreCase(FIPA_QUERY, iprotocol)) - return MessageTemplate.and(MessageTemplate.MatchProtocol(FIPA_QUERY), MessageTemplate.or(MessageTemplate.MatchPerformative(ACLMessage.QUERY_IF), MessageTemplate.MatchPerformative(ACLMessage.QUERY_REF))); - else - return MessageTemplate.MatchProtocol(iprotocol); - } - - - // Inner classes for the FSM states - - private static class HandleRequest extends OneShotBehaviour { - - public HandleRequest(Agent a) { - super(a); - } - - public void action() { - var ds = getMapMessages(); - AchieveREResponder fsm = (AchieveREResponder) getParent(); - ACLMessage request = ds.get(fsm.REQUEST_KEY); - - ACLMessage response; - try { - response = fsm.handleRequest(request); - } catch (NotUnderstoodException | RefuseException nue) { - response = nue.getACLMessage(); - } - ds.put(fsm.RESPONSE_KEY, response); - } - } // End of HandleRequest class - - - private static class SendResponse extends ReplySender { - - public SendResponse(Agent a, String replyKey, String msgKey, HashMap> mapMessagesList, HashMap mapMessages) { - super(a, replyKey, msgKey, mapMessagesList, mapMessages); - } - - // For persistence service - private SendResponse() { - } - - public int onEnd() { - int ret = super.onEnd(); - if (ret != ACLMessage.AGREE && ret != ReplySender.NO_REPLY_SENT) { - AchieveREResponder fsm = (AchieveREResponder) getParent(); - fsm.reset(); - } - return ret; - } - - } // End of SendResponse class - - - private static class PrepareResult extends OneShotBehaviour { - - public PrepareResult(Agent a) { - super(a); - } - - // For persistence service - private PrepareResult() { - } - - public void action() { - var ds = getMapMessages(); - AchieveREResponder fsm = (AchieveREResponder) getParent(); - ACLMessage request = ds.get(fsm.REQUEST_KEY); - ACLMessage response = ds.get(fsm.RESPONSE_KEY); - ACLMessage resNotification; - try { - resNotification = fsm.prepareResultNotification(request, response); - } catch (FailureException fe) { - resNotification = fe.getACLMessage(); - } - ds.put(fsm.RESULT_NOTIFICATION_KEY, resNotification); - } - - } // End of PrepareResult class - - - private static class SendResult extends ReplySender { - - public SendResult(Agent a, String replyKey, String msgKey, HashMap> mapMessagesList, HashMap mapMessages) { - super(a, replyKey, msgKey, mapMessagesList, mapMessages); - } - - // For persistence service - private SendResult() { - } - - public int onEnd() { - AchieveREResponder fsm = (AchieveREResponder) getParent(); - fsm.reset(); - return super.onEnd(); - } - - } // End of SendResult class - - /** * Constructor of the behaviour that creates a new empty HashMap * @@ -205,58 +91,9 @@ public AchieveREResponder(Agent a, MessageTemplate mt) { this(a, mt, new HashMap<>(), new HashMap<>()); } - /** - * Constructor. - * - * @param a is the reference to the Agent object - * @param mt is the MessageTemplate that must be used to match - * the initiator message. Take care that - * if mt is null every message is consumed by this protocol. - * @param mapMessagesList the HashMap of messages list for this protocol - * deprecated use the constructor with 2 hashmap - - public AchieveREResponder(Agent a, MessageTemplate mt, HashMap> mapMessagesList) { - super(a); - - setMapMessagesList(mapMessagesList); - - // Register the FSM transitions - registerDefaultTransition(RECEIVE_REQUEST, HANDLE_REQUEST); - registerDefaultTransition(HANDLE_REQUEST, SEND_RESPONSE); - registerTransition(SEND_RESPONSE, PREPARE_RESULT_NOTIFICATION, ACLMessage.AGREE); - registerTransition(SEND_RESPONSE, PREPARE_RESULT_NOTIFICATION, ReplySender.NO_REPLY_SENT); - registerDefaultTransition(SEND_RESPONSE, RECEIVE_REQUEST); - registerDefaultTransition(PREPARE_RESULT_NOTIFICATION, SEND_RESULT_NOTIFICATION); - registerDefaultTransition(SEND_RESULT_NOTIFICATION, RECEIVE_REQUEST); - - // Create and register the states that make up the FSM - Behaviour b; - - // RECEIVE_REQUEST - rec = new MsgReceiver(myAgent, mt, -1, getMapMessagesList(), getMapMessages(), REQUEST_KEY); - registerFirstState(rec, RECEIVE_REQUEST); - // HANDLE_REQUEST - b = new HandleRequest(myAgent); - b.setMapMessagesList(getMapMessagesList()); - registerState(b, HANDLE_REQUEST); - - // SEND_RESPONSE - b = new SendResponse(myAgent, RESPONSE_KEY, REQUEST_KEY); - b.setMapMessagesList(getMapMessagesList()); - registerState(b, SEND_RESPONSE); - - // PREPARE_RESULT_NOTIFICATION - b = new PrepareResult(myAgent); - b.setMapMessagesList(getMapMessagesList()); - registerState(b, PREPARE_RESULT_NOTIFICATION); + // Inner classes for the FSM states - // SEND_RESULT_NOTIFICATION - b = new SendResult(myAgent, RESULT_NOTIFICATION_KEY, REQUEST_KEY); - b.setMapMessagesList(getMapMessagesList()); - registerState(b, SEND_RESULT_NOTIFICATION); - } -*/ /** * Constructor. * @@ -313,10 +150,28 @@ public AchieveREResponder(Agent a, MessageTemplate mt, HashMap> mapMessagesList) { + super(a); + + setMapMessagesList(mapMessagesList); + + // Register the FSM transitions + registerDefaultTransition(RECEIVE_REQUEST, HANDLE_REQUEST); + registerDefaultTransition(HANDLE_REQUEST, SEND_RESPONSE); + registerTransition(SEND_RESPONSE, PREPARE_RESULT_NOTIFICATION, ACLMessage.AGREE); + registerTransition(SEND_RESPONSE, PREPARE_RESULT_NOTIFICATION, ReplySender.NO_REPLY_SENT); + registerDefaultTransition(SEND_RESPONSE, RECEIVE_REQUEST); + registerDefaultTransition(PREPARE_RESULT_NOTIFICATION, SEND_RESULT_NOTIFICATION); + registerDefaultTransition(SEND_RESULT_NOTIFICATION, RECEIVE_REQUEST); + + // Create and register the states that make up the FSM + Behaviour b; + + // RECEIVE_REQUEST + rec = new MsgReceiver(myAgent, mt, -1, getMapMessagesList(), getMapMessages(), REQUEST_KEY); + registerFirstState(rec, RECEIVE_REQUEST); + + // HANDLE_REQUEST + b = new HandleRequest(myAgent); + b.setMapMessagesList(getMapMessagesList()); + registerState(b, HANDLE_REQUEST); + + // SEND_RESPONSE + b = new SendResponse(myAgent, RESPONSE_KEY, REQUEST_KEY); + b.setMapMessagesList(getMapMessagesList()); + registerState(b, SEND_RESPONSE); + + // PREPARE_RESULT_NOTIFICATION + b = new PrepareResult(myAgent); + b.setMapMessagesList(getMapMessagesList()); + registerState(b, PREPARE_RESULT_NOTIFICATION); + + // SEND_RESULT_NOTIFICATION + b = new SendResult(myAgent, RESULT_NOTIFICATION_KEY, REQUEST_KEY); + b.setMapMessagesList(getMapMessagesList()); + registerState(b, SEND_RESULT_NOTIFICATION); + } + */ /** * This method is called when the protocol initiation message (matching the @@ -381,7 +288,6 @@ protected ACLMessage prepareResultNotification(ACLMessage request, ACLMessage re return null; } - /** * This method allows to register a user defined Behaviour * in the HANDLE_REQUEST state. @@ -426,6 +332,92 @@ public void registerPrepareResultNotification(Behaviour b) { b.setMapMessages(getMapMessages()); } + private static class HandleRequest extends OneShotBehaviour { + + public HandleRequest(Agent a) { + super(a); + } + + public void action() { + var ds = getMapMessages(); + AchieveREResponder fsm = (AchieveREResponder) getParent(); + ACLMessage request = ds.get(fsm.REQUEST_KEY); + + ACLMessage response; + try { + response = fsm.handleRequest(request); + } catch (NotUnderstoodException | RefuseException nue) { + response = nue.getACLMessage(); + } + ds.put(fsm.RESPONSE_KEY, response); + } + } // End of HandleRequest class + + private static class SendResponse extends ReplySender { + + public SendResponse(Agent a, String replyKey, String msgKey, HashMap> mapMessagesList, HashMap mapMessages) { + super(a, replyKey, msgKey, mapMessagesList, mapMessages); + } + + // For persistence service + private SendResponse() { + } + + public int onEnd() { + int ret = super.onEnd(); + if (ret != ACLMessage.AGREE && ret != ReplySender.NO_REPLY_SENT) { + AchieveREResponder fsm = (AchieveREResponder) getParent(); + fsm.reset(); + } + return ret; + } + + } // End of SendResponse class + + private static class PrepareResult extends OneShotBehaviour { + + public PrepareResult(Agent a) { + super(a); + } + + // For persistence service + private PrepareResult() { + } + + public void action() { + var ds = getMapMessages(); + AchieveREResponder fsm = (AchieveREResponder) getParent(); + ACLMessage request = ds.get(fsm.REQUEST_KEY); + ACLMessage response = ds.get(fsm.RESPONSE_KEY); + ACLMessage resNotification; + try { + resNotification = fsm.prepareResultNotification(request, response); + } catch (FailureException fe) { + resNotification = fe.getACLMessage(); + } + ds.put(fsm.RESULT_NOTIFICATION_KEY, resNotification); + } + + } // End of PrepareResult class + + private static class SendResult extends ReplySender { + + public SendResult(Agent a, String replyKey, String msgKey, HashMap> mapMessagesList, HashMap mapMessages) { + super(a, replyKey, msgKey, mapMessagesList, mapMessages); + } + + // For persistence service + private SendResult() { + } + + public int onEnd() { + AchieveREResponder fsm = (AchieveREResponder) getParent(); + fsm.reset(); + return super.onEnd(); + } + + } // End of SendResult class + } diff --git a/src/jade/proto/ContractNetInitiator.java b/src/jade/proto/ContractNetInitiator.java index 6e4cf82..eb2ab5e 100644 --- a/src/jade/proto/ContractNetInitiator.java +++ b/src/jade/proto/ContractNetInitiator.java @@ -130,6 +130,16 @@ public class ContractNetInitiator extends Initiator { // Private data store keys (can't be static since if we register another instance of this class as state of the FSM // using the same data store the new values overrides the old one. + // FSM states names + private static final String HANDLE_PROPOSE = "Handle-propose"; + private static final String HANDLE_REFUSE = "Handle-refuse"; + private static final String HANDLE_INFORM = "Handle-inform"; + private static final String HANDLE_ALL_RESPONSES = "Handle-all-responses"; + private static final String HANDLE_ALL_RESULT_NOTIFICATIONS = "Handle-all-result-notifications"; + // States exit values + private static final int ALL_RESPONSES_RECEIVED = 1; + private static final int ALL_RESULT_NOTIFICATIONS_RECEIVED = 2; + private static final int MORE_ACCEPTANCES = 3; /** * key to retrieve from the HashMap of the behaviour the ACLMessage * object passed in the constructor of the class. @@ -161,19 +171,6 @@ public class ContractNetInitiator extends Initiator { * ACLMessage objects that have been received as result notifications. **/ public final String ALL_RESULT_NOTIFICATIONS_KEY = "__all-result-notifications" + hashCode(); - - // FSM states names - private static final String HANDLE_PROPOSE = "Handle-propose"; - private static final String HANDLE_REFUSE = "Handle-refuse"; - private static final String HANDLE_INFORM = "Handle-inform"; - private static final String HANDLE_ALL_RESPONSES = "Handle-all-responses"; - private static final String HANDLE_ALL_RESULT_NOTIFICATIONS = "Handle-all-result-notifications"; - - // States exit values - private static final int ALL_RESPONSES_RECEIVED = 1; - private static final int ALL_RESULT_NOTIFICATIONS_RECEIVED = 2; - private static final int MORE_ACCEPTANCES = 3; - // When step == 1 we deal with CFP and responses // When step == 2 we deal with ACCEPT/REJECT_PROPOSAL and result notifications private int step = 1; @@ -182,15 +179,7 @@ public class ContractNetInitiator extends Initiator { // Indicates that a new tranche of acceptances must be sent after all result notifications // have been received private boolean moreAcceptancesToSend = false; - - /** - * Constructor for the class that creates a new empty HashMap - * - * @see #ContractNetInitiator(Agent, ACLMessage, HashMap) - **/ - public ContractNetInitiator(Agent a, ACLMessage cfp) { - this(a, cfp, new HashMap<>(), new HashMap<>()); - } + private String[] toBeReset = null; /** * Constructs a ContractNetInitiator behaviour @@ -206,92 +195,100 @@ public ContractNetInitiator(Agent a, ACLMessage cfp) { * deprecated public ContractNetInitiator(Agent a, ACLMessage cfp, HashMap> mapMessagesList) { - super(a, cfp, mapMessagesList); - // Register the FSM transitions specific to the ContractNet protocol - registerTransition(CHECK_IN_SEQ, HANDLE_PROPOSE, ACLMessage.PROPOSE); - registerTransition(CHECK_IN_SEQ, HANDLE_REFUSE, ACLMessage.REFUSE); - registerTransition(CHECK_IN_SEQ, HANDLE_INFORM, ACLMessage.INFORM); - registerDefaultTransition(HANDLE_PROPOSE, CHECK_SESSIONS); - registerDefaultTransition(HANDLE_REFUSE, CHECK_SESSIONS); - registerDefaultTransition(HANDLE_INFORM, CHECK_SESSIONS); - registerTransition(CHECK_SESSIONS, HANDLE_ALL_RESPONSES, ALL_RESPONSES_RECEIVED); - registerTransition(CHECK_SESSIONS, HANDLE_ALL_RESULT_NOTIFICATIONS, ALL_RESULT_NOTIFICATIONS_RECEIVED); - registerDefaultTransition(HANDLE_ALL_RESPONSES, SEND_INITIATIONS, getToBeReset()); - registerTransition(HANDLE_ALL_RESULT_NOTIFICATIONS, SEND_INITIATIONS, MORE_ACCEPTANCES, getToBeReset()); - registerDefaultTransition(HANDLE_ALL_RESULT_NOTIFICATIONS, DUMMY_FINAL); - - // Create and register the states specific to the ContractNet protocol - Behaviour b; - // HANDLE_PROPOSE - b = new OneShotBehaviour(myAgent) { - @Serial - private static final long serialVersionUID = 3487495895819003L; - - public void action() { - var acceptances = getMapMessagesList().get(ALL_ACCEPTANCES_KEY); - ACLMessage propose = getMapMessages().get(REPLY_K); - handlePropose(propose, acceptances); - } - }; - b.setMapMessagesList(getMapMessagesList()); - b.setMapMessages(getMapMessages()); - registerState(b, HANDLE_PROPOSE); + super(a, cfp, mapMessagesList); + // Register the FSM transitions specific to the ContractNet protocol + registerTransition(CHECK_IN_SEQ, HANDLE_PROPOSE, ACLMessage.PROPOSE); + registerTransition(CHECK_IN_SEQ, HANDLE_REFUSE, ACLMessage.REFUSE); + registerTransition(CHECK_IN_SEQ, HANDLE_INFORM, ACLMessage.INFORM); + registerDefaultTransition(HANDLE_PROPOSE, CHECK_SESSIONS); + registerDefaultTransition(HANDLE_REFUSE, CHECK_SESSIONS); + registerDefaultTransition(HANDLE_INFORM, CHECK_SESSIONS); + registerTransition(CHECK_SESSIONS, HANDLE_ALL_RESPONSES, ALL_RESPONSES_RECEIVED); + registerTransition(CHECK_SESSIONS, HANDLE_ALL_RESULT_NOTIFICATIONS, ALL_RESULT_NOTIFICATIONS_RECEIVED); + registerDefaultTransition(HANDLE_ALL_RESPONSES, SEND_INITIATIONS, getToBeReset()); + registerTransition(HANDLE_ALL_RESULT_NOTIFICATIONS, SEND_INITIATIONS, MORE_ACCEPTANCES, getToBeReset()); + registerDefaultTransition(HANDLE_ALL_RESULT_NOTIFICATIONS, DUMMY_FINAL); + + // Create and register the states specific to the ContractNet protocol + Behaviour b; + // HANDLE_PROPOSE + b = new OneShotBehaviour(myAgent) { + @Serial private static final long serialVersionUID = 3487495895819003L; + + public void action() { + var acceptances = getMapMessagesList().get(ALL_ACCEPTANCES_KEY); + ACLMessage propose = getMapMessages().get(REPLY_K); + handlePropose(propose, acceptances); + } + }; + b.setMapMessagesList(getMapMessagesList()); + b.setMapMessages(getMapMessages()); + registerState(b, HANDLE_PROPOSE); - // HANDLE_REFUSE - b = new OneShotBehaviour(myAgent) { - @Serial - private static final long serialVersionUID = 3487495895819004L; + // HANDLE_REFUSE + b = new OneShotBehaviour(myAgent) { + @Serial private static final long serialVersionUID = 3487495895819004L; - public void action() { - handleRefuse(getMapMessages().get(REPLY_K)); - } - }; - b.setMapMessagesList(getMapMessagesList()); - b.setMapMessages(getMapMessages()); - registerState(b, HANDLE_REFUSE); + public void action() { + handleRefuse(getMapMessages().get(REPLY_K)); + } + }; + b.setMapMessagesList(getMapMessagesList()); + b.setMapMessages(getMapMessages()); + registerState(b, HANDLE_REFUSE); - // HANDLE_INFORM - b = new OneShotBehaviour(myAgent) { - @Serial - private static final long serialVersionUID = 3487495895818006L; + // HANDLE_INFORM + b = new OneShotBehaviour(myAgent) { + @Serial private static final long serialVersionUID = 3487495895818006L; - public void action() { - handleInform(getMapMessages().get(REPLY_K)); - } - }; - b.setMapMessagesList(getMapMessagesList()); - b.setMapMessages(getMapMessages()); - registerState(b, HANDLE_INFORM); + public void action() { + handleInform(getMapMessages().get(REPLY_K)); + } + }; + b.setMapMessagesList(getMapMessagesList()); + b.setMapMessages(getMapMessages()); + registerState(b, HANDLE_INFORM); + + // HANDLE_ALL_RESPONSES + b = new OneShotBehaviour(myAgent) { + + public void action() { + var responses = getMapMessagesList().get(ALL_RESPONSES_KEY); + var acceptances = getMapMessagesList().get(ALL_ACCEPTANCES_KEY); + handleAllResponses(responses, acceptances); + } + }; + b.setMapMessagesList(getMapMessagesList()); + b.setMapMessages(getMapMessages()); + registerState(b, HANDLE_ALL_RESPONSES); - // HANDLE_ALL_RESPONSES - b = new OneShotBehaviour(myAgent) { + // HANDLE_ALL_RESULT_NOTIFICATIONS + b = new OneShotBehaviour(myAgent) { - public void action() { - var responses = getMapMessagesList().get(ALL_RESPONSES_KEY); - var acceptances = getMapMessagesList().get(ALL_ACCEPTANCES_KEY); - handleAllResponses(responses, acceptances); - } - }; - b.setMapMessagesList(getMapMessagesList()); - b.setMapMessages(getMapMessages()); - registerState(b, HANDLE_ALL_RESPONSES); + public void action() { + handleAllResultNotifications(getMapMessagesList().get(ALL_RESULT_NOTIFICATIONS_KEY)); + } - // HANDLE_ALL_RESULT_NOTIFICATIONS - b = new OneShotBehaviour(myAgent) { + public int onEnd() { + return moreAcceptancesToSend ? MORE_ACCEPTANCES : super.onEnd(); + } + }; + b.setMapMessagesList(getMapMessagesList()); + b.setMapMessages(getMapMessages()); + registerState(b, HANDLE_ALL_RESULT_NOTIFICATIONS); + } + */ + /** + * Constructor for the class that creates a new empty HashMap + * + * @see #ContractNetInitiator(Agent, ACLMessage, HashMap, HashMap) + **/ + public ContractNetInitiator(Agent a, ACLMessage cfp) { + this(a, cfp, new HashMap<>(), new HashMap<>()); + } - public void action() { - handleAllResultNotifications(getMapMessagesList().get(ALL_RESULT_NOTIFICATIONS_KEY)); - } + //#APIDOC_EXCLUDE_BEGIN - public int onEnd() { - return moreAcceptancesToSend ? MORE_ACCEPTANCES : super.onEnd(); - } - }; - b.setMapMessagesList(getMapMessagesList()); - b.setMapMessages(getMapMessages()); - registerState(b, HANDLE_ALL_RESULT_NOTIFICATIONS); - } -*/ /** * Constructs a ContractNetInitiator behaviour * @@ -393,8 +390,6 @@ public int onEnd() { registerState(b, HANDLE_ALL_RESULT_NOTIFICATIONS); } - //#APIDOC_EXCLUDE_BEGIN - /** * */ @@ -467,8 +462,6 @@ protected int checkSessions(ACLMessage reply) { return ret; } - private String[] toBeReset = null; - /** * */ @@ -788,9 +781,8 @@ class Session implements ProtocolSession, Serializable { // Session states static final int INIT = 0; static final int REPLY_RECEIVED = 1; - - private int state = INIT; private final int sessionStep; + private int state = INIT; public Session(int s) { this.sessionStep = s; diff --git a/src/jade/proto/ContractNetResponder.java b/src/jade/proto/ContractNetResponder.java index 058463b..511c71e 100644 --- a/src/jade/proto/ContractNetResponder.java +++ b/src/jade/proto/ContractNetResponder.java @@ -98,6 +98,7 @@ */ public class ContractNetResponder extends SSContractNetResponder { + public static final String RECEIVE_CFP = "Receive-Cfp"; /** * @deprecated Use REPLY_KEY */ @@ -113,8 +114,6 @@ public class ContractNetResponder extends SSContractNetResponder { */ public final String RESULT_NOTIFICATION_KEY = REPLY_KEY; - public static final String RECEIVE_CFP = "Receive-Cfp"; - /** * Constructor of the behaviour that creates a new empty HashMap * @@ -157,6 +156,23 @@ public ContractNetResponder(Agent a, MessageTemplate mt, HashMaphandleCfp() instead */ @@ -178,6 +194,9 @@ public void registerPrepareResponse(Behaviour b) { registerHandleCfp(b); } + + //#APIDOC_EXCLUDE_BEGIN + /** * @deprecated Use registerHandleAcceptProposal() instead. */ @@ -185,9 +204,6 @@ public void registerPrepareResultNotification(Behaviour b) { registerHandleAcceptProposal(b); } - - //#APIDOC_EXCLUDE_BEGIN - /** * Redefine this method to call prepareResponse() */ @@ -209,6 +225,7 @@ protected ACLMessage handleAcceptProposal(ACLMessage cfp, ACLMessage propose, AC public void registerHandleCfp(Behaviour b) { registerDSState(b, HANDLE_CFP); } + //#APIDOC_EXCLUDE_END protected void sessionTerminated() { // Once the current session is terminated reinit the @@ -218,23 +235,4 @@ protected void sessionTerminated() { // Be sure all children can be correctly re-executed resetChildren(); } - //#APIDOC_EXCLUDE_END - - - /** - * This static method can be used - * to set the proper message Template (based on the interaction protocol - * and the performative) to be passed to the constructor of this behaviour. - * - * @see FIPANames.InteractionProtocol - */ - public static MessageTemplate createMessageTemplate(String iprotocol) { - if (CaseInsensitiveString.equalsIgnoreCase(FIPANames.InteractionProtocol.FIPA_ITERATED_CONTRACT_NET, iprotocol)) { - return MessageTemplate.and(MessageTemplate.MatchProtocol(FIPANames.InteractionProtocol.FIPA_ITERATED_CONTRACT_NET), MessageTemplate.MatchPerformative(ACLMessage.CFP)); - } else if (CaseInsensitiveString.equalsIgnoreCase(FIPANames.InteractionProtocol.FIPA_CONTRACT_NET, iprotocol)) { - return MessageTemplate.and(MessageTemplate.MatchProtocol(FIPANames.InteractionProtocol.FIPA_CONTRACT_NET), MessageTemplate.MatchPerformative(ACLMessage.CFP)); - } else { - return MessageTemplate.MatchProtocol(iprotocol); - } - } } diff --git a/src/jade/proto/Initiator.java b/src/jade/proto/Initiator.java index 53148e5..e729085 100644 --- a/src/jade/proto/Initiator.java +++ b/src/jade/proto/Initiator.java @@ -46,11 +46,6 @@ * @author Giovanni Caire - TILab **/ abstract class Initiator extends FSMBehaviour { - //#APIDOC_EXCLUDE_BEGIN - protected final String INITIATION_K = "__initiation" + hashCode(); - protected final String ALL_INITIATIONS_K = "__all-initiations" + hashCode(); - protected final String REPLY_K = "__reply" + hashCode(); - // FSM states names protected static final String PREPARE_INITIATIONS = "Prepare-initiations"; protected static final String SEND_INITIATIONS = "Send-initiations"; @@ -61,7 +56,11 @@ abstract class Initiator extends FSMBehaviour { protected static final String HANDLE_OUT_OF_SEQ = "Handle-out-of-seq"; protected static final String CHECK_SESSIONS = "Check-sessions"; protected static final String DUMMY_FINAL = "Dummy-final"; - + private static int cnt = 0; + //#APIDOC_EXCLUDE_BEGIN + protected final String INITIATION_K = "__initiation" + hashCode(); + protected final String ALL_INITIATIONS_K = "__all-initiations" + hashCode(); + protected final String REPLY_K = "__reply" + hashCode(); // This maps the AID of each responder to a Session object // holding the status of the protocol as far as that responder // is concerned. Sessions are protocol-specific @@ -70,17 +69,8 @@ abstract class Initiator extends FSMBehaviour { protected MsgReceiver replyReceiver; // The MessageTemplate used by the replyReceiver protected MessageTemplate replyTemplate = null; - private ACLMessage initiation; - /** - * Constructs an Initiator behaviour - * see #AchieveREInitiator(Agent, ACLMessage, HashMap) - **/ - protected Initiator(Agent a, ACLMessage initiation) { - this(a, initiation, new HashMap<>(), new HashMap<>()); - } - /** * Constructs an Initiator behaviour * @@ -91,156 +81,156 @@ protected Initiator(Agent a, ACLMessage initiation) { * deprecated protected Initiator(Agent a, ACLMessage initiation, HashMap> mapMessagesList) { - super(a); - - setMapMessagesList(mapMessagesList); - this.initiation = initiation; - - // Register the FSM transitions - registerDefaultTransition(PREPARE_INITIATIONS, SEND_INITIATIONS); - registerTransition(SEND_INITIATIONS, DUMMY_FINAL, 0); // Exit the protocol if no initiation message is sent - registerDefaultTransition(SEND_INITIATIONS, RECEIVE_REPLY); - registerTransition(RECEIVE_REPLY, CHECK_SESSIONS, MsgReceiver.TIMEOUT_EXPIRED); - registerTransition(RECEIVE_REPLY, CHECK_SESSIONS, MsgReceiver.INTERRUPTED); - registerDefaultTransition(RECEIVE_REPLY, CHECK_IN_SEQ); - registerTransition(CHECK_IN_SEQ, HANDLE_NOT_UNDERSTOOD, ACLMessage.NOT_UNDERSTOOD); - registerTransition(CHECK_IN_SEQ, HANDLE_FAILURE, ACLMessage.FAILURE); - registerDefaultTransition(CHECK_IN_SEQ, HANDLE_OUT_OF_SEQ); - registerDefaultTransition(HANDLE_NOT_UNDERSTOOD, CHECK_SESSIONS); - registerDefaultTransition(HANDLE_FAILURE, CHECK_SESSIONS); - registerDefaultTransition(HANDLE_OUT_OF_SEQ, RECEIVE_REPLY); - registerDefaultTransition(CHECK_SESSIONS, RECEIVE_REPLY, getToBeReset()); - - // Create and register the states that make up the FSM - Behaviour b; - // PREPARE_INITIATIONS - b = new OneShotBehaviour(myAgent) { - @Serial - private static final long serialVersionUID = 3487495895818000L; - - public void action() { - var mapMessages = getMapMessagesList(); - var allInitiations = mapMessages.get(ALL_INITIATIONS_K); - if (allInitiations == null || allInitiations.size() == 0) { - allInitiations = prepareInitiations(getMapMessages().get(INITIATION_K)); - mapMessages.put(ALL_INITIATIONS_K, allInitiations); - } - } - }; - b.setMapMessagesList(getMapMessagesList()); - registerFirstState(b, PREPARE_INITIATIONS); - - // SEND_INITIATIONS - b = new OneShotBehaviour(myAgent) { - @Serial - private static final long serialVersionUID = 3487495895818001L; - - public void action() { - var allInitiations = getMapMessagesList().get(ALL_INITIATIONS_K); - if (allInitiations != null) { - sendInitiations(allInitiations); - } - } - - public int onEnd() { - return mapSessions.size(); - } - }; - b.setMapMessagesList(getMapMessagesList()); - registerState(b, SEND_INITIATIONS); - - // RECEIVE_REPLY - //TODO: THE BUG IS HERE !!!!! 2022-02-28 - replyReceiver = new MsgReceiver(myAgent, null, MsgReceiver.INFINITE, getMapMessagesList(), REPLY_K); - registerState(replyReceiver, RECEIVE_REPLY); - - // CHECK_IN_SEQ - b = new OneShotBehaviour(myAgent) { - int ret; - @Serial - private static final long serialVersionUID = 3487495895818002L; - - public void action() { - ACLMessage reply = getMapMessages().get(REPLY_K); - if (checkInSequence(reply)) { - ret = reply.getPerformative(); - } else { - ret = -1; - } - } - - public int onEnd() { - return ret; - } - }; - b.setMapMessagesList(getMapMessagesList()); - registerState(b, CHECK_IN_SEQ); - - // HANDLE_NOT_UNDERSTOOD - b = new OneShotBehaviour(myAgent) { - @Serial - private static final long serialVersionUID = 3487495895818005L; - - public void action() { - handleNotUnderstood(getMapMessages().get(REPLY_K)); - } - }; - b.setMapMessagesList(getMapMessagesList()); - registerState(b, HANDLE_NOT_UNDERSTOOD); - - // HANDLE_FAILURE - b = new OneShotBehaviour(myAgent) { - @Serial - private static final long serialVersionUID = 3487495895818007L; - - public void action() { - handleFailure(getMapMessages().get(REPLY_K)); - } - }; - b.setMapMessagesList(getMapMessagesList()); - registerState(b, HANDLE_FAILURE); - - // HANDLE_OUT_OF_SEQ - b = new OneShotBehaviour(myAgent) { - @Serial - private static final long serialVersionUID = 3487495895818008L; - - public void action() { - handleOutOfSequence(getMapMessages().get(REPLY_K)); - } - }; - b.setMapMessagesList(getMapMessagesList()); - registerState(b, HANDLE_OUT_OF_SEQ); - - // CHECK_SESSIONS - b = new OneShotBehaviour(myAgent) { - int ret; - @Serial - private static final long serialVersionUID = 3487495895818009L; - - public void action() { - ACLMessage reply = getMapMessages().get(REPLY_K); - ret = checkSessions(reply); - } - - public int onEnd() { - return ret; - } - }; - b.setMapMessagesList(getMapMessagesList()); - registerState(b, CHECK_SESSIONS); - - // DUMMY_FINAL - b = new OneShotBehaviour(myAgent) { - @Serial - private static final long serialVersionUID = 3487495895818010L; + super(a); + + setMapMessagesList(mapMessagesList); + this.initiation = initiation; + + // Register the FSM transitions + registerDefaultTransition(PREPARE_INITIATIONS, SEND_INITIATIONS); + registerTransition(SEND_INITIATIONS, DUMMY_FINAL, 0); // Exit the protocol if no initiation message is sent + registerDefaultTransition(SEND_INITIATIONS, RECEIVE_REPLY); + registerTransition(RECEIVE_REPLY, CHECK_SESSIONS, MsgReceiver.TIMEOUT_EXPIRED); + registerTransition(RECEIVE_REPLY, CHECK_SESSIONS, MsgReceiver.INTERRUPTED); + registerDefaultTransition(RECEIVE_REPLY, CHECK_IN_SEQ); + registerTransition(CHECK_IN_SEQ, HANDLE_NOT_UNDERSTOOD, ACLMessage.NOT_UNDERSTOOD); + registerTransition(CHECK_IN_SEQ, HANDLE_FAILURE, ACLMessage.FAILURE); + registerDefaultTransition(CHECK_IN_SEQ, HANDLE_OUT_OF_SEQ); + registerDefaultTransition(HANDLE_NOT_UNDERSTOOD, CHECK_SESSIONS); + registerDefaultTransition(HANDLE_FAILURE, CHECK_SESSIONS); + registerDefaultTransition(HANDLE_OUT_OF_SEQ, RECEIVE_REPLY); + registerDefaultTransition(CHECK_SESSIONS, RECEIVE_REPLY, getToBeReset()); + + // Create and register the states that make up the FSM + Behaviour b; + // PREPARE_INITIATIONS + b = new OneShotBehaviour(myAgent) { + @Serial private static final long serialVersionUID = 3487495895818000L; + + public void action() { + var mapMessages = getMapMessagesList(); + var allInitiations = mapMessages.get(ALL_INITIATIONS_K); + if (allInitiations == null || allInitiations.size() == 0) { + allInitiations = prepareInitiations(getMapMessages().get(INITIATION_K)); + mapMessages.put(ALL_INITIATIONS_K, allInitiations); + } + } + }; + b.setMapMessagesList(getMapMessagesList()); + registerFirstState(b, PREPARE_INITIATIONS); + + // SEND_INITIATIONS + b = new OneShotBehaviour(myAgent) { + @Serial private static final long serialVersionUID = 3487495895818001L; + + public void action() { + var allInitiations = getMapMessagesList().get(ALL_INITIATIONS_K); + if (allInitiations != null) { + sendInitiations(allInitiations); + } + } - public void action() { - } - }; - registerLastState(b, DUMMY_FINAL); + public int onEnd() { + return mapSessions.size(); + } + }; + b.setMapMessagesList(getMapMessagesList()); + registerState(b, SEND_INITIATIONS); + + // RECEIVE_REPLY + //TODO: THE BUG IS HERE !!!!! 2022-02-28 + replyReceiver = new MsgReceiver(myAgent, null, MsgReceiver.INFINITE, getMapMessagesList(), REPLY_K); + registerState(replyReceiver, RECEIVE_REPLY); + + // CHECK_IN_SEQ + b = new OneShotBehaviour(myAgent) { + int ret; + @Serial private static final long serialVersionUID = 3487495895818002L; + + public void action() { + ACLMessage reply = getMapMessages().get(REPLY_K); + if (checkInSequence(reply)) { + ret = reply.getPerformative(); + } else { + ret = -1; + } + } + + public int onEnd() { + return ret; + } + }; + b.setMapMessagesList(getMapMessagesList()); + registerState(b, CHECK_IN_SEQ); + + // HANDLE_NOT_UNDERSTOOD + b = new OneShotBehaviour(myAgent) { + @Serial private static final long serialVersionUID = 3487495895818005L; + + public void action() { + handleNotUnderstood(getMapMessages().get(REPLY_K)); + } + }; + b.setMapMessagesList(getMapMessagesList()); + registerState(b, HANDLE_NOT_UNDERSTOOD); + + // HANDLE_FAILURE + b = new OneShotBehaviour(myAgent) { + @Serial private static final long serialVersionUID = 3487495895818007L; + + public void action() { + handleFailure(getMapMessages().get(REPLY_K)); + } + }; + b.setMapMessagesList(getMapMessagesList()); + registerState(b, HANDLE_FAILURE); + + // HANDLE_OUT_OF_SEQ + b = new OneShotBehaviour(myAgent) { + @Serial private static final long serialVersionUID = 3487495895818008L; + + public void action() { + handleOutOfSequence(getMapMessages().get(REPLY_K)); + } + }; + b.setMapMessagesList(getMapMessagesList()); + registerState(b, HANDLE_OUT_OF_SEQ); + + // CHECK_SESSIONS + b = new OneShotBehaviour(myAgent) { + int ret; + @Serial private static final long serialVersionUID = 3487495895818009L; + + public void action() { + ACLMessage reply = getMapMessages().get(REPLY_K); + ret = checkSessions(reply); + } + + public int onEnd() { + return ret; + } + }; + b.setMapMessagesList(getMapMessagesList()); + registerState(b, CHECK_SESSIONS); + + // DUMMY_FINAL + b = new OneShotBehaviour(myAgent) { + @Serial private static final long serialVersionUID = 3487495895818010L; + + public void action() { + } + }; + registerLastState(b, DUMMY_FINAL); + } + */ + /** + * Constructs an Initiator behaviour + * see #AchieveREInitiator(Agent, ACLMessage, HashMap) + **/ + protected Initiator(Agent a, ACLMessage initiation) { + this(a, initiation, new HashMap<>(), new HashMap<>()); } -*/ + /** * Constructs an Initiator behaviour * @@ -318,9 +308,9 @@ public int onEnd() { // CHECK_IN_SEQ b = new OneShotBehaviour(myAgent) { - int ret; @Serial private static final long serialVersionUID = 3487495895818002L; + int ret; public void action() { ACLMessage reply = getMapMessages().get(REPLY_K); @@ -380,9 +370,9 @@ public void action() { // CHECK_SESSIONS b = new OneShotBehaviour(myAgent) { - int ret; @Serial private static final long serialVersionUID = 3487495895818009L; + int ret; public void action() { ACLMessage reply = getMapMessages().get(REPLY_K); @@ -408,6 +398,12 @@ public void action() { registerLastState(b, DUMMY_FINAL); } + private synchronized static int getCnt() { + int k = cnt; + cnt++; + return k; + } + /** * Specialize (if necessary) the initiation message for each receiver */ @@ -432,6 +428,7 @@ public void action() { * - The state has an "internal memory" */ protected abstract String[] getToBeReset(); + //#APIDOC_EXCLUDE_END /** * Return a ProtocolSession object to manage replies to a given @@ -498,7 +495,6 @@ protected void sendInitiations(List initiations) { replyReceiver.setTemplate(replyTemplate); replyReceiver.setDeadline(deadline); } - //#APIDOC_EXCLUDE_END /** * This method is called every time a not-understood @@ -512,6 +508,8 @@ protected void sendInitiations(List initiations) { protected void handleNotUnderstood(ACLMessage notUnderstood) { } + //#APIDOC_EXCLUDE_BEGIN + /** * This method is called every time a failure * message is received, which is not out-of-sequence according @@ -523,6 +521,7 @@ protected void handleNotUnderstood(ACLMessage notUnderstood) { **/ protected void handleFailure(ACLMessage failure) { } + //#APIDOC_EXCLUDE_END /** * This method is called every time a @@ -536,8 +535,6 @@ protected void handleFailure(ACLMessage failure) { protected void handleOutOfSequence(ACLMessage msg) { } - //#APIDOC_EXCLUDE_BEGIN - /** * Attach a behaviour to the Prepare-initiations * protocol state. @@ -549,7 +546,6 @@ protected void registerPrepareInitiations(Behaviour b) { registerState(b, PREPARE_INITIATIONS); b.setMapMessagesList(getMapMessagesList()); } - //#APIDOC_EXCLUDE_END /** * This method allows to register a user defined Behaviour @@ -640,6 +636,8 @@ protected void reinit() { map.remove(REPLY_K); } + //#APIDOC_EXCLUDE_BEGIN + /** * Override the onStart() method to initialize the lists that * will keep all the replies in the map store. @@ -647,6 +645,7 @@ protected void reinit() { public void onStart() { initializeHashMap(initiation); } + //#APIDOC_EXCLUDE_END /** * Override the setHashMap() method to propagate this @@ -657,8 +656,6 @@ public void setMapMessagesList(HashMap> ds) { getChildren().forEach(child -> child.setMapMessagesList(ds)); } - //#APIDOC_EXCLUDE_BEGIN - /** * Initialize the data store. **/ @@ -666,7 +663,6 @@ protected void initializeHashMap(ACLMessage initiation) { var map = getMapMessages(); map.put(INITIATION_K, initiation); } - //#APIDOC_EXCLUDE_END /** * Create a new conversation identifier to begin a new @@ -691,14 +687,6 @@ protected String createConvId(List msgs) { return convId; } - private static int cnt = 0; - - private synchronized static int getCnt() { - int k = cnt; - cnt++; - return k; - } - //#APIDOC_EXCLUDE_BEGIN protected void adjustReplyTemplate(ACLMessage msg) { // If myAgent is among the receivers (strange case, but can happen) diff --git a/src/jade/proto/IteratedAchieveREInitiator.java b/src/jade/proto/IteratedAchieveREInitiator.java index b374d27..b242ec3 100644 --- a/src/jade/proto/IteratedAchieveREInitiator.java +++ b/src/jade/proto/IteratedAchieveREInitiator.java @@ -50,14 +50,13 @@ * @author Giovanni Caire - TILab */ public class IteratedAchieveREInitiator extends AchieveREInitiator { + public static final String REINIT = "Reinit"; /** * Key to retrieve from the HashMap of the behaviour the vector of * ACLMessage objects that will be sent at next round. */ public final String ALL_NEXT_REQUESTS_KEY = "__all-next-requests" + hashCode(); - public static final String REINIT = "Reinit"; - /** * Construct an IteratedAchieveREInitiator with an empty HashMap */ @@ -79,25 +78,25 @@ public IteratedAchieveREInitiator(Agent a, ACLMessage msg) { * deprecated use the constructor with 2 hashmap public IteratedAchieveREInitiator(Agent a, ACLMessage msg, HashMap> mapMessagesList) { - super(a, msg, mapMessagesList); + super(a, msg, mapMessagesList); - // The HANDLE_ALL_RESULT_NOTIFICATIONS state must no longer be final - Behaviour b = deregisterState(HANDLE_ALL_RESULT_NOTIFICATIONS); - b.setMapMessagesList(getMapMessagesList()); - registerState(b, HANDLE_ALL_RESULT_NOTIFICATIONS); + // The HANDLE_ALL_RESULT_NOTIFICATIONS state must no longer be final + Behaviour b = deregisterState(HANDLE_ALL_RESULT_NOTIFICATIONS); + b.setMapMessagesList(getMapMessagesList()); + registerState(b, HANDLE_ALL_RESULT_NOTIFICATIONS); - // REINIT - b = new OneShotBehaviour(myAgent) { - public void action() { - prepareForNextRound(); - } - }; - b.setMapMessagesList(getMapMessagesList()); - registerState(b, REINIT); + // REINIT + b = new OneShotBehaviour(myAgent) { + public void action() { + prepareForNextRound(); + } + }; + b.setMapMessagesList(getMapMessagesList()); + registerState(b, REINIT); - // Register the FSM transitions specific to the Iterated-Achieve-RE protocol - registerDefaultTransition(HANDLE_ALL_RESULT_NOTIFICATIONS, REINIT); - registerDefaultTransition(REINIT, SEND_INITIATIONS); + // Register the FSM transitions specific to the Iterated-Achieve-RE protocol + registerDefaultTransition(HANDLE_ALL_RESULT_NOTIFICATIONS, REINIT); + registerDefaultTransition(REINIT, SEND_INITIATIONS); }*/ /** @@ -137,6 +136,14 @@ public void action() { registerDefaultTransition(REINIT, SEND_INITIATIONS); } + /** + * Check if the responder has closed the session just after sending this inform message. + */ + public static boolean isSessionTerminated(ACLMessage inform) { + String terminatedStr = inform.getUserDefinedParameter(SSIteratedAchieveREResponder.ACL_USERDEF_TERMINATED_SESSION); + return "true".equals(terminatedStr); + } + //#APIDOC_EXCLUDE_BEGIN protected void prepareForNextRound() { // Reset local variables, clean data store, reset children and copy the @@ -153,6 +160,7 @@ protected void initializeHashMap(ACLMessage msg) { List v = new ArrayList<>(); getMapMessagesList().put(ALL_NEXT_REQUESTS_KEY, v); } + //#APIDOC_EXCLUDE_END protected ProtocolSession getSession(ACLMessage msg, int sessionIndex) { if (msg.getPerformative() == ACLMessage.CANCEL) { @@ -161,8 +169,6 @@ protected ProtocolSession getSession(ACLMessage msg, int sessionIndex) { return super.getSession(msg, sessionIndex); } } - //#APIDOC_EXCLUDE_END - /** * This method is called every time an inform @@ -251,14 +257,6 @@ public void registerHandleAllResultNotifications(Behaviour b) { registerState(b, HANDLE_ALL_RESULT_NOTIFICATIONS); b.setMapMessagesList(getMapMessagesList()); } - - /** - * Check if the responder has closed the session just after sending this inform message. - */ - public static boolean isSessionTerminated(ACLMessage inform) { - String terminatedStr = inform.getUserDefinedParameter(SSIteratedAchieveREResponder.ACL_USERDEF_TERMINATED_SESSION); - return "true".equals(terminatedStr); - } } diff --git a/src/jade/proto/ProposeInitiator.java b/src/jade/proto/ProposeInitiator.java index 345fe09..222ea30 100644 --- a/src/jade/proto/ProposeInitiator.java +++ b/src/jade/proto/ProposeInitiator.java @@ -94,31 +94,6 @@ public class ProposeInitiator extends FSMBehaviour { // Private data store keys (can't be static since if we register another instance of this class as stare of the FSM //using the same data store the new values overrides the old one. - /** - * key to retrieve from the HashMap of the behaviour the ACLMessage - * object passed in the constructor of the class. - **/ - protected final String INITIATION_K = "__initiation" + hashCode(); - - /** - * key to retrieve from the HashMap of the behaviour the vector of - * PROPOSE ACLMessage objects that have to be sent. - **/ - protected final String ALL_INITIATIONS_K = "__all-initiations" + hashCode(); - - /** - * key to retrieve from the HashMap of the behaviour the last - * ACLMessage object that has been received (null if the timeout - * expired). - **/ - public final String REPLY_KEY = "__reply" + hashCode(); - - /** - * key to retrieve from the HashMap of the behaviour the vector of - * ACLMessage objects that have been received as responses. - **/ - public final String ALL_RESPONSES_KEY = "__all-responses" + hashCode(); - // FSM states names protected static final String PREPARE_INITIATIONS = "Prepare-initiations"; protected static final String SEND_INITIATIONS = "Send-initiations"; @@ -129,32 +104,46 @@ public class ProposeInitiator extends FSMBehaviour { protected static final String HANDLE_ALL_RESPONSES = "Handle-all-responses"; protected static final String HANDLE_REJECT_PROPOSAL = "Handle-reject-proposal"; protected static final String HANDLE_ACCEPT_PROPOSAL = "Handle-accept-proposal"; - private static final String CHECK_AGAIN = "Check-again"; protected static final String CHECK_SESSIONS = "Check-sessions"; protected static final String DUMMY_FINAL = "Dummy-final"; + private static final String CHECK_AGAIN = "Check-again"; + // States exit values + private static final int ALL_RESPONSES_RECEIVED = 1; + private static final int TERMINATED = 2; + /** + * key to retrieve from the HashMap of the behaviour the last + * ACLMessage object that has been received (null if the timeout + * expired). + **/ + public final String REPLY_KEY = "__reply" + hashCode(); + /** + * key to retrieve from the HashMap of the behaviour the vector of + * ACLMessage objects that have been received as responses. + **/ + public final String ALL_RESPONSES_KEY = "__all-responses" + hashCode(); //#APIDOC_EXCLUDE_BEGIN - + /** + * key to retrieve from the HashMap of the behaviour the ACLMessage + * object passed in the constructor of the class. + **/ + protected final String INITIATION_K = "__initiation" + hashCode(); + /** + * key to retrieve from the HashMap of the behaviour the vector of + * PROPOSE ACLMessage objects that have to be sent. + **/ + protected final String ALL_INITIATIONS_K = "__all-initiations" + hashCode(); // This maps the AID of each responder to a Session object // holding the status of the protocol as far as that responder // is concerned. Sessions are protocol-specific protected Map sessions = new HashMap<>(); + + //#APIDOC_EXCLUDE_END // The MsgReceiver behaviour used to receive replies protected MsgReceiver replyReceiver; // The MessageTemplate used by the replyReceiver protected MessageTemplate replyTemplate = null; - - //#APIDOC_EXCLUDE_END - - private ACLMessage initiation; - - // States exit values - private static final int ALL_RESPONSES_RECEIVED = 1; - private static final int TERMINATED = 2; - - //#APIDOC_EXCLUDE_BEGIN - // These states must be reset before they are visited again. // Note that resetting a state before visiting it again is required // only if @@ -169,9 +158,10 @@ public class ProposeInitiator extends FSMBehaviour { HANDLE_OUT_OF_SEQ }; - //#APIDOC_EXCLUDE_END - + //#APIDOC_EXCLUDE_BEGIN + private ACLMessage initiation; + //#APIDOC_EXCLUDE_END // If set to true all expected responses have been received private boolean allResponsesReceived = false; @@ -266,9 +256,9 @@ public int onEnd() { // CHECK_IN_SEQ b = new OneShotBehaviour(myAgent) { - int ret; @Serial private static final long serialVersionUID = 3487495895818002L; + int ret; public void action() { ACLMessage reply = getMapMessages().get(REPLY_KEY); @@ -339,9 +329,9 @@ public void action() { // CHECK_SESSIONS b = new OneShotBehaviour(myAgent) { - int ret; @Serial private static final long serialVersionUID = 3487495895818009L; + int ret; public void action() { ACLMessage reply = getMapMessages().get(REPLY_KEY); @@ -463,9 +453,9 @@ public int onEnd() { // CHECK_IN_SEQ b = new OneShotBehaviour(myAgent) { - int ret; @Serial private static final long serialVersionUID = 3487495895818002L; + int ret; public void action() { ACLMessage reply = getMapMessages().get(REPLY_KEY); @@ -536,9 +526,9 @@ public void action() { // CHECK_SESSIONS b = new OneShotBehaviour(myAgent) { - int ret; @Serial private static final long serialVersionUID = 3487495895818009L; + int ret; public void action() { ACLMessage reply = getMapMessages().get(REPLY_KEY); diff --git a/src/jade/proto/ProposeResponder.java b/src/jade/proto/ProposeResponder.java index 2a77a9b..c311103 100644 --- a/src/jade/proto/ProposeResponder.java +++ b/src/jade/proto/ProposeResponder.java @@ -84,6 +84,10 @@ public class ProposeResponder extends FSMBehaviour implements FIPANames.InteractionProtocol { + // FSM states names + protected static final String RECEIVE_PROPOSE = "Receive-propose"; + protected static final String PREPARE_RESPONSE = "Prepare-response"; + protected static final String SEND_RESPONSE = "Send-response"; /** * key to retrieve from the HashMap of the behaviour the ACLMessage * object sent by the initiator. @@ -94,58 +98,9 @@ public class ProposeResponder extends FSMBehaviour implements FIPANames.Interact * object sent as a response to the initiator. **/ public final String RESPONSE_KEY = "__response" + hashCode(); - - // FSM states names - protected static final String RECEIVE_PROPOSE = "Receive-propose"; - protected static final String PREPARE_RESPONSE = "Prepare-response"; - protected static final String SEND_RESPONSE = "Send-response"; - - // Private inner classes for the FSM states - private static class PrepareResponse extends OneShotBehaviour { - - public PrepareResponse(Agent a) { - super(a); - } - - // For persistence service - private PrepareResponse() { - } - - public void action() { - ProposeResponder fsm = (ProposeResponder) getParent(); - var ds = getMapMessages(); - ACLMessage propose = ds.get(fsm.PROPOSE_KEY); - - ACLMessage response; - try { - response = fsm.prepareResponse(propose); - } catch (NotUnderstoodException | RefuseException nue) { - response = nue.getACLMessage(); - } - ds.put(fsm.RESPONSE_KEY, response); - } - - } // End of PrepareResponse class - - // The MsgReceiver behaviour used to receive propose messages MsgReceiver rec = null; - /** - * This static method can be used - * to set the proper message template (based on the interaction protocol - * and the performative) - * into the constructor of this behaviour. - * - * @see FIPANames.InteractionProtocol - **/ - public static MessageTemplate createMessageTemplate(String iprotocol) { - - if (CaseInsensitiveString.equalsIgnoreCase(FIPA_PROPOSE, iprotocol)) - return MessageTemplate.and(MessageTemplate.MatchProtocol(FIPA_PROPOSE), MessageTemplate.MatchPerformative(ACLMessage.PROPOSE)); - else - return MessageTemplate.MatchProtocol(iprotocol); - } /** * Constructor of the behaviour that creates a new empty HashMap @@ -163,13 +118,14 @@ public ProposeResponder(Agent a, MessageTemplate mt) { * @param mt is the MessageTemplate that must be used to match * the initiator message. Take care that * if mt is null every message is consumed by this protocol. - * @param mapMessagesList the HashMap for this protocol - * @deprecated - - public ProposeResponder(Agent a, MessageTemplate mt, HashMap> mapMessagesList) { + * @param mapMessagesList the HashMap of messages list for this protocol + * @param mapMessages the HashMap of message for this protocol + **/ + public ProposeResponder(Agent a, MessageTemplate mt, HashMap> mapMessagesList, HashMap mapMessages) { super(a); setMapMessagesList(mapMessagesList); + setMapMessages(mapMessages); // Register the FSM transitions registerDefaultTransition(RECEIVE_PROPOSE, PREPARE_RESPONSE); @@ -180,20 +136,24 @@ public ProposeResponder(Agent a, MessageTemplate mt, HashMap> mapMessagesList, HashMap mapMessages) { - super(a); + * @param mapMessagesList the HashMap for this protocol + * @deprecated public ProposeResponder(Agent a, MessageTemplate mt, HashMap> mapMessagesList) { + super(a); - setMapMessagesList(mapMessagesList); - setMapMessages(mapMessages); + setMapMessagesList(mapMessagesList); - // Register the FSM transitions - registerDefaultTransition(RECEIVE_PROPOSE, PREPARE_RESPONSE); - registerDefaultTransition(PREPARE_RESPONSE, SEND_RESPONSE); - registerDefaultTransition(SEND_RESPONSE, RECEIVE_PROPOSE); + // Register the FSM transitions + registerDefaultTransition(RECEIVE_PROPOSE, PREPARE_RESPONSE); + registerDefaultTransition(PREPARE_RESPONSE, SEND_RESPONSE); + registerDefaultTransition(SEND_RESPONSE, RECEIVE_PROPOSE); - // Create and register the states that make up the FSM - Behaviour b; + // Create and register the states that make up the FSM + Behaviour b; - // RECEIVE_PROPOSE - rec = new MsgReceiver(myAgent, mt, -1, mapMessagesList, mapMessages, PROPOSE_KEY); - registerFirstState(rec, RECEIVE_PROPOSE); + // RECEIVE_PROPOSE + rec = new MsgReceiver(myAgent, mt, -1, getMapMessagesList(), PROPOSE_KEY); + registerFirstState(rec, RECEIVE_PROPOSE); - // PREPARE_RESPONSE - b = new PrepareResponse(myAgent); - b.setMapMessagesList(mapMessagesList); - b.setMapMessages(mapMessages); - registerState(b, PREPARE_RESPONSE); + // PREPARE_RESPONSE + b = new PrepareResponse(myAgent); + b.setMapMessagesList(getMapMessagesList()); + registerState(b, PREPARE_RESPONSE); - // SEND_RESPONSE - b = new ReplySender(myAgent, RESPONSE_KEY, PROPOSE_KEY, mapMessagesList, mapMessages); - b.setMapMessagesList(getMapMessagesList()); - registerState(b, SEND_RESPONSE); + // SEND_RESPONSE + b = new ReplySender(myAgent, RESPONSE_KEY, PROPOSE_KEY); + b.setMapMessagesList(getMapMessagesList()); + registerState(b, SEND_RESPONSE); + } + */ + + /** + * This static method can be used + * to set the proper message template (based on the interaction protocol + * and the performative) + * into the constructor of this behaviour. + * + * @see FIPANames.InteractionProtocol + **/ + public static MessageTemplate createMessageTemplate(String iprotocol) { + + if (CaseInsensitiveString.equalsIgnoreCase(FIPA_PROPOSE, iprotocol)) + return MessageTemplate.and(MessageTemplate.MatchProtocol(FIPA_PROPOSE), MessageTemplate.MatchPerformative(ACLMessage.PROPOSE)); + else + return MessageTemplate.MatchProtocol(iprotocol); } /** @@ -295,9 +268,32 @@ public void registerPrepareResponse(Behaviour b) { //#MIDP_EXCLUDE_BEGIN - // For persistence service - private ProposeResponder() { - } + // Private inner classes for the FSM states + private static class PrepareResponse extends OneShotBehaviour { + + public PrepareResponse(Agent a) { + super(a); + } + + // For persistence service + private PrepareResponse() { + } + + public void action() { + ProposeResponder fsm = (ProposeResponder) getParent(); + var ds = getMapMessages(); + ACLMessage propose = ds.get(fsm.PROPOSE_KEY); + + ACLMessage response; + try { + response = fsm.prepareResponse(propose); + } catch (NotUnderstoodException | RefuseException nue) { + response = nue.getACLMessage(); + } + ds.put(fsm.RESPONSE_KEY, response); + } + + } // End of PrepareResponse class //#MIDP_EXCLUDE_END } diff --git a/src/jade/proto/Responder.java b/src/jade/proto/Responder.java index 47ddc4f..f6a0f0c 100644 --- a/src/jade/proto/Responder.java +++ b/src/jade/proto/Responder.java @@ -50,12 +50,21 @@ abstract class Responder extends FSMBehaviour { // Data store keys + //#APIDOC_EXCLUDE_BEGIN + // FSM states names + protected static final String RECEIVE_INITIATION = "Receive-Initiation"; + protected static final String RECEIVE_NEXT = "Receive-Next"; + + + // private inner classes for the FSM states + protected static final String HANDLE_OUT_OF_SEQUENCE = "Handle-Out-of-seq"; + protected static final String CHECK_IN_SEQ = "Check-In-seq"; + protected static final String SEND_REPLY = "Send-Reply"; /** * Key to retrieve from the HashMap of the behaviour the last received * ACLMessage */ public final String RECEIVED_KEY = "__Received_key" + hashCode(); - /** * Key to set into the HashMap of the behaviour the new ACLMessage * to be sent back to the initiator as a reply. @@ -63,149 +72,6 @@ abstract class Responder extends FSMBehaviour { public final String REPLY_KEY = "__Reply_key" + hashCode(); - // private inner classes for the FSM states - - - private static class CfpReceiver extends MsgReceiver { - - /** - * @deprecated - */ - public CfpReceiver(Agent myAgent, MessageTemplate mt, long deadline, HashMap> s, String msgKey) { - super(myAgent, mt, deadline, s, msgKey); - } - - public CfpReceiver(Agent myAgent, MessageTemplate mt, long deadline, HashMap> mapMessagesList, HashMap mapMessages, String msgKey) { - super(myAgent, mt, deadline, mapMessagesList, mapMessages, msgKey); - } - - // For persistence service - private CfpReceiver() { - } - - public int onEnd() { - Responder fsm = (Responder) getParent(); - MsgReceiver nextRecv = (MsgReceiver) fsm.getState(RECEIVE_NEXT); - - // Set the template to receive next messages - ACLMessage received = getMapMessages().get(fsm.RECEIVED_KEY); - nextRecv.setTemplate(MessageTemplate.MatchConversationId(received.getConversationId())); - return super.onEnd(); - } - - } // End of CfpReceiver class - - private static class NextReceiver extends MsgReceiver { - /** - * @deprecated - */ - public NextReceiver(Agent myAgent, MessageTemplate mt, long deadline, HashMap> s, String msgKey) { - super(myAgent, mt, deadline, s, msgKey); - } - - public NextReceiver(Agent myAgent, MessageTemplate mt, long deadline, HashMap> mapMessagesList, HashMap mapMessages, String msgKey) { - super(myAgent, mt, deadline, mapMessagesList, mapMessages, msgKey); - } - - // For persistence service - private NextReceiver() { - } - - public void onStart() { - // Set the deadline for receiving the next message on the basis - // of the last reply sent - Responder fsm = (Responder) getParent(); - ACLMessage reply = getMapMessages().get(fsm.REPLY_KEY); - if (reply != null) { - Date d = reply.getReplyByDate(); - if (d != null && d.getTime() > System.currentTimeMillis()) { - setDeadline(d.getTime()); - } - } - } - - } // End of NextReceiver class - - private static class CheckInSeq extends OneShotBehaviour { - - private int ret; - @Serial - private static final long serialVersionUID = 4487495895818000L; - - public CheckInSeq(Agent a) { - super(a); - } - - // For persistence service - private CheckInSeq() { - } - - public void action() { - Responder fsm = (Responder) getParent(); - ACLMessage received = getMapMessages().get(fsm.RECEIVED_KEY); - if (fsm.checkInSequence(received)) { - ret = received.getPerformative(); - } else { - ret = -1; - } - } - - public int onEnd() { - return ret; - } - - } // End of CheckInSeq class - - - private static class HandleOutOfSeq extends OneShotBehaviour { - - @Serial - private static final long serialVersionUID = 4487495895818005L; - - public HandleOutOfSeq(Agent a) { - super(a); - } - - // For persistence service - private HandleOutOfSeq() { - } - - public void action() { - Responder fsm = (Responder) getParent(); - fsm.handleOutOfSequence(getMapMessages().get(fsm.RECEIVED_KEY)); - } - - } // End of HandleOutOfSeq class - - - private static class SendReply extends ReplySender { - - public SendReply(Agent a, String replyKey, String msgKey, HashMap> mapMessagesList, HashMap mapMessages) { - super(a, replyKey, msgKey, mapMessagesList, mapMessages); - } - - // For persistence service - private SendReply() { - } - - public int onEnd() { - int ret = super.onEnd(); - Responder fsm = (Responder) getParent(); - fsm.replySent(ret); - return ret; - } - - } // End of SendReply class - - - //#APIDOC_EXCLUDE_BEGIN - // FSM states names - protected static final String RECEIVE_INITIATION = "Receive-Initiation"; - protected static final String RECEIVE_NEXT = "Receive-Next"; - protected static final String HANDLE_OUT_OF_SEQUENCE = "Handle-Out-of-seq"; - protected static final String CHECK_IN_SEQ = "Check-In-seq"; - protected static final String SEND_REPLY = "Send-Reply"; - /** * Constructor of the behaviour that creates a new empty HashMap * @@ -214,7 +80,6 @@ public int onEnd() { public Responder(Agent a, MessageTemplate mt) { this(a, mt, new HashMap<>(), new HashMap<>()); } - /** * Constructor of the behaviour. * @@ -258,7 +123,6 @@ public Responder(Agent a, MessageTemplate mt, HashMap> b = new SendReply(myAgent, REPLY_KEY, RECEIVED_KEY, getMapMessagesList(), getMapMessages()); registerDSState(b, SEND_REPLY); } - /** * Constructor of the behaviour. * @@ -303,13 +167,10 @@ public Responder(Agent a, MessageTemplate mt, HashMap> b = new SendReply(myAgent, REPLY_KEY, RECEIVED_KEY, getMapMessagesList(), getMapMessages()); registerDSState(b, SEND_REPLY); } - // For persistence service private Responder() { } - //#APIDOC_EXCLUDE_END - /** * This method is called whenever a message is received that does * not comply to the protocol rules. @@ -349,8 +210,6 @@ public void reset() { ds.remove(REPLY_KEY); } - //#APIDOC_EXCLUDE_BEGIN - /** * Check whether a received message complies with the protocol rules. */ @@ -364,6 +223,8 @@ public void reset() { protected void replySent(int exitValue) { } + //#APIDOC_EXCLUDE_END + /** * Utility method to register a behaviour in a state of the * protocol and set the HashMap appropriately @@ -372,5 +233,136 @@ protected void registerDSState(Behaviour b, String name) { b.setMapMessagesList(getMapMessagesList()); registerState(b, name); } + + private static class CfpReceiver extends MsgReceiver { + + /** + * @deprecated + */ + public CfpReceiver(Agent myAgent, MessageTemplate mt, long deadline, HashMap> s, String msgKey) { + super(myAgent, mt, deadline, s, msgKey); + } + + public CfpReceiver(Agent myAgent, MessageTemplate mt, long deadline, HashMap> mapMessagesList, HashMap mapMessages, String msgKey) { + super(myAgent, mt, deadline, mapMessagesList, mapMessages, msgKey); + } + + // For persistence service + private CfpReceiver() { + } + + public int onEnd() { + Responder fsm = (Responder) getParent(); + MsgReceiver nextRecv = (MsgReceiver) fsm.getState(RECEIVE_NEXT); + + // Set the template to receive next messages + ACLMessage received = getMapMessages().get(fsm.RECEIVED_KEY); + nextRecv.setTemplate(MessageTemplate.MatchConversationId(received.getConversationId())); + return super.onEnd(); + } + + } // End of CfpReceiver class + + private static class NextReceiver extends MsgReceiver { + /** + * @deprecated + */ + public NextReceiver(Agent myAgent, MessageTemplate mt, long deadline, HashMap> s, String msgKey) { + super(myAgent, mt, deadline, s, msgKey); + } + + public NextReceiver(Agent myAgent, MessageTemplate mt, long deadline, HashMap> mapMessagesList, HashMap mapMessages, String msgKey) { + super(myAgent, mt, deadline, mapMessagesList, mapMessages, msgKey); + } + + // For persistence service + private NextReceiver() { + } + + public void onStart() { + // Set the deadline for receiving the next message on the basis + // of the last reply sent + Responder fsm = (Responder) getParent(); + ACLMessage reply = getMapMessages().get(fsm.REPLY_KEY); + if (reply != null) { + Date d = reply.getReplyByDate(); + if (d != null && d.getTime() > System.currentTimeMillis()) { + setDeadline(d.getTime()); + } + } + } + + } // End of NextReceiver class + + //#APIDOC_EXCLUDE_BEGIN + + private static class CheckInSeq extends OneShotBehaviour { + + @Serial + private static final long serialVersionUID = 4487495895818000L; + private int ret; + + public CheckInSeq(Agent a) { + super(a); + } + + // For persistence service + private CheckInSeq() { + } + + public void action() { + Responder fsm = (Responder) getParent(); + ACLMessage received = getMapMessages().get(fsm.RECEIVED_KEY); + if (fsm.checkInSequence(received)) { + ret = received.getPerformative(); + } else { + ret = -1; + } + } + + public int onEnd() { + return ret; + } + + } // End of CheckInSeq class + + private static class HandleOutOfSeq extends OneShotBehaviour { + + @Serial + private static final long serialVersionUID = 4487495895818005L; + + public HandleOutOfSeq(Agent a) { + super(a); + } + + // For persistence service + private HandleOutOfSeq() { + } + + public void action() { + Responder fsm = (Responder) getParent(); + fsm.handleOutOfSequence(getMapMessages().get(fsm.RECEIVED_KEY)); + } + + } // End of HandleOutOfSeq class + + private static class SendReply extends ReplySender { + + public SendReply(Agent a, String replyKey, String msgKey, HashMap> mapMessagesList, HashMap mapMessages) { + super(a, replyKey, msgKey, mapMessagesList, mapMessages); + } + + // For persistence service + private SendReply() { + } + + public int onEnd() { + int ret = super.onEnd(); + Responder fsm = (Responder) getParent(); + fsm.replySent(ret); + return ret; + } + + } // End of SendReply class //#APIDOC_EXCLUDE_END } diff --git a/src/jade/proto/SSContractNetResponder.java b/src/jade/proto/SSContractNetResponder.java index 5e44683..d165de0 100644 --- a/src/jade/proto/SSContractNetResponder.java +++ b/src/jade/proto/SSContractNetResponder.java @@ -46,6 +46,9 @@ * @author Giovanni Caire - TILAB */ public class SSContractNetResponder extends SSResponder { + public static final String HANDLE_CFP = "Handle-Cfp"; + public static final String HANDLE_ACCEPT_PROPOSAL = "Handle-Accept-Proposal"; + public static final String HANDLE_REJECT_PROPOSAL = "Handle-Reject-Proposal"; /** * Key to retrieve from the HashMap of the behaviour the last received * CFP ACLMessage @@ -66,11 +69,6 @@ public class SSContractNetResponder extends SSResponder { * REJECT_PROPOSAL ACLMessage */ public final String REJECT_PROPOSAL_KEY = RECEIVED_KEY; - - public static final String HANDLE_CFP = "Handle-Cfp"; - public static final String HANDLE_ACCEPT_PROPOSAL = "Handle-Accept-Proposal"; - public static final String HANDLE_REJECT_PROPOSAL = "Handle-Reject-Proposal"; - private boolean proposeSent = false; /** @@ -115,6 +113,7 @@ public SSContractNetResponder(Agent a, ACLMessage cfp, HashMap> store) { + // 4th parameter is false since in this protocol we treat the initiation message exactly as all subsequent incoming messages + super(a, request, store, false); - public SSIteratedAchieveREResponder(Agent a, ACLMessage request, HashMap> store) { - // 4th parameter is false since in this protocol we treat the initiation message exactly as all subsequent incoming messages - super(a, request, store, false); + initiationPerformative = request.getPerformative(); - initiationPerformative = request.getPerformative(); + registerDefaultTransition(HANDLE_REQUEST, SEND_REPLY); + registerTransition(SEND_REPLY, RECEIVE_NEXT, ACLMessage.INFORM); + registerTransition(RECEIVE_NEXT, HANDLE_CANCEL, MsgReceiver.TIMEOUT_EXPIRED); + registerTransition(CHECK_IN_SEQ, HANDLE_REQUEST, initiationPerformative, new String[]{HANDLE_REQUEST, SEND_REPLY, RECEIVE_NEXT, CHECK_IN_SEQ}); + registerTransition(CHECK_IN_SEQ, HANDLE_CANCEL, ACLMessage.CANCEL); + registerDefaultTransition(HANDLE_CANCEL, DUMMY_FINAL); - registerDefaultTransition(HANDLE_REQUEST, SEND_REPLY); - registerTransition(SEND_REPLY, RECEIVE_NEXT, ACLMessage.INFORM); - registerTransition(RECEIVE_NEXT, HANDLE_CANCEL, MsgReceiver.TIMEOUT_EXPIRED); - registerTransition(CHECK_IN_SEQ, HANDLE_REQUEST, initiationPerformative, new String[]{HANDLE_REQUEST, SEND_REPLY, RECEIVE_NEXT, CHECK_IN_SEQ}); - registerTransition(CHECK_IN_SEQ, HANDLE_CANCEL, ACLMessage.CANCEL); - registerDefaultTransition(HANDLE_CANCEL, DUMMY_FINAL); + Behaviour b; - Behaviour b; - - // HANDLE_REQUEST - b = new RequestHandler(myAgent); - registerFirstState(b, HANDLE_REQUEST); - b.setMapMessagesList(getMapMessagesList()); + // HANDLE_REQUEST + b = new RequestHandler(myAgent); + registerFirstState(b, HANDLE_REQUEST); + b.setMapMessagesList(getMapMessagesList()); - // HANDLE_CANCEL - b = new CancelHandler(myAgent); - registerDSState(b, HANDLE_CANCEL); + // HANDLE_CANCEL + b = new CancelHandler(myAgent); + registerDSState(b, HANDLE_CANCEL); } -*/ + */ /** * Construct a SSIteratedAchieveREResponder that is activated * by the reception of a given initiation REQUEST message and uses diff --git a/src/jade/proto/SSIteratedContractNetResponder.java b/src/jade/proto/SSIteratedContractNetResponder.java index 559377b..f82a087 100644 --- a/src/jade/proto/SSIteratedContractNetResponder.java +++ b/src/jade/proto/SSIteratedContractNetResponder.java @@ -17,14 +17,12 @@ public SSIteratedContractNetResponder(Agent a, ACLMessage cfp) { * by the reception of a given initiation CFP message and uses * a given HashMap of messages list. * - * @deprecated + * @deprecated public SSIteratedContractNetResponder(Agent a, ACLMessage cfp, HashMap> mapMessagesList) { + super(a, cfp, mapMessagesList); - public SSIteratedContractNetResponder(Agent a, ACLMessage cfp, HashMap> mapMessagesList) { - super(a, cfp, mapMessagesList); - - registerTransition(CHECK_IN_SEQ, HANDLE_CFP, ACLMessage.CFP, new String[]{HANDLE_CFP, SEND_REPLY, RECEIVE_NEXT}); + registerTransition(CHECK_IN_SEQ, HANDLE_CFP, ACLMessage.CFP, new String[]{HANDLE_CFP, SEND_REPLY, RECEIVE_NEXT}); } -*/ + */ /** * Construct a SSIteratedContractNetResponder that is activated * by the reception of a given initiation CFP message and uses diff --git a/src/jade/proto/SSResponder.java b/src/jade/proto/SSResponder.java index 3f8d745..0797cd5 100644 --- a/src/jade/proto/SSResponder.java +++ b/src/jade/proto/SSResponder.java @@ -47,34 +47,29 @@ * @author Giovanni Caire - TILAB */ abstract class SSResponder extends FSMBehaviour { + //#APIDOC_EXCLUDE_BEGIN + // FSM states names + protected static final String RECEIVE_NEXT = "Receive-Next"; + protected static final String CHECK_IN_SEQ = "Check-In-seq"; + protected static final String HANDLE_OUT_OF_SEQUENCE = "Handle-Out-of-seq"; + protected static final String SEND_REPLY = "Send-Reply"; + protected static final String DUMMY_FINAL = "Dummy-Final"; + private static final int OUT_OF_SEQUENCE_EXIT_CODE = -98765; // Very strange number /** * Key to retrieve from the HashMap of the behaviour the initiation * ACLMessage that triggered this responder session */ public final String INITIATION_KEY = "__Initiation_key" + hashCode(); - /** * Key to retrieve from the HashMap of the behaviour the last received * ACLMessage */ public final String RECEIVED_KEY = "__Received_key" + hashCode(); - /** * Key to set into the HashMap of the behaviour the new ACLMessage * to be sent back to the initiator as a reply. */ public final String REPLY_KEY = "__Reply_key" + hashCode(); - - private static final int OUT_OF_SEQUENCE_EXIT_CODE = -98765; // Very strange number - - //#APIDOC_EXCLUDE_BEGIN - // FSM states names - protected static final String RECEIVE_NEXT = "Receive-Next"; - protected static final String CHECK_IN_SEQ = "Check-In-seq"; - protected static final String HANDLE_OUT_OF_SEQUENCE = "Handle-Out-of-seq"; - protected static final String SEND_REPLY = "Send-Reply"; - protected static final String DUMMY_FINAL = "Dummy-Final"; - private final ACLMessage initiation; private final String initiationKey; @@ -119,6 +114,7 @@ public SSResponder(Agent a, ACLMessage initiation, HashMap> mapMessagesList, HashMap mapMessages, boolean useInitiationKey) { super(a); @@ -291,9 +287,9 @@ public int onEnd() { * Inner class SeqChecker */ private static class SeqChecker extends OneShotBehaviour { - private int ret; @Serial private static final long serialVersionUID = 4487495895818002L; + private int ret; public SeqChecker(Agent a) { super(a); diff --git a/src/jade/proto/SSResponderDispatcher.java b/src/jade/proto/SSResponderDispatcher.java index 2d81dcd..531c02e 100644 --- a/src/jade/proto/SSResponderDispatcher.java +++ b/src/jade/proto/SSResponderDispatcher.java @@ -22,6 +22,7 @@ * see SSIteratedAchieveREtResponder */ public abstract class SSResponderDispatcher extends CyclicBehaviour { + private static long cnt = 0; private final ConversationList activeConversations; private final MessageTemplate template; @@ -33,6 +34,10 @@ public SSResponderDispatcher(Agent a, MessageTemplate tpl) { activeConversations.getMessageTemplate()); } + private synchronized static String createConversationId(String name) { + return "C-" + name + '-' + System.currentTimeMillis() + '-' + (cnt++); + } + public final void action() { ACLMessage msg = myAgent.receive(template); if (msg != null) { @@ -74,10 +79,4 @@ public int onEnd() { protected void addBehaviour(Behaviour b) { myAgent.addBehaviour(b); } - - private static long cnt = 0; - - private synchronized static String createConversationId(String name) { - return "C-" + name + '-' + System.currentTimeMillis() + '-' + (cnt++); - } } diff --git a/src/jade/proto/SimpleAchieveREInitiator.java b/src/jade/proto/SimpleAchieveREInitiator.java index 1bf1d19..585950b 100644 --- a/src/jade/proto/SimpleAchieveREInitiator.java +++ b/src/jade/proto/SimpleAchieveREInitiator.java @@ -123,17 +123,14 @@ public class SimpleAchieveREInitiator extends SimpleBehaviour { * key to retrive the result notification received. **/ public final String ALL_RESULT_NOTIFICATIONS_KEY = "_all-result-notification" + hashCode(); - + private final Logger logger = Logger.getMyLogger(this.getClass().getName()); //private ACLMessage request = null; private MessageTemplate mt = null; - private int state = PREPARE_MSG_STATE; private boolean finished; private long timeout = -1; private long endingTime = 0; - private final Logger logger = Logger.getMyLogger(this.getClass().getName()); - /** * Construct for the class by creating a new empty HashMap * diff --git a/src/jade/proto/SimpleAchieveREResponder.java b/src/jade/proto/SimpleAchieveREResponder.java index b8569f8..f74aa7b 100644 --- a/src/jade/proto/SimpleAchieveREResponder.java +++ b/src/jade/proto/SimpleAchieveREResponder.java @@ -83,18 +83,6 @@ public class SimpleAchieveREResponder extends SimpleBehaviour implements FIPANam private int state = WAITING_MSG_STATE; private boolean finished; - /** - * This static method can be used - * to set the proper message Template (based on the interaction protocol - * and the performative) - * into the constructor of this behaviour. - * - * @see FIPANames.InteractionProtocol - **/ - public static MessageTemplate createMessageTemplate(String iprotocol) { - return AchieveREResponder.createMessageTemplate(iprotocol); - } - /** * Constructor of the behaviour that creates a new empty HashMap **/ @@ -136,6 +124,18 @@ public SimpleAchieveREResponder(Agent a, MessageTemplate mt, HashMapSubscriptionInitiator with an empty HashMap - * - * @see #SubscriptionInitiator(Agent, ACLMessage, HashMap, HashMap) - **/ - public SubscriptionInitiator(Agent a, ACLMessage msg) { - this(a, msg, new HashMap<>(), new HashMap<>()); - } + private String[] toBeReset = null; /** * Construct a SubscriptionInitiator with a given HashMap @@ -144,82 +133,90 @@ public SubscriptionInitiator(Agent a, ACLMessage msg) { * @param mapMessagesList The HashMap of messages list that will be used by this SubscriptionInitiator * deprecated public SubscriptionInitiator(Agent a, ACLMessage msg, HashMap> mapMessagesList) { - super(a, msg, mapMessagesList); - - // Register the FSM transitions specific to the Achieve-RE protocol - registerTransition(CHECK_IN_SEQ, HANDLE_AGREE, ACLMessage.AGREE); - registerTransition(CHECK_IN_SEQ, HANDLE_INFORM, ACLMessage.INFORM); - registerTransition(CHECK_IN_SEQ, HANDLE_REFUSE, ACLMessage.REFUSE); - registerDefaultTransition(HANDLE_AGREE, CHECK_SESSIONS); - registerDefaultTransition(HANDLE_INFORM, CHECK_SESSIONS); - registerDefaultTransition(HANDLE_REFUSE, CHECK_SESSIONS); - registerTransition(CHECK_SESSIONS, HANDLE_ALL_RESPONSES, ALL_RESPONSES_RECEIVED); - registerTransition(CHECK_SESSIONS, DUMMY_FINAL, TERMINATED); - registerDefaultTransition(HANDLE_ALL_RESPONSES, CHECK_AGAIN); - registerTransition(CHECK_AGAIN, DUMMY_FINAL, 0); - registerDefaultTransition(CHECK_AGAIN, RECEIVE_REPLY, getToBeReset()); - - // Create and register the states specific to the Subscription protocol - Behaviour b; - // HANDLE_AGREE - b = new OneShotBehaviour(myAgent) { - @Serial - private static final long serialVersionUID = 3487495895820003L; + super(a, msg, mapMessagesList); + + // Register the FSM transitions specific to the Achieve-RE protocol + registerTransition(CHECK_IN_SEQ, HANDLE_AGREE, ACLMessage.AGREE); + registerTransition(CHECK_IN_SEQ, HANDLE_INFORM, ACLMessage.INFORM); + registerTransition(CHECK_IN_SEQ, HANDLE_REFUSE, ACLMessage.REFUSE); + registerDefaultTransition(HANDLE_AGREE, CHECK_SESSIONS); + registerDefaultTransition(HANDLE_INFORM, CHECK_SESSIONS); + registerDefaultTransition(HANDLE_REFUSE, CHECK_SESSIONS); + registerTransition(CHECK_SESSIONS, HANDLE_ALL_RESPONSES, ALL_RESPONSES_RECEIVED); + registerTransition(CHECK_SESSIONS, DUMMY_FINAL, TERMINATED); + registerDefaultTransition(HANDLE_ALL_RESPONSES, CHECK_AGAIN); + registerTransition(CHECK_AGAIN, DUMMY_FINAL, 0); + registerDefaultTransition(CHECK_AGAIN, RECEIVE_REPLY, getToBeReset()); + + // Create and register the states specific to the Subscription protocol + Behaviour b; + // HANDLE_AGREE + b = new OneShotBehaviour(myAgent) { + @Serial private static final long serialVersionUID = 3487495895820003L; + + public void action() { + handleAgree(getMapMessages().get(REPLY_K)); + } + }; + b.setMapMessagesList(getMapMessagesList()); + registerState(b, HANDLE_AGREE); - public void action() { - handleAgree(getMapMessages().get(REPLY_K)); - } - }; - b.setMapMessagesList(getMapMessagesList()); - registerState(b, HANDLE_AGREE); + // HANDLE_REFUSE + b = new OneShotBehaviour(myAgent) { + @Serial private static final long serialVersionUID = 3487495895820004L; - // HANDLE_REFUSE - b = new OneShotBehaviour(myAgent) { - @Serial - private static final long serialVersionUID = 3487495895820004L; + public void action() { + handleRefuse(getMapMessages().get(REPLY_K)); + } + }; + b.setMapMessagesList(getMapMessagesList()); + registerState(b, HANDLE_REFUSE); - public void action() { - handleRefuse(getMapMessages().get(REPLY_K)); - } - }; - b.setMapMessagesList(getMapMessagesList()); - registerState(b, HANDLE_REFUSE); + // HANDLE_INFORM + b = new OneShotBehaviour(myAgent) { + @Serial private static final long serialVersionUID = 3487495895820006L; - // HANDLE_INFORM - b = new OneShotBehaviour(myAgent) { - @Serial - private static final long serialVersionUID = 3487495895820006L; + public void action() { + handleInform(getMapMessages().get(REPLY_K)); + } + }; + b.setMapMessagesList(getMapMessagesList()); + registerState(b, HANDLE_INFORM); - public void action() { - handleInform(getMapMessages().get(REPLY_K)); - } - }; - b.setMapMessagesList(getMapMessagesList()); - registerState(b, HANDLE_INFORM); + // HANDLE_ALL_RESPONSES + b = new OneShotBehaviour(myAgent) { - // HANDLE_ALL_RESPONSES - b = new OneShotBehaviour(myAgent) { + public void action() { + handleAllResponses(getMapMessagesList().get(ALL_RESPONSES_KEY)); + } + }; + b.setMapMessagesList(getMapMessagesList()); + registerState(b, HANDLE_ALL_RESPONSES); - public void action() { - handleAllResponses(getMapMessagesList().get(ALL_RESPONSES_KEY)); - } - }; - b.setMapMessagesList(getMapMessagesList()); - registerState(b, HANDLE_ALL_RESPONSES); + // CHECK_AGAIN + b = new OneShotBehaviour(myAgent) { + public void action() { + } - // CHECK_AGAIN - b = new OneShotBehaviour(myAgent) { - public void action() { - } + public int onEnd() { + return mapSessions.size(); + } + }; + b.setMapMessagesList(getMapMessagesList()); + registerState(b, CHECK_AGAIN); + } + */ - public int onEnd() { - return mapSessions.size(); - } - }; - b.setMapMessagesList(getMapMessagesList()); - registerState(b, CHECK_AGAIN); + /** + * Construct a SubscriptionInitiator with an empty HashMap + * + * @see #SubscriptionInitiator(Agent, ACLMessage, HashMap, HashMap) + **/ + public SubscriptionInitiator(Agent a, ACLMessage msg) { + this(a, msg, new HashMap<>(), new HashMap<>()); } - */ + + //#APIDOC_EXCLUDE_BEGIN /** * Construct a SubscriptionInitiator with a given HashMap @@ -318,8 +315,6 @@ public int onEnd() { registerState(b, CHECK_AGAIN); } - //#APIDOC_EXCLUDE_BEGIN - /** * This method is called internally by the framework and is not intended * to be called by the user @@ -328,7 +323,6 @@ protected List prepareInitiations(ACLMessage initiation) { return prepareSubscriptions(initiation); } - /** * Check whether a reply is in-sequence and update the appropriate Session. * This method is called internally by the framework and is not intended @@ -342,14 +336,17 @@ protected boolean checkInSequence(ACLMessage reply) { if (s.update(perf)) { // The reply is compliant to the protocol switch (s.getState()) { - case Session.POSITIVE_RESPONSE_RECEIVED, Session.NEGATIVE_RESPONSE_RECEIVED-> { + case Session.POSITIVE_RESPONSE_RECEIVED, Session.NEGATIVE_RESPONSE_RECEIVED -> { // The reply is a response var allRsp = getMapMessagesList().get(ALL_RESPONSES_KEY); allRsp.add(reply); } - case Session.NOTIFICATION_RECEIVED->{} - default -> {return false;} - // Something went wrong. Return false --> we will go to the HANDLE_OUT_OF_SEQ state + case Session.NOTIFICATION_RECEIVED -> { + } + default -> { + return false; + } + // Something went wrong. Return false --> we will go to the HANDLE_OUT_OF_SEQ state } // If the session is completed then remove it. if (s.isCompleted()) { @@ -413,8 +410,6 @@ protected int checkSessions(ACLMessage reply) { return ret; } - private String[] toBeReset = null; - /** * */ diff --git a/src/jade/proto/SubscriptionResponder.java b/src/jade/proto/SubscriptionResponder.java index 592adb1..d4c2e62 100644 --- a/src/jade/proto/SubscriptionResponder.java +++ b/src/jade/proto/SubscriptionResponder.java @@ -59,6 +59,12 @@ */ public class SubscriptionResponder extends FSMBehaviour implements FIPANames.InteractionProtocol { + // FSM states names + private static final String RECEIVE_SUBSCRIPTION = "Receive-subscription"; + private static final String HANDLE_SUBSCRIPTION = "Handle-subscription"; + private static final String HANDLE_CANCEL = "Handle-cancel"; + private static final String SEND_RESPONSE = "Send-response"; + private static final String SEND_NOTIFICATIONS = "Send-notifications"; /** * key to retrieve from the HashMap of the behaviour the ACLMessage * object sent by the initiator as a subscription. @@ -74,41 +80,18 @@ public class SubscriptionResponder extends FSMBehaviour implements FIPANames.Int * object sent as a response to the initiator. **/ public final String RESPONSE_KEY = "__response" + hashCode(); - - // FSM states names - private static final String RECEIVE_SUBSCRIPTION = "Receive-subscription"; - private static final String HANDLE_SUBSCRIPTION = "Handle-subscription"; - private static final String HANDLE_CANCEL = "Handle-cancel"; - private static final String SEND_RESPONSE = "Send-response"; - private static final String SEND_NOTIFICATIONS = "Send-notifications"; - // The MsgReceiver behaviour used to receive subscription messages private final MsgReceiver msgRecBehaviour; private final Hashtable subscriptions = new Hashtable<>(); private final List notifications = new ArrayList<>(); - + private final Logger myLogger = Logger.getJADELogger(getClass().getName()); /** * The SubscriptionManager used by this * SubscriptionResponder to register subscriptions */ protected SubscriptionManager mySubscriptionManager; - private final Logger myLogger = Logger.getJADELogger(getClass().getName()); - - /** - * This static method can be used - * to set the proper message Template (based on the performative of the - * subscription message) into the constructor of this behaviour. - * - * @param perf The performative of the subscription message - */ - public static MessageTemplate createMessageTemplate(int perf) { - return MessageTemplate.and( - MessageTemplate.MatchProtocol(FIPA_SUBSCRIBE), - MessageTemplate.or(MessageTemplate.MatchPerformative(perf), MessageTemplate.MatchPerformative(ACLMessage.CANCEL))); - } - /** * Construct a SubscriptionResponder behaviour that handles subscription messages matching a given template. * @@ -121,8 +104,8 @@ public SubscriptionResponder(Agent a, MessageTemplate mt) { /** * Construct a SubscriptionResponder behaviour that handles subscription messages matching a given template and * notifies a given SubscriptionManager about subscription/un-subscription events. - * - * see #SubscriptionResponder(Agent, MessageTemplate, SubscriptionManager, HashMap) + *

+ * see #SubscriptionResponder(Agent, MessageTemplate, SubscriptionManager, HashMap) **/ public SubscriptionResponder(Agent a, MessageTemplate mt, SubscriptionManager sm) { this(a, mt, sm, new HashMap<>(), new HashMap<>()); @@ -137,11 +120,13 @@ public SubscriptionResponder(Agent a, MessageTemplate mt, SubscriptionManager sm * subscription messages sent by the initiators. Take care that * if mt is null every message is consumed by this protocol. * @param sm The SubscriptionManager object that is notified about subscription/un-subscription events - * @param mapMessagesList the HashMap that will be used by protocol - * @deprecated - public SubscriptionResponder(Agent a, MessageTemplate mt, SubscriptionManager sm, HashMap> mapMessagesList) { + * @param mapMessagesList the HashMap of messages list that will be used by protocol + * @param mapMessages the HashMap of messages that will be used by protocol + **/ + public SubscriptionResponder(Agent a, MessageTemplate mt, SubscriptionManager sm, HashMap> mapMessagesList, HashMap mapMessages) { super(a); setMapMessagesList(mapMessagesList); + setMapMessages(mapMessages); mySubscriptionManager = sm; // Register the FSM transitions @@ -159,7 +144,7 @@ public SubscriptionResponder(Agent a, MessageTemplate mt, SubscriptionManager sm Behaviour b; // RECEIVE_SUBSCRIPTION - msgRecBehaviour = new MsgReceiver(myAgent, mt, MsgReceiver.INFINITE, getMapMessagesList(), SUBSCRIPTION_KEY); + msgRecBehaviour = new MsgReceiver(myAgent, mt, MsgReceiver.INFINITE, getMapMessagesList(), getMapMessages(), SUBSCRIPTION_KEY); registerFirstState(msgRecBehaviour, RECEIVE_SUBSCRIPTION); // HANDLE_SUBSCRIPTION @@ -178,6 +163,7 @@ public void action() { } }; b.setMapMessagesList(getMapMessagesList()); + b.setMapMessages(getMapMessages()); registerState(b, HANDLE_SUBSCRIPTION); // HANDLE_CANCEL @@ -195,10 +181,11 @@ public void action() { } }; b.setMapMessagesList(getMapMessagesList()); + b.setMapMessages(getMapMessages()); registerState(b, HANDLE_CANCEL); // SEND_RESPONSE - b = new ReplySender(myAgent, RESPONSE_KEY, SUBSCRIPTION_KEY, mapMessagesList, null); + b = new ReplySender(myAgent, RESPONSE_KEY, SUBSCRIPTION_KEY, mapMessagesList, mapMessages); registerState(b, SEND_RESPONSE); // SEND_NOTIFICATIONS @@ -207,11 +194,11 @@ public void action() { sendNotifications(); } }; - b.setMapMessagesList(getMapMessagesList()); + b.setMapMessagesList(mapMessagesList); + b.setMapMessages(mapMessages); registerState(b, SEND_NOTIFICATIONS); } // End of Constructor -*/ /** * Construct a SubscriptionResponder behaviour that handles subscription messages matching a given template, @@ -222,85 +209,93 @@ public void action() { * subscription messages sent by the initiators. Take care that * if mt is null every message is consumed by this protocol. * @param sm The SubscriptionManager object that is notified about subscription/un-subscription events - * @param mapMessagesList the HashMap of messages list that will be used by protocol - * @param mapMessages the HashMap of messages that will be used by protocol - **/ - public SubscriptionResponder(Agent a, MessageTemplate mt, SubscriptionManager sm, HashMap> mapMessagesList, HashMap mapMessages) { - super(a); - setMapMessagesList(mapMessagesList); - setMapMessages(mapMessages); - mySubscriptionManager = sm; - - // Register the FSM transitions - registerDefaultTransition(RECEIVE_SUBSCRIPTION, HANDLE_SUBSCRIPTION); - registerTransition(RECEIVE_SUBSCRIPTION, HANDLE_CANCEL, ACLMessage.CANCEL); - registerTransition(RECEIVE_SUBSCRIPTION, SEND_NOTIFICATIONS, MsgReceiver.INTERRUPTED); - registerDefaultTransition(HANDLE_SUBSCRIPTION, SEND_RESPONSE); - registerDefaultTransition(HANDLE_CANCEL, SEND_RESPONSE); - registerDefaultTransition(SEND_RESPONSE, RECEIVE_SUBSCRIPTION, new String[]{HANDLE_SUBSCRIPTION, HANDLE_CANCEL}); - registerDefaultTransition(SEND_NOTIFICATIONS, RECEIVE_SUBSCRIPTION); - - //*********************************************** - // For each state create and register a behaviour - //*********************************************** - Behaviour b; - - // RECEIVE_SUBSCRIPTION - msgRecBehaviour = new MsgReceiver(myAgent, mt, MsgReceiver.INFINITE, getMapMessagesList(), getMapMessages(), SUBSCRIPTION_KEY); - registerFirstState(msgRecBehaviour, RECEIVE_SUBSCRIPTION); - - // HANDLE_SUBSCRIPTION - b = new OneShotBehaviour(myAgent) { - - public void action() { - var ds = getMapMessages(); - ACLMessage subscription = ds.get(SUBSCRIPTION_KEY); - ACLMessage response; - try { - response = handleSubscription(subscription); - } catch (NotUnderstoodException | RefuseException nue) { - response = nue.getACLMessage(); - } - ds.put(RESPONSE_KEY, response); - } - }; - b.setMapMessagesList(getMapMessagesList()); - b.setMapMessages(getMapMessages()); - registerState(b, HANDLE_SUBSCRIPTION); - - // HANDLE_CANCEL - b = new OneShotBehaviour(myAgent) { - public void action() { - var ds = getMapMessages(); - ACLMessage cancel = ds.get(CANCEL_KEY); - ACLMessage response; - try { - response = handleCancel(cancel); - } catch (FailureException fe) { - response = fe.getACLMessage(); - } - ds.put(RESPONSE_KEY, response); - } - }; - b.setMapMessagesList(getMapMessagesList()); - b.setMapMessages(getMapMessages()); - registerState(b, HANDLE_CANCEL); - - // SEND_RESPONSE - b = new ReplySender(myAgent, RESPONSE_KEY, SUBSCRIPTION_KEY, mapMessagesList, mapMessages); - registerState(b, SEND_RESPONSE); - - // SEND_NOTIFICATIONS - b = new OneShotBehaviour(myAgent) { - public void action() { - sendNotifications(); - } - }; - b.setMapMessagesList(mapMessagesList); - b.setMapMessages(mapMessages); - registerState(b, SEND_NOTIFICATIONS); + * @param mapMessagesList the HashMap that will be used by protocol + * @deprecated public SubscriptionResponder(Agent a, MessageTemplate mt, SubscriptionManager sm, HashMap> mapMessagesList) { + super(a); + setMapMessagesList(mapMessagesList); + mySubscriptionManager = sm; + + // Register the FSM transitions + registerDefaultTransition(RECEIVE_SUBSCRIPTION, HANDLE_SUBSCRIPTION); + registerTransition(RECEIVE_SUBSCRIPTION, HANDLE_CANCEL, ACLMessage.CANCEL); + registerTransition(RECEIVE_SUBSCRIPTION, SEND_NOTIFICATIONS, MsgReceiver.INTERRUPTED); + registerDefaultTransition(HANDLE_SUBSCRIPTION, SEND_RESPONSE); + registerDefaultTransition(HANDLE_CANCEL, SEND_RESPONSE); + registerDefaultTransition(SEND_RESPONSE, RECEIVE_SUBSCRIPTION, new String[]{HANDLE_SUBSCRIPTION, HANDLE_CANCEL}); + registerDefaultTransition(SEND_NOTIFICATIONS, RECEIVE_SUBSCRIPTION); + + //*********************************************** + // For each state create and register a behaviour + //*********************************************** + Behaviour b; + + // RECEIVE_SUBSCRIPTION + msgRecBehaviour = new MsgReceiver(myAgent, mt, MsgReceiver.INFINITE, getMapMessagesList(), SUBSCRIPTION_KEY); + registerFirstState(msgRecBehaviour, RECEIVE_SUBSCRIPTION); + + // HANDLE_SUBSCRIPTION + b = new OneShotBehaviour(myAgent) { + + public void action() { + var ds = getMapMessages(); + ACLMessage subscription = ds.get(SUBSCRIPTION_KEY); + ACLMessage response; + try { + response = handleSubscription(subscription); + } catch (NotUnderstoodException | RefuseException nue) { + response = nue.getACLMessage(); + } + ds.put(RESPONSE_KEY, response); + } + }; + b.setMapMessagesList(getMapMessagesList()); + registerState(b, HANDLE_SUBSCRIPTION); + + // HANDLE_CANCEL + b = new OneShotBehaviour(myAgent) { + public void action() { + var ds = getMapMessages(); + ACLMessage cancel = ds.get(CANCEL_KEY); + ACLMessage response; + try { + response = handleCancel(cancel); + } catch (FailureException fe) { + response = fe.getACLMessage(); + } + ds.put(RESPONSE_KEY, response); + } + }; + b.setMapMessagesList(getMapMessagesList()); + registerState(b, HANDLE_CANCEL); + + // SEND_RESPONSE + b = new ReplySender(myAgent, RESPONSE_KEY, SUBSCRIPTION_KEY, mapMessagesList, null); + registerState(b, SEND_RESPONSE); + + // SEND_NOTIFICATIONS + b = new OneShotBehaviour(myAgent) { + public void action() { + sendNotifications(); + } + }; + b.setMapMessagesList(getMapMessagesList()); + registerState(b, SEND_NOTIFICATIONS); } // End of Constructor + */ + + /** + * This static method can be used + * to set the proper message Template (based on the performative of the + * subscription message) into the constructor of this behaviour. + * + * @param perf The performative of the subscription message + */ + public static MessageTemplate createMessageTemplate(int perf) { + return MessageTemplate.and( + MessageTemplate.MatchProtocol(FIPA_SUBSCRIBE), + MessageTemplate.or(MessageTemplate.MatchPerformative(perf), MessageTemplate.MatchPerformative(ACLMessage.CANCEL))); + } /** * Reset this behaviour diff --git a/src/jade/proto/TwoPh0Initiator.java b/src/jade/proto/TwoPh0Initiator.java index b03079b..a4d2538 100644 --- a/src/jade/proto/TwoPh0Initiator.java +++ b/src/jade/proto/TwoPh0Initiator.java @@ -43,6 +43,10 @@ public class TwoPh0Initiator extends Initiator { // Data store keys // Private data store keys (can't be static since if we register another instance of this class as state of the FSM // using the same data store the new values overrides the old one. + /* FSM states names */ + private static final String HANDLE_PROPOSE = "Handle-Propose"; + private static final String HANDLE_ALL_RESPONSES = "Handle-all-responses"; + private static final int ALL_RESPONSES_RECEIVED = 1; /** * key to retrieve from the HashMap of the behaviour the ACLMessage * object passed in the constructor of the class. @@ -74,31 +78,11 @@ public class TwoPh0Initiator extends Initiator { * CFP messages for which a response has not been received yet. */ public final String ALL_PENDINGS_KEY = "__all-pendings" + hashCode(); - - /* FSM states names */ - private static final String HANDLE_PROPOSE = "Handle-Propose"; - private static final String HANDLE_ALL_RESPONSES = "Handle-all-responses"; - - private static final int ALL_RESPONSES_RECEIVED = 1; - /* Data store output key */ private final String outputKey; private int totSessions; - - /** - * Constructs a TwoPh0Initiator behaviour. - * - * @param a The agent performing the protocol. - * @param cfp The message that must be used to initiate the protocol. - * Notice that the default implementation of the prepareCfps method - * returns an array composed of that message only. - * @param outputKey Data store key where the behaviour will store the Vector - * of messages to be sent to initiate the successive phase. - */ - public TwoPh0Initiator(Agent a, ACLMessage cfp, String outputKey) { - this(a, cfp, outputKey, new HashMap<>(), new HashMap<>()); - } + private String[] toBeReset = null; /** * Constructs a TwoPh0Initiator behaviour. @@ -113,45 +97,59 @@ public TwoPh0Initiator(Agent a, ACLMessage cfp, String outputKey) { * deprecated public TwoPh0Initiator(Agent a, ACLMessage cfp, String outputKey, HashMap> mapMessagesList) { - super(a, cfp, mapMessagesList); - //this.conversationId = conversationId; - this.outputKey = outputKey; - // Register the FSM transitions specific to the Two-Phase0-Commit protocol - registerTransition(CHECK_IN_SEQ, HANDLE_PROPOSE, ACLMessage.PROPOSE); - registerDefaultTransition(HANDLE_PROPOSE, CHECK_SESSIONS); - registerTransition(CHECK_SESSIONS, HANDLE_ALL_RESPONSES, ALL_RESPONSES_RECEIVED); // update1 - registerDefaultTransition(HANDLE_ALL_RESPONSES, DUMMY_FINAL); - - // Create and register the states specific to the Two-Phase0-Commit protocol - //Behaviour b; - - // HANDLE_PROPOSE - // This state is activated when a propose message is received as a reply - b = new OneShotBehaviour(myAgent) { - public void action() { - ACLMessage propose = getMapMessages().get(REPLY_KEY); - handlePropose(propose); - } - }; - b.setMapMessagesList(getMapMessagesList()); - registerState(b, HANDLE_PROPOSE); - - // HANDLE_ALL_RESPONSES - // This state is activated when all the responsess have been - // received or the specified timeout has expired. - b = new OneShotBehaviour(myAgent) { - public void action() { - var responses = getMapMessagesList().get(ALL_RESPONSES_KEY); - var proposes = getMapMessagesList().get(ALL_PROPOSES_KEY); - var pendings = getMapMessagesList().get(ALL_PENDINGS_KEY); - var nextPhMsgs = getMapMessagesList().get(TwoPh0Initiator.this.outputKey); - handleAllResponses(responses, proposes, pendings, nextPhMsgs); - } - }; - b.setMapMessagesList(getMapMessagesList()); - registerState(b, HANDLE_ALL_RESPONSES); + super(a, cfp, mapMessagesList); + //this.conversationId = conversationId; + this.outputKey = outputKey; + // Register the FSM transitions specific to the Two-Phase0-Commit protocol + registerTransition(CHECK_IN_SEQ, HANDLE_PROPOSE, ACLMessage.PROPOSE); + registerDefaultTransition(HANDLE_PROPOSE, CHECK_SESSIONS); + registerTransition(CHECK_SESSIONS, HANDLE_ALL_RESPONSES, ALL_RESPONSES_RECEIVED); // update1 + registerDefaultTransition(HANDLE_ALL_RESPONSES, DUMMY_FINAL); + + // Create and register the states specific to the Two-Phase0-Commit protocol + //Behaviour b; + + // HANDLE_PROPOSE + // This state is activated when a propose message is received as a reply + b = new OneShotBehaviour(myAgent) { + public void action() { + ACLMessage propose = getMapMessages().get(REPLY_KEY); + handlePropose(propose); + } + }; + b.setMapMessagesList(getMapMessagesList()); + registerState(b, HANDLE_PROPOSE); + + // HANDLE_ALL_RESPONSES + // This state is activated when all the responsess have been + // received or the specified timeout has expired. + b = new OneShotBehaviour(myAgent) { + public void action() { + var responses = getMapMessagesList().get(ALL_RESPONSES_KEY); + var proposes = getMapMessagesList().get(ALL_PROPOSES_KEY); + var pendings = getMapMessagesList().get(ALL_PENDINGS_KEY); + var nextPhMsgs = getMapMessagesList().get(TwoPh0Initiator.this.outputKey); + handleAllResponses(responses, proposes, pendings, nextPhMsgs); + } + }; + b.setMapMessagesList(getMapMessagesList()); + registerState(b, HANDLE_ALL_RESPONSES); }*/ + /** + * Constructs a TwoPh0Initiator behaviour. + * + * @param a The agent performing the protocol. + * @param cfp The message that must be used to initiate the protocol. + * Notice that the default implementation of the prepareCfps method + * returns an array composed of that message only. + * @param outputKey Data store key where the behaviour will store the Vector + * of messages to be sent to initiate the successive phase. + */ + public TwoPh0Initiator(Agent a, ACLMessage cfp, String outputKey) { + this(a, cfp, outputKey, new HashMap<>(), new HashMap<>()); + } + /** * Constructs a TwoPh0Initiator behaviour. * @@ -216,8 +214,6 @@ public int onEnd() { } } - private String[] toBeReset = null; - /* User can override these methods */ /** @@ -486,9 +482,8 @@ class Session implements ProtocolSession, Serializable { // Session states static final int INIT = 0; static final int REPLY_RECEIVED = 1; - - private int state = INIT; private final String myId; + private int state = INIT; public Session(String id) { myId = id; diff --git a/src/jade/proto/TwoPh1Initiator.java b/src/jade/proto/TwoPh1Initiator.java index a582a2c..539aa11 100644 --- a/src/jade/proto/TwoPh1Initiator.java +++ b/src/jade/proto/TwoPh1Initiator.java @@ -43,6 +43,12 @@ public class TwoPh1Initiator extends Initiator { // Data store keys // Private data store keys (can't be static since if we register another instance of this class as state of the FSM // using the same data store the new values overrides the old one. + /* FSM states names */ + private static final String HANDLE_CONFIRM = "Handle-Confirm"; + private static final String HANDLE_DISCONFIRM = "Handle-Disconfirm"; + private static final String HANDLE_INFORM = "Handle-Inform"; + private static final String HANDLE_ALL_RESPONSES = "Handle-all-responses"; + private static final int ALL_RESPONSES_RECEIVED = 1; /** * key to retrieve from the HashMap of the behaviour the ACLMessage * object passed in the constructor of the class. @@ -84,21 +90,98 @@ public class TwoPh1Initiator extends Initiator { * QUERY_IF messages for which a response has not been received yet. */ public final String ALL_PENDINGS_KEY = "__all-pendings" + hashCode(); - - /* FSM states names */ - private static final String HANDLE_CONFIRM = "Handle-Confirm"; - private static final String HANDLE_DISCONFIRM = "Handle-Disconfirm"; - private static final String HANDLE_INFORM = "Handle-Inform"; - private static final String HANDLE_ALL_RESPONSES = "Handle-all-responses"; - - private static final int ALL_RESPONSES_RECEIVED = 1; - /* Data store output key */ private final String outputKey; private int totSessions; + private String[] toBeReset = null; + /** + * Constructs a TwoPh1Initiator behaviour. + * + * @param a The agent performing the protocol. + * @param queryIf msg + * @param outputKey Data store key where the behaviour prepares a vector of + * messages which will be send by a TwoPh2Initiator behaviour. + * If phase 1 ends with all confirm or inform than messages prepared are + * accept-proposal, otherwise they are reject-proposal. + * @param mapMessagesList HashMap of messages list that will be used by this TwoPh1Initiator. + * deprecated + public TwoPh1Initiator(Agent a, ACLMessage queryIf, String outputKey, HashMap> mapMessagesList) { + super(a, queryIf, mapMessagesList); + //this.inputKey = inputKey; + this.outputKey = outputKey; + //Register the FSM transitions specific to the Two-Phase1-Commit protocol + registerTransition(CHECK_IN_SEQ, HANDLE_CONFIRM, ACLMessage.CONFIRM); + registerTransition(CHECK_IN_SEQ, HANDLE_DISCONFIRM, ACLMessage.DISCONFIRM); + registerTransition(CHECK_IN_SEQ, HANDLE_INFORM, ACLMessage.INFORM); + registerDefaultTransition(HANDLE_CONFIRM, CHECK_SESSIONS); + registerDefaultTransition(HANDLE_DISCONFIRM, CHECK_SESSIONS); + registerDefaultTransition(HANDLE_INFORM, CHECK_SESSIONS); + registerTransition(CHECK_SESSIONS, HANDLE_ALL_RESPONSES, ALL_RESPONSES_RECEIVED); + /* + registerTransition(CHECK_SESSIONS, HANDLE_ALL_RESPONSES, SOME_DISCONFIRM); + registerTransition(CHECK_SESSIONS, HANDLE_ALL_RESPONSES, PH1_TIMEOUT_EXPIRED); + registerTransition(CHECK_SESSIONS, HANDLE_ALL_RESPONSES, ALL_CONFIRM_OR_INFORM); + registerDefaultTransition(HANDLE_ALL_RESPONSES, DUMMY_FINAL); + + + // Create and register the states specific to the Two-Phase1-Commit protocol + Behaviour b; + + // HANDLE_CONFIRM state activated if arrived a confirm message compliant with conversationId and a receiver of one of queryIf messages sent. + b = new OneShotBehaviour(myAgent) { + public void action() { + ACLMessage confirm = getMapMessages().get(REPLY_KEY); + handleConfirm(confirm); + } + }; + b.setMapMessagesList(getMapMessagesList()); + registerState(b, HANDLE_CONFIRM); + + // HANDLE_DISCONFIRM state activated if arrived a disconfirm message + //compliant with conversationId and a receiver of one of queryIf messages + //sent. + b = new OneShotBehaviour(myAgent) { + public void action() { + ACLMessage disconfirm = getMapMessages().get(REPLY_KEY); + handleDisconfirm(disconfirm); + } + }; + b.setMapMessagesList(getMapMessagesList()); + registerState(b, HANDLE_DISCONFIRM); + + // HANDLE_INFORM state activated if arrived an inform message + //compliant with conversationId and a receiver of one of queryIf messages + //sent. + b = new OneShotBehaviour(myAgent) { + public void action() { + ACLMessage inform = getMapMessages().get(REPLY_KEY); + handleInform(inform); + } + }; + b.setMapMessagesList(getMapMessagesList()); + registerState(b, HANDLE_INFORM); + + // HANDLE_ALL_RESPONSES state activated when timeout is expired or + //all the answers have been received. + b = new OneShotBehaviour(myAgent) { + public void action() { + var responses = getMapMessagesList().get(ALL_RESPONSES_KEY); + var confirms = getMapMessagesList().get(ALL_CONFIRMS_KEY); + var disconfirms = getMapMessagesList().get(ALL_DISCONFIRMS_KEY); + var informs = getMapMessagesList().get(ALL_INFORMS_KEY); + var pendings = getMapMessagesList().get(ALL_PENDINGS_KEY); + var nextPhMsgs = getMapMessagesList().get(TwoPh1Initiator.this.outputKey); + handleAllResponses(responses, confirms, disconfirms, informs, + pendings, nextPhMsgs); + } + }; + b.setMapMessagesList(getMapMessagesList()); + registerState(b, HANDLE_ALL_RESPONSES); + } + */ /** * Constructs a TwoPh1Initiator behaviour. * @@ -113,92 +196,6 @@ public TwoPh1Initiator(Agent a, ACLMessage queryIf, String outputKey) { this(a, queryIf, outputKey, new HashMap<>(), new HashMap<>()); } - /** - * Constructs a TwoPh1Initiator behaviour. - * - * @param a The agent performing the protocol. - * @param queryIf msg - * @param outputKey Data store key where the behaviour prepares a vector of - * messages which will be send by a TwoPh2Initiator behaviour. - * If phase 1 ends with all confirm or inform than messages prepared are - * accept-proposal, otherwise they are reject-proposal. - * @param mapMessagesList HashMap of messages list that will be used by this TwoPh1Initiator. - * deprecated - - public TwoPh1Initiator(Agent a, ACLMessage queryIf, String outputKey, HashMap> mapMessagesList) { - super(a, queryIf, mapMessagesList); - //this.inputKey = inputKey; - this.outputKey = outputKey; - //Register the FSM transitions specific to the Two-Phase1-Commit protocol - registerTransition(CHECK_IN_SEQ, HANDLE_CONFIRM, ACLMessage.CONFIRM); - registerTransition(CHECK_IN_SEQ, HANDLE_DISCONFIRM, ACLMessage.DISCONFIRM); - registerTransition(CHECK_IN_SEQ, HANDLE_INFORM, ACLMessage.INFORM); - registerDefaultTransition(HANDLE_CONFIRM, CHECK_SESSIONS); - registerDefaultTransition(HANDLE_DISCONFIRM, CHECK_SESSIONS); - registerDefaultTransition(HANDLE_INFORM, CHECK_SESSIONS); - registerTransition(CHECK_SESSIONS, HANDLE_ALL_RESPONSES, ALL_RESPONSES_RECEIVED); - /* - registerTransition(CHECK_SESSIONS, HANDLE_ALL_RESPONSES, SOME_DISCONFIRM); - registerTransition(CHECK_SESSIONS, HANDLE_ALL_RESPONSES, PH1_TIMEOUT_EXPIRED); - registerTransition(CHECK_SESSIONS, HANDLE_ALL_RESPONSES, ALL_CONFIRM_OR_INFORM); - registerDefaultTransition(HANDLE_ALL_RESPONSES, DUMMY_FINAL); - - - // Create and register the states specific to the Two-Phase1-Commit protocol - Behaviour b; - - // HANDLE_CONFIRM state activated if arrived a confirm message compliant with conversationId and a receiver of one of queryIf messages sent. - b = new OneShotBehaviour(myAgent) { - public void action() { - ACLMessage confirm = getMapMessages().get(REPLY_KEY); - handleConfirm(confirm); - } - }; - b.setMapMessagesList(getMapMessagesList()); - registerState(b, HANDLE_CONFIRM); - - // HANDLE_DISCONFIRM state activated if arrived a disconfirm message - //compliant with conversationId and a receiver of one of queryIf messages - //sent. - b = new OneShotBehaviour(myAgent) { - public void action() { - ACLMessage disconfirm = getMapMessages().get(REPLY_KEY); - handleDisconfirm(disconfirm); - } - }; - b.setMapMessagesList(getMapMessagesList()); - registerState(b, HANDLE_DISCONFIRM); - - // HANDLE_INFORM state activated if arrived an inform message - //compliant with conversationId and a receiver of one of queryIf messages - //sent. - b = new OneShotBehaviour(myAgent) { - public void action() { - ACLMessage inform = getMapMessages().get(REPLY_KEY); - handleInform(inform); - } - }; - b.setMapMessagesList(getMapMessagesList()); - registerState(b, HANDLE_INFORM); - - // HANDLE_ALL_RESPONSES state activated when timeout is expired or - //all the answers have been received. - b = new OneShotBehaviour(myAgent) { - public void action() { - var responses = getMapMessagesList().get(ALL_RESPONSES_KEY); - var confirms = getMapMessagesList().get(ALL_CONFIRMS_KEY); - var disconfirms = getMapMessagesList().get(ALL_DISCONFIRMS_KEY); - var informs = getMapMessagesList().get(ALL_INFORMS_KEY); - var pendings = getMapMessagesList().get(ALL_PENDINGS_KEY); - var nextPhMsgs = getMapMessagesList().get(TwoPh1Initiator.this.outputKey); - handleAllResponses(responses, confirms, disconfirms, informs, - pendings, nextPhMsgs); - } - }; - b.setMapMessagesList(getMapMessagesList()); - registerState(b, HANDLE_ALL_RESPONSES); - } -*/ /** * Constructs a TwoPh1Initiator behaviour. * @@ -300,8 +297,6 @@ public int onEnd() { } } - private String[] toBeReset = null; - /* User can override these methods */ /** @@ -619,9 +614,8 @@ class Session implements ProtocolSession, Serializable { // Session states static final int INIT = 0; static final int REPLY_RECEIVED = 1; - - private int state = INIT; private final String myId; + private int state = INIT; public Session(String id) { myId = id; diff --git a/src/jade/proto/TwoPh2Initiator.java b/src/jade/proto/TwoPh2Initiator.java index 8600ae8..eccc11f 100644 --- a/src/jade/proto/TwoPh2Initiator.java +++ b/src/jade/proto/TwoPh2Initiator.java @@ -43,6 +43,13 @@ public class TwoPh2Initiator extends Initiator { // Data store keys // Private data store keys (can't be static since if we register another instance of this class as state of the FSM // using the same data store the new values overrides the old one. + /* FSM states names */ + private static final String HANDLE_INFORM = "Handle-Inform"; + private static final String HANDLE_OLD_RESPONSE = "Handle-old-response"; + private static final String HANDLE_ALL_RESPONSES = "Handle-all-responses"; + /* Possible TwoPh2Initiator's returned values */ + private static final int OLD_RESPONSE = 1000; + private static final int ALL_RESPONSES_RECEIVED = 1; /** * key to retrieve from the HashMap of the behaviour the ACLMessage * object passed in the constructor of the class. @@ -75,25 +82,7 @@ public class TwoPh2Initiator extends Initiator { * has not been received yet. */ public final String ALL_PENDINGS_KEY = "__all-pendings" + hashCode(); - - /* FSM states names */ - private static final String HANDLE_INFORM = "Handle-Inform"; - private static final String HANDLE_OLD_RESPONSE = "Handle-old-response"; - private static final String HANDLE_ALL_RESPONSES = "Handle-all-responses"; - /* Possible TwoPh2Initiator's returned values */ - private static final int OLD_RESPONSE = 1000; - private static final int ALL_RESPONSES_RECEIVED = 1; - - - /** - * Constructs a TwoPh2Initiator behaviour. - * - * @param a The agent performing the protocol. - * @param acceptance msg - */ - public TwoPh2Initiator(Agent a, ACLMessage acceptance) { - this(a, acceptance, new HashMap<>(), new HashMap<>()); - } + private String[] toBeReset = null; /** * Constructs a TwoPh2Initiator behaviour. @@ -104,86 +93,98 @@ public TwoPh2Initiator(Agent a, ACLMessage acceptance) { * deprecated public TwoPh2Initiator(Agent a, ACLMessage acceptance, HashMap> mapMessagesList) { - super(a, acceptance, mapMessagesList); - // Register the FSM transitions specific to the Two-Phase2-Commit protocol - registerTransition(CHECK_IN_SEQ, HANDLE_INFORM, ACLMessage.INFORM); - registerTransition(CHECK_IN_SEQ, HANDLE_OLD_RESPONSE, OLD_RESPONSE); - registerDefaultTransition(HANDLE_INFORM, CHECK_SESSIONS); - registerDefaultTransition(HANDLE_OLD_RESPONSE, CHECK_SESSIONS); - registerTransition(CHECK_SESSIONS, HANDLE_ALL_RESPONSES, ALL_RESPONSES_RECEIVED); - registerDefaultTransition(HANDLE_ALL_RESPONSES, DUMMY_FINAL); - - // Create and register the states specific to the Two-Phase2-Commit protocol - Behaviour b; - - // CHECK_IN_SEQ - // We must override this state to distinguish the case in which - // a response belonging to a previous phase is received (e.g. due - // to network delay). - b = new OneShotBehaviour(myAgent) { - int ret; - - public void action() { - ACLMessage reply = (ACLMessage) getMapMessagesList().get(REPLY_K); - String inReplyTo = reply.getInReplyTo(); - String phase = inReplyTo.substring(inReplyTo.length() - 3); - if (phase.equals(TwoPhConstants.PH0) || phase.equals(TwoPhConstants.PH1)) { - // The reply belongs to a previous phase - oldResponse(reply); - ret = OLD_RESPONSE; - } else { - if (checkInSequence(reply)) { - ret = reply.getPerformative(); - } else { - ret = -1; - } - } - } - - public int onEnd() { - return ret; - } - }; - b.setMapMessagesList(getMapMessagesList()); - registerState(b, CHECK_IN_SEQ); - - // HANDLE_INFORM state activated if arrived an inform message compliant with - //conversationId and a receiver of one of accept/reject-proposal messages sent. - b = new OneShotBehaviour(myAgent) { - final int ret = -1; - - public void action() { - ACLMessage inform = (ACLMessage) (getMapMessagesList().get(REPLY_KEY)); - handleInform(inform); - } - }; - b.setMapMessagesList(getMapMessagesList()); - registerState(b, HANDLE_INFORM); + super(a, acceptance, mapMessagesList); + // Register the FSM transitions specific to the Two-Phase2-Commit protocol + registerTransition(CHECK_IN_SEQ, HANDLE_INFORM, ACLMessage.INFORM); + registerTransition(CHECK_IN_SEQ, HANDLE_OLD_RESPONSE, OLD_RESPONSE); + registerDefaultTransition(HANDLE_INFORM, CHECK_SESSIONS); + registerDefaultTransition(HANDLE_OLD_RESPONSE, CHECK_SESSIONS); + registerTransition(CHECK_SESSIONS, HANDLE_ALL_RESPONSES, ALL_RESPONSES_RECEIVED); + registerDefaultTransition(HANDLE_ALL_RESPONSES, DUMMY_FINAL); + + // Create and register the states specific to the Two-Phase2-Commit protocol + Behaviour b; + + // CHECK_IN_SEQ + // We must override this state to distinguish the case in which + // a response belonging to a previous phase is received (e.g. due + // to network delay). + b = new OneShotBehaviour(myAgent) { + int ret; + + public void action() { + ACLMessage reply = (ACLMessage) getMapMessagesList().get(REPLY_K); + String inReplyTo = reply.getInReplyTo(); + String phase = inReplyTo.substring(inReplyTo.length() - 3); + if (phase.equals(TwoPhConstants.PH0) || phase.equals(TwoPhConstants.PH1)) { + // The reply belongs to a previous phase + oldResponse(reply); + ret = OLD_RESPONSE; + } else { + if (checkInSequence(reply)) { + ret = reply.getPerformative(); + } else { + ret = -1; + } + } + } - // HANDLE_OLD_RESPONSE state activate if arrived a failure message coming - //from phase 0 (timeout expired), a disconfirm or inform message coming from phase 1 - //(timeout expired). - b = new OneShotBehaviour(myAgent) { - public void action() { - ACLMessage old = (ACLMessage) (getMapMessagesList().get(REPLY_KEY)); - handleOldResponse(old); - } - }; - b.setMapMessagesList(getMapMessagesList()); - registerState(b, HANDLE_OLD_RESPONSE); + public int onEnd() { + return ret; + } + }; + b.setMapMessagesList(getMapMessagesList()); + registerState(b, CHECK_IN_SEQ); + + // HANDLE_INFORM state activated if arrived an inform message compliant with + //conversationId and a receiver of one of accept/reject-proposal messages sent. + b = new OneShotBehaviour(myAgent) { + final int ret = -1; + + public void action() { + ACLMessage inform = (ACLMessage) (getMapMessagesList().get(REPLY_KEY)); + handleInform(inform); + } + }; + b.setMapMessagesList(getMapMessagesList()); + registerState(b, HANDLE_INFORM); + + // HANDLE_OLD_RESPONSE state activate if arrived a failure message coming + //from phase 0 (timeout expired), a disconfirm or inform message coming from phase 1 + //(timeout expired). + b = new OneShotBehaviour(myAgent) { + public void action() { + ACLMessage old = (ACLMessage) (getMapMessagesList().get(REPLY_KEY)); + handleOldResponse(old); + } + }; + b.setMapMessagesList(getMapMessagesList()); + registerState(b, HANDLE_OLD_RESPONSE); + + // HANDLE_ALL_RESPONSES state activated when all the answers have been received. + b = new OneShotBehaviour(myAgent) { + public void action() { + var responses = getMapMessagesList().get(ALL_RESPONSES_KEY); + handleAllResponses(responses); + } + }; + b.setMapMessagesList(getMapMessagesList()); + registerState(b, HANDLE_ALL_RESPONSES); - // HANDLE_ALL_RESPONSES state activated when all the answers have been received. - b = new OneShotBehaviour(myAgent) { - public void action() { - var responses = getMapMessagesList().get(ALL_RESPONSES_KEY); - handleAllResponses(responses); - } - }; - b.setMapMessagesList(getMapMessagesList()); - registerState(b, HANDLE_ALL_RESPONSES); + } + */ + /** + * Constructs a TwoPh2Initiator behaviour. + * + * @param a The agent performing the protocol. + * @param acceptance msg + */ + public TwoPh2Initiator(Agent a, ACLMessage acceptance) { + this(a, acceptance, new HashMap<>(), new HashMap<>()); } - */ + + /* User can override these methods */ /** * Constructs a TwoPh2Initiator behaviour. @@ -278,8 +279,6 @@ public void action() { } - /* User can override these methods */ - /** * This method must return the vector of ACLMessage objects to be sent. * It is called in the first state of this protocol. This default @@ -381,6 +380,9 @@ public void registerHandleOldResponse(Behaviour b) { b.setMapMessagesList(getMapMessagesList()); } + /* User CAN'T override these methods */ + //#APIDOC_EXCLUDE_BEGIN + /** * This method allows to register a user defined Behaviour in the * HANDLE_ALL_RESPONSES state. This behaviour would override the homonymous method. @@ -396,11 +398,6 @@ public void registerHandleAllResponses(Behaviour b) { b.setMapMessagesList(getMapMessagesList()); } - /* User CAN'T override these methods */ - //#APIDOC_EXCLUDE_BEGIN - - private String[] toBeReset = null; - /** * */ @@ -535,9 +532,8 @@ class Session implements ProtocolSession, Serializable { // Possible Session states static final int INIT = 0; static final int REPLY_RECEIVED = 1; - - private int state = INIT; private final String myId; + private int state = INIT; public Session(String id) { myId = id; diff --git a/src/jade/proto/TwoPhInitiator.java b/src/jade/proto/TwoPhInitiator.java index 6ac5b8a..bb59799 100644 --- a/src/jade/proto/TwoPhInitiator.java +++ b/src/jade/proto/TwoPhInitiator.java @@ -73,142 +73,142 @@ public TwoPhInitiator(Agent a, ACLMessage cfp) { * deprecated public TwoPhInitiator(Agent a, ACLMessage cfp, HashMap> mapMessagesList) { - super(a); - setMapMessagesList(mapMessagesList); - // Register the FSM transitions specific to the Two-Phase-Commit protocol - registerTransition(PH0_STATE, PH1_STATE, ACLMessage.QUERY_IF); - registerTransition(PH0_STATE, PH2_STATE, ACLMessage.REJECT_PROPOSAL); - registerTransition(PH0_STATE, DUMMY_FINAL, -1); - registerTransition(PH0_STATE, PH0_STATE, ACLMessage.CFP, new String[]{PH0_STATE}); - - registerTransition(PH1_STATE, PH2_STATE, ACLMessage.ACCEPT_PROPOSAL); - registerTransition(PH1_STATE, PH2_STATE, ACLMessage.REJECT_PROPOSAL); - registerTransition(PH1_STATE, DUMMY_FINAL, -1); // fix - - // Create and register the states specific to the Two-Phase-Commit protocol - Behaviour b; - - // PH0_STATE activated for the first time. It sends cfps messages and wait - // for a propose (operation completed), a failure (operation failed) or - // expiration of timeout. - b = new TwoPh0Initiator(myAgent, cfp, TEMP, mapMessagesList) { - - protected List prepareCfps(ACLMessage cfp) { - return TwoPhInitiator.this.prepareCfps(cfp); - } - - protected void handlePropose(ACLMessage propose) { - TwoPhInitiator.this.handlePropose(propose); - } + super(a); + setMapMessagesList(mapMessagesList); + // Register the FSM transitions specific to the Two-Phase-Commit protocol + registerTransition(PH0_STATE, PH1_STATE, ACLMessage.QUERY_IF); + registerTransition(PH0_STATE, PH2_STATE, ACLMessage.REJECT_PROPOSAL); + registerTransition(PH0_STATE, DUMMY_FINAL, -1); + registerTransition(PH0_STATE, PH0_STATE, ACLMessage.CFP, new String[]{PH0_STATE}); + + registerTransition(PH1_STATE, PH2_STATE, ACLMessage.ACCEPT_PROPOSAL); + registerTransition(PH1_STATE, PH2_STATE, ACLMessage.REJECT_PROPOSAL); + registerTransition(PH1_STATE, DUMMY_FINAL, -1); // fix + + // Create and register the states specific to the Two-Phase-Commit protocol + Behaviour b; + + // PH0_STATE activated for the first time. It sends cfps messages and wait + // for a propose (operation completed), a failure (operation failed) or + // expiration of timeout. + b = new TwoPh0Initiator(myAgent, cfp, TEMP, mapMessagesList) { - protected void handleFailure(ACLMessage failure) { - TwoPhInitiator.this.handleFailure(failure); - } + protected List prepareCfps(ACLMessage cfp) { + return TwoPhInitiator.this.prepareCfps(cfp); + } - protected void handleNotUnderstood(ACLMessage notUnderstood) { - TwoPhInitiator.this.handleNotUnderstood(notUnderstood); - } + protected void handlePropose(ACLMessage propose) { + TwoPhInitiator.this.handlePropose(propose); + } - protected void handleOutOfSequence(ACLMessage msg) { - TwoPhInitiator.this.handleOutOfSequence(msg); - } + protected void handleFailure(ACLMessage failure) { + TwoPhInitiator.this.handleFailure(failure); + } - protected void handleAllResponses(List responses, List proposes, List pendings, List nextPhMsgs) { - TwoPhInitiator.this.handleAllPh0Responses(responses, proposes, pendings, nextPhMsgs); - } - }; - registerFirstState(b, PH0_STATE); + protected void handleNotUnderstood(ACLMessage notUnderstood) { + TwoPhInitiator.this.handleNotUnderstood(notUnderstood); + } - // PH1_STATE activated if phase 0 succeded (all propose in phase 0). It - // sends queryIf messages and wait for a confirm (receiver prepared), a - // disconfirm (receiver aborted), an inform (receiver not changed) or - // expiration of timeout. - b = new TwoPh1Initiator(myAgent, null, TEMP, mapMessagesList) { - protected void initializeHashMap(ACLMessage msg) { - // Use the QUERY_IF messages prepared in previous phase - var v = getMapMessagesList().get(TEMP); - getMapMessagesList().put(ALL_QUERYIFS_KEY, v); - super.initializeHashMap(msg); - } + protected void handleOutOfSequence(ACLMessage msg) { + TwoPhInitiator.this.handleOutOfSequence(msg); + } - protected void handleConfirm(ACLMessage confirm) { - TwoPhInitiator.this.handleConfirm(confirm); - } + protected void handleAllResponses(List responses, List proposes, List pendings, List nextPhMsgs) { + TwoPhInitiator.this.handleAllPh0Responses(responses, proposes, pendings, nextPhMsgs); + } + }; + registerFirstState(b, PH0_STATE); + + // PH1_STATE activated if phase 0 succeded (all propose in phase 0). It + // sends queryIf messages and wait for a confirm (receiver prepared), a + // disconfirm (receiver aborted), an inform (receiver not changed) or + // expiration of timeout. + b = new TwoPh1Initiator(myAgent, null, TEMP, mapMessagesList) { + protected void initializeHashMap(ACLMessage msg) { + // Use the QUERY_IF messages prepared in previous phase + var v = getMapMessagesList().get(TEMP); + getMapMessagesList().put(ALL_QUERYIFS_KEY, v); + super.initializeHashMap(msg); + } - protected void handleDisconfirm(ACLMessage disconfirm) { - TwoPhInitiator.this.handleDisconfirm(disconfirm); - } + protected void handleConfirm(ACLMessage confirm) { + TwoPhInitiator.this.handleConfirm(confirm); + } - protected void handleInform(ACLMessage inform) { - TwoPhInitiator.this.handlePh1Inform(inform); - } + protected void handleDisconfirm(ACLMessage disconfirm) { + TwoPhInitiator.this.handleDisconfirm(disconfirm); + } - protected void handleFailure(ACLMessage failure) { - TwoPhInitiator.this.handleFailure(failure); - } + protected void handleInform(ACLMessage inform) { + TwoPhInitiator.this.handlePh1Inform(inform); + } - protected void handleNotUnderstood(ACLMessage notUnderstood) { - TwoPhInitiator.this.handleNotUnderstood(notUnderstood); - } + protected void handleFailure(ACLMessage failure) { + TwoPhInitiator.this.handleFailure(failure); + } - protected void handleOutOfSequence(ACLMessage msg) { - TwoPhInitiator.this.handleOutOfSequence(msg); - } + protected void handleNotUnderstood(ACLMessage notUnderstood) { + TwoPhInitiator.this.handleNotUnderstood(notUnderstood); + } - protected void handleAllResponses(List responses, List confirms, List disconfirms, - List informs, List pendings, List nextPhMsgs) { - TwoPhInitiator.this.handleAllPh1Responses(responses, confirms, disconfirms, informs, pendings, nextPhMsgs); - } - }; - registerState(b, PH1_STATE); + protected void handleOutOfSequence(ACLMessage msg) { + TwoPhInitiator.this.handleOutOfSequence(msg); + } - // PH2_STATE activated when phase 0 fails (some failure or expiration - // of timeout), phase 1 fails (some disconfirm or expiration of timeout) or - // phase 1 succeds (no disconfirms). In the first and third case it sends - // reject-proposal; in the second case it sends accept-proposal. - b = new TwoPh2Initiator(myAgent, null, mapMessagesList) { - protected void initializeHashMap(ACLMessage msg) { - // Use the acceptance messages prepared in previous phase - var v = getMapMessagesList().get(TEMP); - getMapMessagesList().put(ALL_ACCEPTANCES_KEY, v); - super.initializeHashMap(msg); - } + protected void handleAllResponses(List responses, List confirms, List disconfirms, + List informs, List pendings, List nextPhMsgs) { + TwoPhInitiator.this.handleAllPh1Responses(responses, confirms, disconfirms, informs, pendings, nextPhMsgs); + } + }; + registerState(b, PH1_STATE); + + // PH2_STATE activated when phase 0 fails (some failure or expiration + // of timeout), phase 1 fails (some disconfirm or expiration of timeout) or + // phase 1 succeds (no disconfirms). In the first and third case it sends + // reject-proposal; in the second case it sends accept-proposal. + b = new TwoPh2Initiator(myAgent, null, mapMessagesList) { + protected void initializeHashMap(ACLMessage msg) { + // Use the acceptance messages prepared in previous phase + var v = getMapMessagesList().get(TEMP); + getMapMessagesList().put(ALL_ACCEPTANCES_KEY, v); + super.initializeHashMap(msg); + } - protected void handleInform(ACLMessage inform) { - TwoPhInitiator.this.handlePh2Inform(inform); - } + protected void handleInform(ACLMessage inform) { + TwoPhInitiator.this.handlePh2Inform(inform); + } - protected void handleOldResponse(ACLMessage old) { - TwoPhInitiator.this.handleOldResponse(old); - } + protected void handleOldResponse(ACLMessage old) { + TwoPhInitiator.this.handleOldResponse(old); + } - protected void handleFailure(ACLMessage failure) { - TwoPhInitiator.this.handleFailure(failure); - } + protected void handleFailure(ACLMessage failure) { + TwoPhInitiator.this.handleFailure(failure); + } - protected void handleNotUnderstood(ACLMessage notUnderstood) { - TwoPhInitiator.this.handleNotUnderstood(notUnderstood); - } + protected void handleNotUnderstood(ACLMessage notUnderstood) { + TwoPhInitiator.this.handleNotUnderstood(notUnderstood); + } - protected void handleOutOfSequence(ACLMessage msg) { - TwoPhInitiator.this.handleOutOfSequence(msg); - } + protected void handleOutOfSequence(ACLMessage msg) { + TwoPhInitiator.this.handleOutOfSequence(msg); + } - protected void handleAllResponses(List responses) { - TwoPhInitiator.this.handleAllPh2Responses(responses); - } - }; - registerLastState(b, PH2_STATE); + protected void handleAllResponses(List responses) { + TwoPhInitiator.this.handleAllPh2Responses(responses); + } + }; + registerLastState(b, PH2_STATE); - // DUMMY_FINAL - b = new OneShotBehaviour(myAgent) { - public void action() { - } - }; - b.setMapMessagesList(getMapMessagesList()); - registerLastState(b, DUMMY_FINAL); + // DUMMY_FINAL + b = new OneShotBehaviour(myAgent) { + public void action() { } -*/ + }; + b.setMapMessagesList(getMapMessagesList()); + registerLastState(b, DUMMY_FINAL); + } + */ /** * Constructs a TwoPhInitiator behaviour. * diff --git a/src/jade/proto/TwoPhResponder.java b/src/jade/proto/TwoPhResponder.java index 3e24f54..bc42e2a 100644 --- a/src/jade/proto/TwoPhResponder.java +++ b/src/jade/proto/TwoPhResponder.java @@ -242,6 +242,17 @@ public void action() { registerState(b, HANDLE_REJECT_PROPOSAL); } + /** + * This static method can be used to set the proper message Template + * (based on the interaction protocol and the performative) to be passed to the constructor of this behaviour. + * + * @see jade.domain.FIPANames.InteractionProtocol + **/ + public static MessageTemplate createMessageTemplate() { + return MessageTemplate.and(MessageTemplate.MatchProtocol(TwoPhConstants.JADE_TWO_PHASE_COMMIT), + MessageTemplate.MatchPerformative(ACLMessage.CFP)); + } + /** * This method is called when the initiator's * message is received that matches the message template @@ -352,6 +363,8 @@ public void registerHandleRejectProposal(Behaviour b) { registerDSState(b, HANDLE_REJECT_PROPOSAL); } + /**todo@ Da rivedere il createMessageTemplate E I COMMENTI!!!! */ + /** * This method allows to register a user defined Behaviour * in the HANDLE_ACCEPTANCE state. This behaviour would override the homonymous @@ -366,18 +379,6 @@ public void registerHandleAcceptProposal(Behaviour b) { registerDSState(b, HANDLE_ACCEPT_PROPOSAL); } - /**todo@ Da rivedere il createMessageTemplate E I COMMENTI!!!! */ - /** - * This static method can be used to set the proper message Template - * (based on the interaction protocol and the performative) to be passed to the constructor of this behaviour. - * - * @see jade.domain.FIPANames.InteractionProtocol - **/ - public static MessageTemplate createMessageTemplate() { - return MessageTemplate.and(MessageTemplate.MatchProtocol(TwoPhConstants.JADE_TWO_PHASE_COMMIT), - MessageTemplate.MatchPerformative(ACLMessage.CFP)); - } - public void reset() { super.reset(); phase = 0; diff --git a/src/jade/proto/states/HandlerSelector.java b/src/jade/proto/states/HandlerSelector.java index 3b17626..09a703d 100644 --- a/src/jade/proto/states/HandlerSelector.java +++ b/src/jade/proto/states/HandlerSelector.java @@ -44,15 +44,6 @@ * @version $Date: 2005-09-16 15:54:46 +0200 (ven, 16 set 2005) $ $Revision: 5780 $ **/ public abstract class HandlerSelector extends FSMBehaviour { - private final Map handlers = new HashMap<>(); - private final Object accesKey; - - // FSM states names - private static final String SELECT = "Select"; - private static final String HANDLE = "Handle"; - private static final String DUMMY = "Dummy"; - - // States exit values /** * Value returned by onEnd method if * an handler was found mapped to the key @@ -63,6 +54,14 @@ public abstract class HandlerSelector extends FSMBehaviour { * no handler was found mapped to the key **/ public static final int SELECTION_NOK = 0; + // FSM states names + private static final String SELECT = "Select"; + private static final String HANDLE = "Handle"; + private static final String DUMMY = "Dummy"; + + // States exit values + private final Map handlers = new HashMap<>(); + private final Object accesKey; /** diff --git a/src/jade/proto/states/ReplySender.java b/src/jade/proto/states/ReplySender.java index cac1403..1007894 100644 --- a/src/jade/proto/states/ReplySender.java +++ b/src/jade/proto/states/ReplySender.java @@ -56,10 +56,9 @@ public class ReplySender extends OneShotBehaviour { * @param replyKey HashMap's key where to read the reply message * @param msgKey HashMap's key where to read the message to reply to. * @param mapMessagesList the HashMap of messages list for this bheaviour - * @deprecated - public ReplySender(Agent a, String replyKey, String msgKey, HashMap> mapMessagesList) { - this(a, replyKey, msgKey); - setMapMessagesList(mapMessagesList); + * @deprecated public ReplySender(Agent a, String replyKey, String msgKey, HashMap> mapMessagesList) { + this(a, replyKey, msgKey); + setMapMessagesList(mapMessagesList); } **/ @@ -70,7 +69,7 @@ public ReplySender(Agent a, String replyKey, String msgKey, HashMap> mapMessagesList, HashMap mapMessages) { super(a); @@ -93,32 +92,9 @@ public ReplySender(Agent a, String replyKey, String msgKey) { } **/ - public void action() { - ret = NO_REPLY_SENT; - //TODO: VERIFIER ICI LA map a utiliser selon la clef - //CAR LA MAP EST VIDE !!!!!!! - var ds = getMapMessages(); - ACLMessage reply = ds.get(replyKey); - if (reply != null) { - ACLMessage msg = ds.get(msgKey); - if (msg != null) { - adjustReply(myAgent, reply, msg); - myAgent.send(reply); - ret = reply.getPerformative(); - } - } - } - - public int onEnd() { - return ret; - } - - public void setMsgKey(String msgKey) { - this.msgKey = msgKey; - } - - public void setReplyKey(String replyKey) { - this.replyKey = replyKey; + //#APIDOC_EXCLUDE_BEGIN + // For persistence service + protected ReplySender() { } /** @@ -150,9 +126,32 @@ public static void adjustReply(Agent myAgent, ACLMessage reply, ACLMessage msg) } } - //#APIDOC_EXCLUDE_BEGIN - // For persistence service - protected ReplySender() { + public void action() { + ret = NO_REPLY_SENT; + //TODO: VERIFIER ICI LA map a utiliser selon la clef + //CAR LA MAP EST VIDE !!!!!!! + var ds = getMapMessages(); + ACLMessage reply = ds.get(replyKey); + if (reply != null) { + ACLMessage msg = ds.get(msgKey); + if (msg != null) { + adjustReply(myAgent, reply, msg); + myAgent.send(reply); + ret = reply.getPerformative(); + } + } + } + + public int onEnd() { + return ret; + } + + public void setMsgKey(String msgKey) { + this.msgKey = msgKey; + } + + public void setReplyKey(String replyKey) { + this.replyKey = replyKey; } //#APIDOC_EXCLUDE_END } diff --git a/src/jade/security/ThreadGroupHttpAuthenticator.java b/src/jade/security/ThreadGroupHttpAuthenticator.java index 96a2499..69bca92 100644 --- a/src/jade/security/ThreadGroupHttpAuthenticator.java +++ b/src/jade/security/ThreadGroupHttpAuthenticator.java @@ -34,9 +34,8 @@ public class ThreadGroupHttpAuthenticator extends Authenticator { private static final String PROXY_KEY = "PROXY"; private static final String SERVER_DEFAULT_KEY = "SERVER_DEAFULT"; - - private static ThreadGroupHttpAuthenticator theInstance; private static final Map passwordAuthentications = new HashMap<>(); + private static ThreadGroupHttpAuthenticator theInstance; private ThreadGroupHttpAuthenticator() { } diff --git a/src/jade/tools/DummyAgent/DummyAgentGui.java b/src/jade/tools/DummyAgent/DummyAgentGui.java index 82d8cb8..db9557f 100644 --- a/src/jade/tools/DummyAgent/DummyAgentGui.java +++ b/src/jade/tools/DummyAgent/DummyAgentGui.java @@ -48,6 +48,8 @@ * @version $Date: 2011-06-06 09:19:06 +0200(lun, 06 giu 2011) $ $Revision: 6415 $ */ class DummyAgentGui extends JFrame { + //logging + private final Logger logger = Logger.getMyLogger(this.getClass().getName()); DummyAgent myAgent; AID agentName; AclGui currentMsgGui; @@ -57,9 +59,6 @@ class DummyAgentGui extends JFrame { String logoDummy = "images/dummyagent.gif"; DummyAgentGui thisGUI; - //logging - private final Logger logger = Logger.getMyLogger(this.getClass().getName()); - // Constructor DummyAgentGui(DummyAgent a) { ////////////////////////// diff --git a/src/jade/tools/DummyAgent/GuiProperties.java b/src/jade/tools/DummyAgent/GuiProperties.java index a6cbaf5..964502f 100644 --- a/src/jade/tools/DummyAgent/GuiProperties.java +++ b/src/jade/tools/DummyAgent/GuiProperties.java @@ -35,9 +35,9 @@ * This class encapsulates some informations used by the program */ public class GuiProperties { + public static final String ImagePath = ""; protected static UIDefaults MyDefaults; protected static GuiProperties foo = new GuiProperties(); - public static final String ImagePath = ""; static { Object[] icons = { diff --git a/src/jade/tools/DummyAgent/MsgIndication.java b/src/jade/tools/DummyAgent/MsgIndication.java index f2699e5..f3d9f7c 100644 --- a/src/jade/tools/DummyAgent/MsgIndication.java +++ b/src/jade/tools/DummyAgent/MsgIndication.java @@ -44,18 +44,15 @@ */ class MsgIndication { - private static final int TYPE_LEN = 20; public static final int INCOMING = 0; public static final int OUTGOING = 1; - - public ACLMessage msg; - public int direction; - public Date date; - + private static final int TYPE_LEN = 20; //logging private static final Logger logger = Logger.getMyLogger(MsgIndication.class.getName()); - private static final DateFormat df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT); + public ACLMessage msg; + public int direction; + public Date date; MsgIndication() { msg = new ACLMessage(ACLMessage.NOT_UNDERSTOOD); @@ -69,6 +66,45 @@ class MsgIndication { date = d; } + static MsgIndication fromText(BufferedReader r) { + MsgIndication mi = new MsgIndication(); + try { + String line; + + // Date + line = r.readLine(); + mi.date = df.parse(line); + + // Direction + mi.direction = Integer.parseInt(r.readLine()); + + // Message length + int len = Integer.parseInt(r.readLine()); + + // Message + char[] cBuf = new char[len]; + r.read(cBuf, 0, len); + + StringACLCodec codec = new StringACLCodec(new StringReader(new String(cBuf)), null); + mi.msg = codec.decode(); + + // Read the last newline + line = r.readLine(); + + } catch (IOException e) { + if (logger.isLoggable(Logger.WARNING)) + logger.log(Logger.WARNING, "IO Exception in MsgIndication.fromText()"); + } catch (java.text.ParseException e1) { + if (logger.isLoggable(Logger.WARNING)) + logger.log(Logger.WARNING, "ParseException in MsgIndication.fromText()"); + } catch (ACLCodec.CodecException e2) { + if (logger.isLoggable(Logger.WARNING)) + logger.log(Logger.WARNING, "ParseException in parsing the ACL message"); + } //Exception thrown by ACLMessage.fromText() + + return (mi); + } + String getIndication() { int perf = msg.getPerformative(); StringBuilder tmpType = new StringBuilder(ACLMessage.getPerformative(perf)); @@ -89,14 +125,14 @@ String getIndication() { return (df.format(date) + ": " + tmpType + " " + tmpDir + " " + tmpPeer); } - void setMessage(ACLMessage m) { - msg = (ACLMessage) m.clone(); - } - ACLMessage getMessage() { return (msg); } + void setMessage(ACLMessage m) { + msg = (ACLMessage) m.clone(); + } + public String toString() { return (df.format(date) + "\n" + direction + "\n" + msg.toString()); } @@ -123,45 +159,6 @@ void toText(BufferedWriter w) { logger.log(Logger.WARNING, "IO Exception in MsgIndication.toText()"); } } - - static MsgIndication fromText(BufferedReader r) { - MsgIndication mi = new MsgIndication(); - try { - String line; - - // Date - line = r.readLine(); - mi.date = df.parse(line); - - // Direction - mi.direction = Integer.parseInt(r.readLine()); - - // Message length - int len = Integer.parseInt(r.readLine()); - - // Message - char[] cBuf = new char[len]; - r.read(cBuf, 0, len); - - StringACLCodec codec = new StringACLCodec(new StringReader(new String(cBuf)), null); - mi.msg = codec.decode(); - - // Read the last newline - line = r.readLine(); - - } catch (IOException e) { - if (logger.isLoggable(Logger.WARNING)) - logger.log(Logger.WARNING, "IO Exception in MsgIndication.fromText()"); - } catch (java.text.ParseException e1) { - if (logger.isLoggable(Logger.WARNING)) - logger.log(Logger.WARNING, "ParseException in MsgIndication.fromText()"); - } catch (ACLCodec.CodecException e2) { - if (logger.isLoggable(Logger.WARNING)) - logger.log(Logger.WARNING, "ParseException in parsing the ACL message"); - } //Exception thrown by ACLMessage.fromText() - - return (mi); - } } diff --git a/src/jade/tools/SocketProxyAgent/Connection.java b/src/jade/tools/SocketProxyAgent/Connection.java index db682e0..9997d8c 100644 --- a/src/jade/tools/SocketProxyAgent/Connection.java +++ b/src/jade/tools/SocketProxyAgent/Connection.java @@ -45,17 +45,16 @@ class Connection extends Thread { */ private final static Logger logger = Logger.getMyLogger(Server.class.getName()); - private Agent myAgent; - private Socket client; - private DataInputStream in; - private PrintStream out; private final boolean done = false; - private boolean closed = false; - /** * Name of the agents who intend to receive any message from this agent */ private final Vector allowedNames; + private Agent myAgent; + private Socket client; + private DataInputStream in; + private PrintStream out; + private boolean closed = false; /** * this class is a thread to listen on socket and copy to receivers diff --git a/src/jade/tools/SocketProxyAgent/Server.java b/src/jade/tools/SocketProxyAgent/Server.java index 0d0144a..8590400 100644 --- a/src/jade/tools/SocketProxyAgent/Server.java +++ b/src/jade/tools/SocketProxyAgent/Server.java @@ -42,9 +42,9 @@ class Server extends Thread { */ private final static Logger logger = Logger.getMyLogger(Server.class.getName()); - private ServerSocket listen_socket; private final Agent myAgent; private final Vector myOnlyReceivers; + private ServerSocket listen_socket; private boolean done = false; private Socket client_socket; private Connection c; diff --git a/src/jade/tools/SocketProxyAgent/SocketProxyAgent.java b/src/jade/tools/SocketProxyAgent/SocketProxyAgent.java index 8898ec5..ff3c026 100644 --- a/src/jade/tools/SocketProxyAgent/SocketProxyAgent.java +++ b/src/jade/tools/SocketProxyAgent/SocketProxyAgent.java @@ -65,6 +65,11 @@ public class SocketProxyAgent extends Agent { * my logger */ private final static Logger logger = Logger.getMyLogger(SocketProxyAgent.class.getName()); + private final static int ONE_SEC_AS_MS = 1000; + /** + * port we're using + */ + int portNumber = DEFAULT_PORT; /** * reader for parameters */ @@ -73,10 +78,6 @@ public class SocketProxyAgent extends Agent { * the thread doing connection on desired port */ private Server proxyServer; - /** - * port we're using - */ - int portNumber = DEFAULT_PORT; /** * agent setup @@ -167,8 +168,6 @@ public int getPort() { return portNumber; } - private final static int ONE_SEC_AS_MS = 1000; - /** * agent takedown */ diff --git a/src/jade/tools/SocketProxyAgent/WaitAnswersBehaviour.java b/src/jade/tools/SocketProxyAgent/WaitAnswersBehaviour.java index 05fe408..f860508 100644 --- a/src/jade/tools/SocketProxyAgent/WaitAnswersBehaviour.java +++ b/src/jade/tools/SocketProxyAgent/WaitAnswersBehaviour.java @@ -36,21 +36,21 @@ * behaviour to wait for answer to message sent */ class WaitAnswersBehaviour extends SimpleBehaviour { - ACLMessage msg; - PrintStream out; - long timeout; private final static long ONE_SEC_AS_MS = 1000; private final static long TEN_SEC_AS_MS = 10 * ONE_SEC_AS_MS; final static long DEFAULT_TIMEOUT = TEN_SEC_AS_MS; - boolean finished; - MessageTemplate mt; - Agent myAgent = null; - private final String myThreadName; /** * my logger */ private final static Logger logger = Logger.getMyLogger(WaitAnswersBehaviour.class.getName()); + private final String myThreadName; + ACLMessage msg; + PrintStream out; + long timeout; + boolean finished; + MessageTemplate mt; + Agent myAgent = null; /** * construct behaviour to wait for answer to message sent diff --git a/src/jade/tools/ToolAgent.java b/src/jade/tools/ToolAgent.java index e899689..b7c9191 100644 --- a/src/jade/tools/ToolAgent.java +++ b/src/jade/tools/ToolAgent.java @@ -48,25 +48,10 @@ public abstract class ToolAgent extends Agent { private final ACLMessage AMSSubscription = new ACLMessage(ACLMessage.SUBSCRIBE); private final ACLMessage AMSCancellation = new ACLMessage(ACLMessage.CANCEL); - - private transient ContainerListener myContainerListener = null; protected transient Logger logger; + private transient ContainerListener myContainerListener = null; - // This is left here for backward compatibility - public interface EventHandler extends AMSSubscriber.EventHandler { - } - - /** - * This abstract behaviour is used to receive notifications from - * the AMS. - */ - protected abstract class AMSListenerBehaviour extends AMSSubscriber { - // Redefine the onStart() method not to automatically subscribe. - public void onStart() { - } - } // End of AMSListenerBehaviour class - /** * Default constructor. */ @@ -235,4 +220,18 @@ private void clean() { } } } + + // This is left here for backward compatibility + public interface EventHandler extends AMSSubscriber.EventHandler { + } + + /** + * This abstract behaviour is used to receive notifications from + * the AMS. + */ + protected abstract class AMSListenerBehaviour extends AMSSubscriber { + // Redefine the onStart() method not to automatically subscribe. + public void onStart() { + } + } // End of AMSListenerBehaviour class } diff --git a/src/jade/tools/ToolNotifier.java b/src/jade/tools/ToolNotifier.java index c8f3981..5b3c7a5 100644 --- a/src/jade/tools/ToolNotifier.java +++ b/src/jade/tools/ToolNotifier.java @@ -60,40 +60,10 @@ public class ToolNotifier extends ToolAgent implements MessageListener, AgentLis private Logger myLogger; - /** - * Inner class NotifierAMSListenerBehaviour - */ - - class NotifierAMSListenerBehaviour extends AMSListenerBehaviour { - protected void installHandlers(Map handlersTable) { - // Fill the event handler table. - handlersTable.put(IntrospectionOntology.DEADAGENT, (EventHandler) ev -> { - DeadAgent da = (DeadAgent) ev; - AID dead = da.getAgent(); - removeObservedAgent(dead); - if (dead.equals(observerAgent)) { - suicide(); - } - }); - - handlersTable.put(IntrospectionOntology.MOVEDAGENT, (EventHandler) ev -> { - MovedAgent ma = (MovedAgent) ev; - AID moved = ma.getAgent(); - if (!here().equals(ma.getTo())) { - removeObservedAgent(moved); - } - }); - - } // END of installHandlers() method - - } // END of inner class NotifierAMSListenerBehaviour - - public ToolNotifier(AID id) { observerAgent = id; } - protected void toolSetup() { state = ACTIVE_STATE; @@ -317,12 +287,10 @@ public void changedBehaviourState(AgentEvent ev) { } } - public void changedAgentPrincipal(AgentEvent ev) { // No tool is interested in this type of event --> Do nothing } - private ACLMessage createObserverMessage() { ACLMessage msg = new ACLMessage(ACLMessage.INFORM); msg.addReceiver(observerAgent); @@ -381,60 +349,11 @@ private void sendEvent(Event ev, String replyWith) { } } - - /** - * Inner class SynchEventInformer. - * When the observation of an event must be synchronous (i.e. the - * thread that generated the event must block until the observer - * has finished observing the event) we must - * - inform the observer - * - wait for the observer to send back a proper indication - * - wake up the thread that generated the event - */ - private class SynchEventInformer extends SimpleBehaviour { - private final Event ev; - private final JADEEvent jev; - private boolean finished = false; - private MessageTemplate template; - - SynchEventInformer(Agent a, Event ev, JADEEvent jev) { - super(a); - this.ev = ev; - this.jev = jev; - } - - public void onStart() { - String replyWith = String.valueOf(jev.hashCode()); - sendEvent(ev, replyWith); - template = MessageTemplate.MatchInReplyTo(replyWith); - } - - public void action() { - ACLMessage msg = myAgent.receive(template); - if (msg != null) { - jev.notifyProcessed(null); - removePendingEvent(jev); - finished = true; - } else { - block(); - } - } - - public boolean done() { - return finished; - } - } - - ////////////////////////////////////////////// // Utility methods dealing with pending events private void addPendingEvent(JADEEvent ev, AID id) { synchronized (pendingEvents) { - List l = pendingEvents.get(id); - if (l == null) { - l = new ArrayList<>(); - pendingEvents.put(id, l); - } + List l = pendingEvents.computeIfAbsent(id, k -> new ArrayList<>()); l.add(ev); } } @@ -477,4 +396,75 @@ private void notifyAllPendingEvents() { } } } + + /** + * Inner class NotifierAMSListenerBehaviour + */ + + class NotifierAMSListenerBehaviour extends AMSListenerBehaviour { + protected void installHandlers(Map handlersTable) { + // Fill the event handler table. + handlersTable.put(IntrospectionOntology.DEADAGENT, (EventHandler) ev -> { + DeadAgent da = (DeadAgent) ev; + AID dead = da.getAgent(); + removeObservedAgent(dead); + if (dead.equals(observerAgent)) { + suicide(); + } + }); + + handlersTable.put(IntrospectionOntology.MOVEDAGENT, (EventHandler) ev -> { + MovedAgent ma = (MovedAgent) ev; + AID moved = ma.getAgent(); + if (!here().equals(ma.getTo())) { + removeObservedAgent(moved); + } + }); + + } // END of installHandlers() method + + } // END of inner class NotifierAMSListenerBehaviour + + /** + * Inner class SynchEventInformer. + * When the observation of an event must be synchronous (i.e. the + * thread that generated the event must block until the observer + * has finished observing the event) we must + * - inform the observer + * - wait for the observer to send back a proper indication + * - wake up the thread that generated the event + */ + private class SynchEventInformer extends SimpleBehaviour { + private final Event ev; + private final JADEEvent jev; + private boolean finished = false; + private MessageTemplate template; + + SynchEventInformer(Agent a, Event ev, JADEEvent jev) { + super(a); + this.ev = ev; + this.jev = jev; + } + + public void onStart() { + String replyWith = String.valueOf(jev.hashCode()); + sendEvent(ev, replyWith); + template = MessageTemplate.MatchInReplyTo(replyWith); + } + + public void action() { + ACLMessage msg = myAgent.receive(template); + if (msg != null) { + jev.notifyProcessed(null); + removePendingEvent(jev); + finished = true; + } else { + block(); + } + } + + public boolean done() { + return finished; + } + } } diff --git a/src/jade/tools/dfgui/DFGUI.java b/src/jade/tools/dfgui/DFGUI.java index 8cd95a5..a70ad61 100644 --- a/src/jade/tools/dfgui/DFGUI.java +++ b/src/jade/tools/dfgui/DFGUI.java @@ -549,22 +549,6 @@ public DFGUI(DFGUIAdapter a) { } - class tabListener implements ChangeListener { - public void stateChanged(ChangeEvent event) { - Object object = event.getSource(); - if (object == tabbedPane) - tabStateChanged(event); - - } - - public void tabStateChanged(ChangeEvent event) { - int index = tabbedPane.getSelectedIndex(); - setButton(index); - - } - - } - /* This method must be used after the constructor of the gui to set the object implementing the DFGUIAdapter interface. @@ -583,7 +567,6 @@ public void setAdapter(DFGUIAdapter a) { } - /** * Use this method to show a message on the DF GUI. * @@ -616,7 +599,6 @@ private void setRegister(boolean value) { } - private void setModify(boolean value) { modifyB.setEnabled(value); dfModifyAction.setEnabled(value); @@ -627,6 +609,11 @@ private void setDeregister(boolean value) { deregB.setEnabled(value); dfDeregAction.setEnabled(value); + } + + private void setDFfed(boolean value) { + fedDFB.setEnabled(value); + dfFedAction.setEnabled(value); } /*private void setSearch(boolean value) @@ -636,11 +623,6 @@ private void setDeregister(boolean value) { }*/ - private void setDFfed(boolean value) { - fedDFB.setEnabled(value); - dfFedAction.setEnabled(value); - } - /** * This method permits to set the tabben pane to show. */ @@ -860,7 +842,6 @@ public void removeParent(AID parentName) { parentTable.clearSelection(); } - /** * Shows DF GUI properly */ @@ -899,7 +880,6 @@ public void run() { EventQueue.invokeLater(new disposeIt(this)); } - /** * This method returns the DFAgentDescription of an agent found in a search operation. * @@ -920,4 +900,20 @@ public void enableRefreshButton() { refreshItem.setVisible(true); } + class tabListener implements ChangeListener { + public void stateChanged(ChangeEvent event) { + Object object = event.getSource(); + if (object == tabbedPane) + tabStateChanged(event); + + } + + public void tabStateChanged(ChangeEvent event) { + int index = tabbedPane.getSelectedIndex(); + setButton(index); + + } + + } + } diff --git a/src/jade/tools/dfgui/DFGuiProperties.java b/src/jade/tools/dfgui/DFGuiProperties.java index ffa813a..48fd3e4 100644 --- a/src/jade/tools/dfgui/DFGuiProperties.java +++ b/src/jade/tools/dfgui/DFGuiProperties.java @@ -35,9 +35,9 @@ * This class encapsulates some informations used by the program */ class DFGuiProperties { + public static final String ImagePath = ""; protected static UIDefaults MyDefaults; protected static DFGuiProperties foo = new DFGuiProperties(); - public static final String ImagePath = ""; static { Object[] icons = diff --git a/src/jade/tools/gui/ACLAIDDialog.java b/src/jade/tools/gui/ACLAIDDialog.java index fb1308e..1be0142 100644 --- a/src/jade/tools/gui/ACLAIDDialog.java +++ b/src/jade/tools/gui/ACLAIDDialog.java @@ -44,6 +44,23 @@ */ public class ACLAIDDialog extends JDialog { + private final GridBagLayout gridBagLayout1 = new GridBagLayout(); + private final JLabel jLabel1 = new JLabel(); + private final JTextField nameTextField = new JTextField(); + private final JLabel jLabel2 = new JLabel(); + private final JLabel jLabel3 = new JLabel(); + private final JPanel buttonPanel = new JPanel(); + private final JButton okButton = new JButton(); + private final JButton cancelButton = new JButton(); + private final String CANCELLED = "cancelled"; + private final AIDAddressList addressesList = new AIDAddressList(); + private final boolean editable = true; + private final Agent agent; + public JCheckBox localCheckBox = new JCheckBox(); + private String OK = "ok"; + private String userAction = CANCELLED; + private ACLAIDList resolverList; + private AID itsAID; /** * Constructor for the ACLAIDDialog object * @@ -62,7 +79,6 @@ public ACLAIDDialog(Agent agent) { } } - /** * Gets the ItsAID attribute of the ACLAIDDialog object * @@ -72,6 +88,23 @@ public AID getItsAID() { return itsAID; } + /** + * Sets the ItsAID attribute of the ACLAIDDialog object + * + * @param newItsAID The new ItsAID value + */ + public void setItsAID(AID newItsAID) { + itsAID = newItsAID; + nameTextField.setText(itsAID.getName()); + addressesList.register(itsAID); + resolverList.register(itsAID, "Resolvers"); + + String name = itsAID.getName(); + if ((name != null) && (!name.endsWith(agent.getHap()))) { + this.localCheckBox.setSelected(true); + } + + } /** * Gets the OK attribute of the ACLAIDDialog object. OK is true when the @@ -83,7 +116,6 @@ public boolean getOK() { return userAction.equals(OK); } - /** * Sets the Editable attribute of the ACLAIDDialog object * @@ -100,26 +132,6 @@ public void setEditable(boolean theBool) { } } - - /** - * Sets the ItsAID attribute of the ACLAIDDialog object - * - * @param newItsAID The new ItsAID value - */ - public void setItsAID(AID newItsAID) { - itsAID = newItsAID; - nameTextField.setText(itsAID.getName()); - addressesList.register(itsAID); - resolverList.register(itsAID, "Resolvers"); - - String name = itsAID.getName(); - if ((name != null) && (!name.endsWith(agent.getHap()))) { - this.localCheckBox.setSelected(true); - } - - } - - /** * Sets the UserAction attribute of the ACLAIDDialog object * @@ -129,7 +141,6 @@ public void setUserAction(String newUserAction) { userAction = newUserAction; } - /** * Method triggered by the OK button * @@ -140,7 +151,6 @@ void okButton_actionPerformed(ActionEvent e) { this.setVisible(false); } - /** * Method triggered by the cancel button * @@ -151,7 +161,6 @@ void cancelButton_actionPerformed(ActionEvent e) { this.setVisible(false); } - /** * Method triggered when leaving the textfield of "name" * @@ -161,7 +170,6 @@ void nameTextField_focusLost(FocusEvent e) { updateSenderName(); } - /** * Updates the name field of the current AID. The localCheckBox indicates * wheter the agent is local or not. @@ -175,7 +183,6 @@ void updateSenderName() { } - /** * Method triggered by changing the state of the checkbox of "local" * @@ -185,7 +192,6 @@ void localCheckBox_itemStateChanged(ItemEvent e) { updateSenderName(); } - /** * builds up the dialog *

@@ -241,27 +247,5 @@ public void focusLost(FocusEvent e) { this.getContentPane().add(localCheckBox, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0 , GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0)); } - - - public JCheckBox localCheckBox = new JCheckBox(); - - private final GridBagLayout gridBagLayout1 = new GridBagLayout(); - private final JLabel jLabel1 = new JLabel(); - private final JTextField nameTextField = new JTextField(); - private final JLabel jLabel2 = new JLabel(); - private final JLabel jLabel3 = new JLabel(); - private final JPanel buttonPanel = new JPanel(); - private final JButton okButton = new JButton(); - private final JButton cancelButton = new JButton(); - - private String OK = "ok"; - private final String CANCELLED = "cancelled"; - private final AIDAddressList addressesList = new AIDAddressList(); - private final boolean editable = true; - private String userAction = CANCELLED; - private ACLAIDList resolverList; - - private final Agent agent; - private AID itsAID; } // ***EOF*** diff --git a/src/jade/tools/gui/ACLAIDList.java b/src/jade/tools/gui/ACLAIDList.java index 323c1cb..43df667 100644 --- a/src/jade/tools/gui/ACLAIDList.java +++ b/src/jade/tools/gui/ACLAIDList.java @@ -45,6 +45,24 @@ * @since April 26, 2002 */ public class ACLAIDList extends JPanel { + private final String MSG = "msg"; + private final String AID = "Aid"; + private final JScrollPane contentScrollPane = new JScrollPane(); + private final JList contentList = new JList<>(); + private final GridBagLayout gridBagLayout1 = new GridBagLayout(); + private final JButton viewButton = new JButton(); + private final JButton addButton = new JButton(); + private final JButton deleteButton = new JButton(); + private final DefaultListModel listModel = new DefaultListModel<>(); + private final AIDListCellRenderer aidListCellRenderer = new AIDListCellRenderer(); + private final Agent agent; + private boolean editable = true; + private String fieldName = ""; + private String mode = MSG; + private AIDListListener theDataListener; + private ACLMessage itsMsg; + private AID itsAid; + private Object itsObj; /** * Constructor for the ACLAIDList object * @@ -59,7 +77,6 @@ public ACLAIDList(Agent agent) { } } - /** * Sets the Editable attribute of the ACLAIDList object * @@ -73,7 +90,6 @@ public void setEditable(boolean theBool) { } } - /** * register Object and accompagnied field name in ACLMessage * @@ -102,7 +118,6 @@ public void register(Object o, String fieldName) { contentList.setModel(listModel); } - /** * register AID and fieldname from ACLMessage * @@ -130,7 +145,6 @@ public void register(AID aid, String fieldName) { contentList.setModel(listModel); } - /** * show the current selected AID */ @@ -153,7 +167,6 @@ void doView() { } } - /** * Triggered by delete button * @@ -163,7 +176,6 @@ void deleteButton_actionPerformed(ActionEvent e) { doDelete(); } - /** * delete selected AID */ @@ -175,7 +187,6 @@ void doDelete() { } } - /** * Triggered by add button * @@ -185,7 +196,6 @@ void addButton_actionPerformed(ActionEvent e) { doAdd(); } - /** * Add a AID to the list */ @@ -201,7 +211,6 @@ void doAdd() { } - /** * Triggered by the view button * @@ -211,7 +220,6 @@ void viewButton_actionPerformed(ActionEvent e) { doView(); } - /** * Triggered when clicking with mouse pointer. On doubleclick, call * doView() @@ -225,7 +233,6 @@ void contentList_mouseClicked(MouseEvent e) { } - /** * Triggered when pressing a key. Enter will call doView(), Insert will * call doAdd(), and Delete will call doDelete(). @@ -251,7 +258,6 @@ void contentList_keyPressed(KeyEvent e) { } - /** * Builds up the componenent *

@@ -314,7 +320,6 @@ public void mouseClicked(MouseEvent e) { contentScrollPane.getViewport().add(contentList, null); } - public class AIDListCellRenderer extends JLabel implements ListCellRenderer { /** * Constructor for the AIDListCellRenderer object @@ -346,7 +351,6 @@ public Component getListCellRendererComponent(JList list, Object value, int inde } } - /** * This class listenes to the AIDList * @@ -355,6 +359,10 @@ public Component getListCellRendererComponent(JList list, Object value, int inde */ public class AIDListListener implements ListDataListener { + String fieldName = ""; + private AID theRemovedAID, theChangedAID; + private Object itsObj; + /** * Description of the Method * @@ -366,7 +374,6 @@ public void register(Object obj, String fieldName) { this.fieldName = fieldName; } - /** * Description of the Method * @@ -387,7 +394,6 @@ public void intervalAdded(ListDataEvent parm1) { } - /** * Description of the Method * @@ -397,7 +403,6 @@ public void registerRemovedAID(AID theRemovedAID) { this.theRemovedAID = theRemovedAID; } - /** * Description of the Method * @@ -407,7 +412,6 @@ public void registerChangedAID(AID theChangedAID) { this.theChangedAID = theChangedAID; } - /** * Description of the Method * @@ -424,7 +428,6 @@ public void intervalRemoved(ListDataEvent parm1) { } } - /** * Description of the Method * @@ -454,36 +457,7 @@ public void contentsChanged(ListDataEvent parm1) { } } - - - String fieldName = ""; - - private AID theRemovedAID, theChangedAID; - - private Object itsObj; } - - private final String MSG = "msg"; - private final String AID = "Aid"; - private final JScrollPane contentScrollPane = new JScrollPane(); - private final JList contentList = new JList<>(); - - private final GridBagLayout gridBagLayout1 = new GridBagLayout(); - private final JButton viewButton = new JButton(); - private final JButton addButton = new JButton(); - private final JButton deleteButton = new JButton(); - - private final DefaultListModel listModel = new DefaultListModel<>(); - private final AIDListCellRenderer aidListCellRenderer = new AIDListCellRenderer(); - private boolean editable = true; - private String fieldName = ""; - private String mode = MSG; - private final Agent agent; - private AIDListListener theDataListener; - private ACLMessage itsMsg; - private AID itsAid; - private Object itsObj; - } // ***EOF*** diff --git a/src/jade/tools/gui/ACLComboBox.java b/src/jade/tools/gui/ACLComboBox.java index 45a2e90..0bc54ea 100644 --- a/src/jade/tools/gui/ACLComboBox.java +++ b/src/jade/tools/gui/ACLComboBox.java @@ -43,6 +43,23 @@ public class ACLComboBox extends JComboBox implements Observer { + private static final String[] fipaProtocols = { + "", + FIPANames.InteractionProtocol.FIPA_REQUEST, + FIPANames.InteractionProtocol.FIPA_QUERY, + FIPANames.InteractionProtocol.FIPA_REQUEST_WHEN, + FIPANames.InteractionProtocol.FIPA_ENGLISH_AUCTION, + FIPANames.InteractionProtocol.FIPA_DUTCH_AUCTION, + FIPANames.InteractionProtocol.FIPA_BROKERING, + FIPANames.InteractionProtocol.FIPA_RECRUITING, + FIPANames.InteractionProtocol.FIPA_PROPOSE, + FIPANames.InteractionProtocol.FIPA_CONTRACT_NET, + FIPANames.InteractionProtocol.FIPA_ITERATED_CONTRACT_NET + }; + private final DefaultComboBoxModel comboBoxModel = new DefaultComboBoxModel<>(); + private ACLMessage msg; + private String fieldName; + /** * Sets the Editable attribute of the ACLComboBox object * @@ -53,7 +70,6 @@ public void setEditable(boolean theBool) { this.setEnabled(theBool); } - /** * register performatives in the comboBoxModel * @@ -84,7 +100,6 @@ public void registerPerformatives(Object arg) { updateUI(); } - /** * Register protocols from ACLMessage * @@ -115,7 +130,6 @@ public void registerProtocol(Object arg) { updateUI(); } - /** * part of observer interface * @@ -127,7 +141,6 @@ public void registerProtocol(Object arg) { public void update(Observable ob, Object arg) { } - /** * triggered when focus lost * @@ -136,7 +149,6 @@ public void update(Observable ob, Object arg) { public void focusLost(FocusEvent e) { } - /** * Description of the Method */ @@ -154,7 +166,6 @@ void performativeItemStateChanged() { } - /** * Description of the Method */ @@ -167,25 +178,5 @@ void protocolItemStateChanged() { msg.setProtocol(value); } } - - - private static final String[] fipaProtocols = { - "", - FIPANames.InteractionProtocol.FIPA_REQUEST, - FIPANames.InteractionProtocol.FIPA_QUERY, - FIPANames.InteractionProtocol.FIPA_REQUEST_WHEN, - FIPANames.InteractionProtocol.FIPA_ENGLISH_AUCTION, - FIPANames.InteractionProtocol.FIPA_DUTCH_AUCTION, - FIPANames.InteractionProtocol.FIPA_BROKERING, - FIPANames.InteractionProtocol.FIPA_RECRUITING, - FIPANames.InteractionProtocol.FIPA_PROPOSE, - FIPANames.InteractionProtocol.FIPA_CONTRACT_NET, - FIPANames.InteractionProtocol.FIPA_ITERATED_CONTRACT_NET - }; - - private final DefaultComboBoxModel comboBoxModel = new DefaultComboBoxModel<>(); - - private ACLMessage msg; - private String fieldName; } // ***EOF*** diff --git a/src/jade/tools/gui/ACLContentDialog.java b/src/jade/tools/gui/ACLContentDialog.java index 505a7cf..56cfdb7 100644 --- a/src/jade/tools/gui/ACLContentDialog.java +++ b/src/jade/tools/gui/ACLContentDialog.java @@ -36,6 +36,13 @@ public class ACLContentDialog extends JDialog { + JPanel contentPanel = new JPanel(); + BorderLayout borderLayout1 = new BorderLayout(); + JLabel titleLabel = new JLabel(); + JButton doneButton = new JButton(); + ACLTextArea contentTextArea = new ACLTextArea(); + + public ACLContentDialog(Frame frame, String title, boolean modal) { super(frame, title, modal); try { @@ -51,12 +58,10 @@ public ACLContentDialog() { this(null, "", false); } - public void setEditable(boolean theBool) { this.contentTextArea.setEditable(theBool); } - public void setItsContent(ACLMessage itsMsg) { contentTextArea.register(itsMsg, "Content"); @@ -68,7 +73,6 @@ public void setItsContent(ACLMessage itsMsg) { } - void jbInit() { contentPanel.setLayout(borderLayout1); this.getContentPane().setBackground(Color.white); @@ -96,22 +100,12 @@ public void focusGained(FocusEvent e) { contentPanel.add(contentTextArea, BorderLayout.CENTER); } - void doneButton_actionPerformed(ActionEvent e) { this.setVisible(false); } - void this_focusGained(FocusEvent e) { this.contentTextArea.requestFocus(); } - - - JPanel contentPanel = new JPanel(); - BorderLayout borderLayout1 = new BorderLayout(); - JLabel titleLabel = new JLabel(); - JButton doneButton = new JButton(); - - ACLTextArea contentTextArea = new ACLTextArea(); } // ***EOF*** diff --git a/src/jade/tools/gui/ACLFrame.java b/src/jade/tools/gui/ACLFrame.java index a9f93da..fe48aff 100644 --- a/src/jade/tools/gui/ACLFrame.java +++ b/src/jade/tools/gui/ACLFrame.java @@ -40,6 +40,20 @@ */ public class ACLFrame extends JFrame { + private final GridBagLayout gridBagLayout1 = new GridBagLayout(); + private final JPanel buttonPanel = new JPanel(); + private final JButton closeButton = new JButton(); + private final JMenuBar theMenuBar = new JMenuBar(); + private final JMenu fileMenu = new JMenu(); + private final JMenuItem saveMenuItem = new JMenuItem(); + private final JMenuItem exitMenuItem = new JMenuItem(); + private final JMenu toolsMenu = new JMenu(); + private final JMenuItem systemoutMenuItem = new JMenuItem(); + private final Agent agent; + private ACLPanel aclPanel; + private ACLMessage msg; + + /** * Constructor for the ACLFrame object * @@ -62,7 +76,6 @@ public ACLFrame(Agent agent) { } } - /** * show the ACLMessage, disabled * @@ -75,7 +88,6 @@ public static void show(ACLMessage theMsg, Agent agent) { theFrame.disableACLPanel(); } - /** * Sets the ACLMessage of the Frame * @@ -97,7 +109,6 @@ public void setMsg(ACLMessage msg) { this.setVisible(true); } - /** * disable editing of ACLmessage */ @@ -105,7 +116,6 @@ public void disableACLPanel() { aclPanel.setReadOnly(); } - /** * Description of the Method * @@ -115,7 +125,6 @@ void closeButton_actionPerformed(ActionEvent e) { doExit(); } - /** * Description of the Method * @@ -125,7 +134,6 @@ void exitMenuItem_actionPerformed(ActionEvent e) { doExit(); } - /** * Description of the Method */ @@ -133,7 +141,6 @@ void doExit() { this.setVisible(false); } - /** * Description of the Method * @@ -143,7 +150,6 @@ void systemoutMenuItem_actionPerformed(ActionEvent e) { doSystemOut(); } - /** * Description of the Method */ @@ -151,7 +157,6 @@ void doSystemOut() { aclPanel.doSystemOut(); } - /** * Description of the Method * @@ -161,7 +166,6 @@ void saveMenuItem_actionPerformed(ActionEvent e) { aclPanel.saveACL(); } - /** * Sets the FrameIcon attribute of the ACLFrame object * @@ -172,7 +176,6 @@ private void setFrameIcon(String iconpath) { setIconImage(image.getImage()); } - /** * Description of the Method *

@@ -225,19 +228,5 @@ private void jbInit() { toolsMenu.add(systemoutMenuItem); } - - private final GridBagLayout gridBagLayout1 = new GridBagLayout(); - private final JPanel buttonPanel = new JPanel(); - private final JButton closeButton = new JButton(); - private final JMenuBar theMenuBar = new JMenuBar(); - private final JMenu fileMenu = new JMenu(); - private final JMenuItem saveMenuItem = new JMenuItem(); - private final JMenuItem exitMenuItem = new JMenuItem(); - private final JMenu toolsMenu = new JMenu(); - private final JMenuItem systemoutMenuItem = new JMenuItem(); - private ACLPanel aclPanel; - private ACLMessage msg; - private final Agent agent; - } // ***EOF*** diff --git a/src/jade/tools/gui/ACLMessageNode.java b/src/jade/tools/gui/ACLMessageNode.java index e84df3f..4e367c8 100644 --- a/src/jade/tools/gui/ACLMessageNode.java +++ b/src/jade/tools/gui/ACLMessageNode.java @@ -42,6 +42,13 @@ public class ACLMessageNode extends DefaultMutableTreeNode { + private static final DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM); + private Date theDate = new Date(); + private ACLMessage theMessage; + private String direction; + private String time; + + /** * Constructor for the MessageNode object * @@ -51,7 +58,6 @@ public class ACLMessageNode extends DefaultMutableTreeNode { super(str); } - /** * Gets the Message attribute of the MessageNode object * @@ -61,6 +67,14 @@ public ACLMessage getMessage() { return theMessage; } + /** + * Sets the Message attribute of the MessageNode object + * + * @param msg The new Message value + */ + public void setMessage(ACLMessage msg) { + theMessage = (ACLMessage) msg.clone(); + } /** * Gets the Performative attribute of the MessageNode object @@ -71,7 +85,6 @@ public String getPerformative() { return ACLMessage.getPerformative(theMessage.getPerformative()); } - /** * Gets the SendTo attribute of the MessageNode object * @@ -85,7 +98,6 @@ public String getSendTo() { return ""; } - /** * Gets the Ontology attribute of the MessageNode object * @@ -99,7 +111,6 @@ public String getOntology() { return ""; } - /** * Gets the Direction attribute of the MessageNode object * @@ -109,27 +120,6 @@ public String getDirection() { return direction; } - - public String getTime() { - return time; - } - - - public Date getTheDate() { - return theDate; - } - - - /** - * Sets the Message attribute of the MessageNode object - * - * @param msg The new Message value - */ - public void setMessage(ACLMessage msg) { - theMessage = (ACLMessage) msg.clone(); - } - - /** * Sets the Direction attribute of the MessageNode object * @@ -139,6 +129,9 @@ public void setDirection(String theDirection) { direction = theDirection; } + public String getTime() { + return time; + } public void setTime(String theTime) { time = theTime; @@ -149,12 +142,14 @@ public void setTime(String theTime) { } } + public Date getTheDate() { + return theDate; + } public void setTheDate(Date theTheDate) { theDate = theTheDate; } - public String receivedFrom() { if (theMessage.getSender() != null) { AID sender = theMessage.getSender(); @@ -162,12 +157,5 @@ public String receivedFrom() { } return ""; } - - - private static final DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM); - private Date theDate = new Date(); - private ACLMessage theMessage; - private String direction; - private String time; } // ***EOF*** diff --git a/src/jade/tools/gui/ACLPanel.java b/src/jade/tools/gui/ACLPanel.java index e6a2a59..1e1cb80 100644 --- a/src/jade/tools/gui/ACLPanel.java +++ b/src/jade/tools/gui/ACLPanel.java @@ -56,7 +56,78 @@ public class ACLPanel extends JPanel { private final Logger logger = Logger.getMyLogger(this.getClass().getName()); + private final ACLTextField envACLReprTextField = new ACLTextField(); + private final ACLTextField envPayloadLengthTextField = new ACLTextField(); + private final ACLTextField envPayloadEncodingTextField = new ACLTextField(); + private final JTextField envFromTextField = new JTextField(); + private final JTextField senderTextField = new JTextField(); + private final ACLPropertyList userpropList = new ACLPropertyList(); + private final ACLTextField conversationTextField = new ACLTextField(); + private final ACLTextField languageTextField = new ACLTextField(); + private final ACLTextField encodingTextField = new ACLTextField(); + private final ACLTextField ontologyTextField = new ACLTextField(); + private final ACLComboBox protocolComboBox = new ACLComboBox(); + private final ACLTextField inreplytoTextField = new ACLTextField(); + private final ACLTextField replywithTextField = new ACLTextField(); + private final JTextField replybyTextField = new JTextField(); + private final ACLComboBox performativesComboBox = new ACLComboBox(); + private final Vector editsVector = new Vector<>(); + private final JPanel aclTab = new JPanel(); + private final GridBagLayout gridBagLayout2 = new GridBagLayout(); + private final JTabbedPane theTabbedPane = new JTabbedPane(); + private final JPanel envelopeTab = new JPanel(); + private final GridBagLayout gridBagLayout3 = new GridBagLayout(); + private final JScrollPane commentsScrollPane = new JScrollPane(); + private final EnvCommentsTextArea envCommentsTextArea = new EnvCommentsTextArea(); + private final ImageIcon zoomIcon = + new ImageIcon(this.getClass().getResource("images/zoom.gif")); + private final ImageIcon dateIcon = + new ImageIcon(this.getClass().getResource("images/date.gif")); + private final ImageIcon envelopeIcon = + new ImageIcon(this.getClass().getResource("images/envelope.gif")); + private final ImageIcon messageIcon = + new ImageIcon(this.getClass().getResource("images/message.gif")); + GridBagLayout gridBagLayout1 = new GridBagLayout(); + JLabel senderLabel = new JLabel(); + JLabel receiverLabel = new JLabel(); + JLabel replytoLabel = new JLabel(); + JLabel contentLabel = new JLabel(); + JLabel languageLabel = new JLabel(); + JLabel encodingLabel = new JLabel(); + JLabel ontologyjLabel = new JLabel(); + JLabel protocolLabel = new JLabel(); + JLabel inreplytoLabel = new JLabel(); + JLabel replywithLabel = new JLabel(); + JLabel replybyLabel = new JLabel(); + JLabel userpropLabel = new JLabel(); + JLabel convidLabel = new JLabel(); + JLabel performativeLabel = new JLabel(); + JButton senderButton = new JButton(); + JButton replyByButton = new JButton(); + JLabel toLabel = new JLabel(); + JLabel fromLabel = new JLabel(); + JLabel commentsLabel = new JLabel(); + JLabel aclRepreLabel = new JLabel(); + JLabel payLoadLabel = new JLabel(); + JLabel envDateLabel = new JLabel(); + JLabel intReceiversLabel = new JLabel(); + JLabel jLabel1 = new JLabel(); + JTextField envDateTextField = new JTextField(); + JButton defaultEnvelopeButton = new JButton(); + JButton fromButton = new JButton(); + JButton envDateButton = new JButton(); + JButton contentZoomButton = new JButton(); + ACLTextArea contentTextArea = new ACLTextArea(); + private boolean editable = true; + private ACLMessage itsMsg = new ACLMessage(ACLMessage.INFORM); + private ACLAIDList envToList; + private ACLAIDList envIntendedReceiversList; + private Agent agent; + private ACLAIDList receiverList; + private ACLAIDList replytoList; + private File currentDir; + private Envelope itsEnvelope; /** * Constructor for the ACLPanel object * @@ -100,7 +171,6 @@ public ACLPanel(Agent agent) { } } - /** * Gets the ItsMsg attribute of the ACLPanel object * @@ -110,7 +180,6 @@ public ACLMessage getItsMsg() { return itsMsg; } - /** * Sets the ItsMsg attribute of the ACLPanel object * @@ -152,7 +221,6 @@ public void setItsMsg(ACLMessage msg) { } - /** * Sets the ReadOnly attribute of the ACLPanel object */ @@ -161,7 +229,6 @@ public void setReadOnly() { editable = false; } - /** * Sets the Disabled attribute of the ACLPanel object * @@ -183,7 +250,6 @@ public void setEnabled(boolean theBool) { } } - /** * Description of the Method */ @@ -192,7 +258,6 @@ public void doSystemOut() { logger.log(Logger.INFO, "\n" + itsMsg.toString() + "\n"); } - /** * Description of the Method */ @@ -233,7 +298,6 @@ public void saveACL() { } } - public void loadACL() { UIManager.put("FileChooser.openButtonToolTipText", "Open ACLMessage"); @@ -268,7 +332,6 @@ public void loadACL() { } } - public void doZoomContent() { ACLContentDialog theDialog = new ACLContentDialog(null, "ACLMessage content", true); @@ -279,7 +342,6 @@ public void doZoomContent() { this.contentTextArea.update(); } - void setDefaultEnvelope() { itsMsg.setDefaultEnvelope(); setItsMsg(itsMsg); @@ -287,7 +349,6 @@ void setDefaultEnvelope() { logger.log(Logger.CONFIG, ":" + this.itsEnvelope.toString()); } - /** * Description of the Method * @@ -297,7 +358,6 @@ void senderButton_actionPerformed(ActionEvent e) { doShowSender(); } - /** * Description of the Method */ @@ -317,7 +377,6 @@ void doShowSender() { } - void doShowFrom() { ACLAIDDialog aidGui = new ACLAIDDialog(agent); AID currentAID = (itsMsg.getEnvelope().getFrom() != null ? itsMsg.getEnvelope().getFrom() : new AID()); @@ -333,7 +392,6 @@ void doShowFrom() { } } - /** * Description of the Method * @@ -343,7 +401,6 @@ void replyByButton_actionPerformed(ActionEvent e) { doShowTimeDialog(); } - /** * Description of the Method */ @@ -378,7 +435,6 @@ void doShowTimeDialog() { } - void doShowEnvTimeDialog() { ACLTimeChooserDialog t = new ACLTimeChooserDialog(); Date theDate = itsMsg.getEnvelope().getDate(); @@ -411,7 +467,6 @@ void doShowEnvTimeDialog() { } - /** * Description of the Method * @@ -425,7 +480,6 @@ void contentTextArea_mouseClicked(MouseEvent e) { } - /** * Description of the Method * @@ -435,7 +489,6 @@ void senderTextField_mouseClicked(MouseEvent e) { doShowSender(); } - /** * Description of the Method * @@ -445,37 +498,30 @@ void replybyTextField_mouseClicked(MouseEvent e) { doShowTimeDialog(); } - void defaultEnvelopeButton_actionPerformed(ActionEvent e) { setDefaultEnvelope(); } - void fromButton_actionPerformed(ActionEvent e) { doShowFrom(); } - void envDateButton_actionPerformed(ActionEvent e) { this.doShowEnvTimeDialog(); } - void contentZoomButton_actionPerformed(ActionEvent e) { doZoomContent(); } - void envFromTextField_mouseClicked(MouseEvent e) { doShowFrom(); } - void envDateTextField_mouseClicked(MouseEvent e) { this.doShowEnvTimeDialog(); } - /** * Description of the Method *

@@ -761,12 +807,13 @@ public void mouseClicked(MouseEvent e) { "ACC for inter-platform messaging."); } - private class ACLFileFilter extends javax.swing.filechooser.FileFilter { + private final String[] extensions = {".acl"}; + + public ACLFileFilter() { } - /** * The description of this filter. For example: "JPG and GIF Images" * @@ -777,95 +824,13 @@ public String getDescription() { return "ACLMessage files (*.acl)"; } - public boolean accept(File pathName) { if (pathName.isDirectory()) { return true; } else return pathName.isFile() && (pathName.getName().endsWith(".acl")); } - - - private final String[] extensions = {".acl"}; } - - GridBagLayout gridBagLayout1 = new GridBagLayout(); - JLabel senderLabel = new JLabel(); - JLabel receiverLabel = new JLabel(); - JLabel replytoLabel = new JLabel(); - JLabel contentLabel = new JLabel(); - JLabel languageLabel = new JLabel(); - JLabel encodingLabel = new JLabel(); - JLabel ontologyjLabel = new JLabel(); - JLabel protocolLabel = new JLabel(); - JLabel inreplytoLabel = new JLabel(); - JLabel replywithLabel = new JLabel(); - JLabel replybyLabel = new JLabel(); - JLabel userpropLabel = new JLabel(); - - JLabel convidLabel = new JLabel(); - JLabel performativeLabel = new JLabel(); - JButton senderButton = new JButton(); - JButton replyByButton = new JButton(); - JLabel toLabel = new JLabel(); - JLabel fromLabel = new JLabel(); - JLabel commentsLabel = new JLabel(); - JLabel aclRepreLabel = new JLabel(); - JLabel payLoadLabel = new JLabel(); - JLabel envDateLabel = new JLabel(); - JLabel intReceiversLabel = new JLabel(); - JLabel jLabel1 = new JLabel(); - JTextField envDateTextField = new JTextField(); - JButton defaultEnvelopeButton = new JButton(); - JButton fromButton = new JButton(); - JButton envDateButton = new JButton(); - JButton contentZoomButton = new JButton(); - ACLTextArea contentTextArea = new ACLTextArea(); - private final ACLTextField envACLReprTextField = new ACLTextField(); - private final ACLTextField envPayloadLengthTextField = new ACLTextField(); - private final ACLTextField envPayloadEncodingTextField = new ACLTextField(); - private final JTextField envFromTextField = new JTextField(); - private boolean editable = true; - private final JTextField senderTextField = new JTextField(); - private final ACLPropertyList userpropList = new ACLPropertyList(); - - private final ACLTextField conversationTextField = new ACLTextField(); - private final ACLTextField languageTextField = new ACLTextField(); - private final ACLTextField encodingTextField = new ACLTextField(); - private final ACLTextField ontologyTextField = new ACLTextField(); - private final ACLComboBox protocolComboBox = new ACLComboBox(); - private final ACLTextField inreplytoTextField = new ACLTextField(); - private final ACLTextField replywithTextField = new ACLTextField(); - private final JTextField replybyTextField = new JTextField(); - private final ACLComboBox performativesComboBox = new ACLComboBox(); - private ACLMessage itsMsg = new ACLMessage(ACLMessage.INFORM); - - private final Vector editsVector = new Vector<>(); - private final JPanel aclTab = new JPanel(); - private final GridBagLayout gridBagLayout2 = new GridBagLayout(); - private final JTabbedPane theTabbedPane = new JTabbedPane(); - private final JPanel envelopeTab = new JPanel(); - private final GridBagLayout gridBagLayout3 = new GridBagLayout(); - private final JScrollPane commentsScrollPane = new JScrollPane(); - private final EnvCommentsTextArea envCommentsTextArea = new EnvCommentsTextArea(); - - private final ImageIcon zoomIcon = - new ImageIcon(this.getClass().getResource("images/zoom.gif")); - private final ImageIcon dateIcon = - new ImageIcon(this.getClass().getResource("images/date.gif")); - private final ImageIcon envelopeIcon = - new ImageIcon(this.getClass().getResource("images/envelope.gif")); - private final ImageIcon messageIcon = - new ImageIcon(this.getClass().getResource("images/message.gif")); - private ACLAIDList envToList; - private ACLAIDList envIntendedReceiversList; - private Agent agent; - private ACLAIDList receiverList; - private ACLAIDList replytoList; - - private File currentDir; - private Envelope itsEnvelope; - } // ***EOF*** diff --git a/src/jade/tools/gui/ACLPropertyList.java b/src/jade/tools/gui/ACLPropertyList.java index ce36f6e..36e79e3 100644 --- a/src/jade/tools/gui/ACLPropertyList.java +++ b/src/jade/tools/gui/ACLPropertyList.java @@ -45,6 +45,20 @@ public class ACLPropertyList extends JPanel { + private final GridBagLayout gridBagLayout1 = new GridBagLayout(); + private final JList contentList = new JList<>(); + private final JButton viewButton = new JButton(); + private final JButton addButton = new JButton(); + private final JButton deleteButton = new JButton(); + private final ACLPropertyListCellRenderer aclPropertyListCellRenderer = new ACLPropertyListCellRenderer(); + private final ACLPropertyListener theDataListener = new ACLPropertyListener(); + private final JScrollPane contentScrollPane = new JScrollPane(); + private boolean editable = true; + private DefaultListModel listModel = new DefaultListModel<>(); + private String fieldName = ""; + private ACLMessage msg; + + /** * Constructor for the ACLPropertyList object */ @@ -56,7 +70,6 @@ public ACLPropertyList() { } } - /** * Sets the Editable attribute of the ACLPropertyList object * @@ -70,7 +83,6 @@ public void setEditable(boolean theBool) { } } - /** * Register ACLMessage * @@ -93,7 +105,6 @@ public void register(ACLMessage msg, String fieldName) { listModel.addListDataListener(theDataListener); } - /** * show a property */ @@ -118,7 +129,6 @@ void doView() { } } - /** * Description of the Method * @@ -128,7 +138,6 @@ void deleteButton_actionPerformed(ActionEvent e) { doDelete(); } - /** * delete a property */ @@ -140,7 +149,6 @@ void doDelete() { } } - /** * Adds a feature to the Button_actionPerformed attribute of the * ACLPropertyList object @@ -152,7 +160,6 @@ void addButton_actionPerformed(ActionEvent e) { doAdd(); } - /** * Add an property */ @@ -168,7 +175,6 @@ void doAdd() { this.validate(); } - /** * Description of the Method * @@ -178,7 +184,6 @@ void viewButton_actionPerformed(ActionEvent e) { doView(); } - /** * Description of the Method * @@ -191,7 +196,6 @@ void contentList_mouseClicked(MouseEvent e) { } - /** * Description of the Method * @@ -209,7 +213,6 @@ String filterEntry(String entry) { return result; } - /** * Description of the Method * @@ -233,7 +236,6 @@ void contentList_keyPressed(KeyEvent e) { } - /** * Description of the Method *

@@ -297,8 +299,10 @@ public void mouseClicked(MouseEvent e) { , GridBagConstraints.CENTER, GridBagConstraints.VERTICAL, new Insets(0, 0, 0, 0), 0, 0)); } - private class ACLPropertyListCellRenderer extends JLabel implements ListCellRenderer { + private ACLMessage msg; + + /** * Constructor for the ACLPropertyListCellRenderer object */ @@ -307,7 +311,6 @@ public ACLPropertyListCellRenderer() { setFont(new Font("Dialog", Font.PLAIN, 11)); } - /** * Gets the ListCellRendererComponent attribute of the * ACLPropertyListCellRenderer object @@ -329,7 +332,6 @@ public Component getListCellRendererComponent(JList list, Object value, int inde return this; } - /** * register the ACLMessage * @@ -338,14 +340,24 @@ public Component getListCellRendererComponent(JList list, Object value, int inde public void register(ACLMessage msg) { this.msg = msg; } - - - private ACLMessage msg; } - private class ACLPropertyDialog extends JDialog { + private final String CANCELLED = "cancelled"; + private final String CLOSED = "closed"; + private final GridBagLayout gridBagLayout1 = new GridBagLayout(); + private final JTextField keyTextField = new JTextField(); + private final JLabel jLabel1 = new JLabel(); + private final JButton okButton = new JButton(); + private final JButton cancelButton = new JButton(); + private final JLabel jLabel2 = new JLabel(); + private final JTextField valueTextField = new JTextField(); + private String OK = "ok"; + private String userAction; + private String itsAddress; + private String itskey; + private String itsvalue; /** * Constructor for the ACLPropertyDialog object */ @@ -359,7 +371,6 @@ public ACLPropertyDialog() { } } - /** * Gets the UserAction attribute of the ACLPropertyDialog object * @@ -369,6 +380,14 @@ public String getUserAction() { return userAction; } + /** + * Sets the UserAction attribute of the ACLPropertyDialog object + * + * @param newUserAction The new UserAction value + */ + public void setUserAction(String newUserAction) { + userAction = newUserAction; + } /** * Gets the OK attribute of the ACLPropertyDialog object @@ -379,7 +398,6 @@ public boolean getOK() { return userAction.equals(OK); } - /** * Gets the Itskey attribute of the ACLPropertyDialog object * @@ -389,6 +407,15 @@ public String getItskey() { return itskey; } + /** + * Sets the Itskey attribute of the ACLPropertyDialog object + * + * @param newItskey The new Itskey value + */ + public void setItskey(String newItskey) { + keyTextField.setText(newItskey); + itskey = newItskey; + } /** * Gets the Itsvalue attribute of the ACLPropertyDialog object @@ -399,6 +426,15 @@ public String getItsvalue() { return itsvalue; } + /** + * Sets the Itsvalue attribute of the ACLPropertyDialog object + * + * @param newItsvalue The new Itsvalue value + */ + public void setItsvalue(String newItsvalue) { + valueTextField.setText(newItsvalue); + itsvalue = newItsvalue; + } /** * Sets the Editable attribute of the ACLPropertyDialog object @@ -413,28 +449,6 @@ public void setEditable(boolean theBool) { } } - - /** - * Sets the UserAction attribute of the ACLPropertyDialog object - * - * @param newUserAction The new UserAction value - */ - public void setUserAction(String newUserAction) { - userAction = newUserAction; - } - - - /** - * Sets the Itskey attribute of the ACLPropertyDialog object - * - * @param newItskey The new Itskey value - */ - public void setItskey(String newItskey) { - keyTextField.setText(newItskey); - itskey = newItskey; - } - - /** * Sets the Edit attribute of the ACLPropertyDialog object */ @@ -442,18 +456,6 @@ public void setEdit() { keyTextField.setEditable(false); } - - /** - * Sets the Itsvalue attribute of the ACLPropertyDialog object - * - * @param newItsvalue The new Itsvalue value - */ - public void setItsvalue(String newItsvalue) { - valueTextField.setText(newItsvalue); - itsvalue = newItsvalue; - } - - /** * Description of the Method *

@@ -490,7 +492,6 @@ void jbInit() { , GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, -16, 0, 0), 0, 0)); } - /** * Description of the Method * @@ -501,7 +502,6 @@ void cancelButton_actionPerformed(ActionEvent e) { setVisible(false); } - /** * Description of the Method * @@ -514,26 +514,8 @@ void okButton_actionPerformed(ActionEvent e) { setVisible(false); } - - private String OK = "ok"; - private final String CANCELLED = "cancelled"; - private final String CLOSED = "closed"; - - private final GridBagLayout gridBagLayout1 = new GridBagLayout(); - private final JTextField keyTextField = new JTextField(); - private final JLabel jLabel1 = new JLabel(); - private final JButton okButton = new JButton(); - private final JButton cancelButton = new JButton(); - private final JLabel jLabel2 = new JLabel(); - private final JTextField valueTextField = new JTextField(); - private String userAction; - private String itsAddress; - private String itskey; - private String itsvalue; - } - /** * This class is the ListDataListener of the ACLPropertyList. * @@ -542,6 +524,10 @@ void okButton_actionPerformed(ActionEvent e) { */ private class ACLPropertyListener implements ListDataListener { + private String fieldName = ""; + private String theRemovedKey, theChangedKey, theChangedValue; + private ACLMessage itsMsg; + /** * Description of the Method * @@ -553,7 +539,6 @@ public void register(Object obj, String fieldName) { this.fieldName = fieldName; } - /** * Description of the Method * @@ -566,7 +551,6 @@ public void intervalAdded(ListDataEvent parm1) { itsMsg.addUserDefinedParameter(theChangedKey, theChangedValue); } - /** * Description of the Method * @@ -578,7 +562,6 @@ public void registerChangedProperty(String theChangedKey, String theChangedValue this.theChangedValue = theChangedValue; } - /** * Description of the Method * @@ -588,7 +571,6 @@ public void registerRemovedKey(String theRemovedKey) { this.theRemovedKey = theRemovedKey; } - /** * Description of the Method * @@ -600,7 +582,6 @@ public void intervalRemoved(ListDataEvent parm1) { itsMsg.removeUserDefinedParameter(theRemovedKey); } - /** * Description of the Method * @@ -612,29 +593,7 @@ public void contentsChanged(ListDataEvent parm1) { itsMsg.removeUserDefinedParameter(theChangedKey); itsMsg.addUserDefinedParameter(theChangedKey, theChangedValue); } - - - private String fieldName = ""; - private String theRemovedKey, theChangedKey, theChangedValue; - private ACLMessage itsMsg; } - - private boolean editable = true; - - private final GridBagLayout gridBagLayout1 = new GridBagLayout(); - private final JList contentList = new JList<>(); - private final JButton viewButton = new JButton(); - private final JButton addButton = new JButton(); - private final JButton deleteButton = new JButton(); - - private DefaultListModel listModel = new DefaultListModel<>(); - private final ACLPropertyListCellRenderer aclPropertyListCellRenderer = new ACLPropertyListCellRenderer(); - private final ACLPropertyListener theDataListener = new ACLPropertyListener(); - private final JScrollPane contentScrollPane = new JScrollPane(); - - private String fieldName = ""; - private ACLMessage msg; - } // ***EOF*** diff --git a/src/jade/tools/gui/ACLSLTokenMarker.java b/src/jade/tools/gui/ACLSLTokenMarker.java index 0eaaf18..8f1abab 100644 --- a/src/jade/tools/gui/ACLSLTokenMarker.java +++ b/src/jade/tools/gui/ACLSLTokenMarker.java @@ -38,18 +38,68 @@ public class ACLSLTokenMarker { + // public members + public final static byte S_ONE = ACLToken.INTERNAL_FIRST; + public final static byte S_TWO = (byte) (ACLToken.INTERNAL_FIRST + 1); + public final static byte S_END = (byte) (ACLToken.INTERNAL_FIRST + 2); + private static KeywordMap aclSLKeywords; + // private members + private final KeywordMap keywords; + /** + * The first token in the list. This should be used as the return value + * from markTokens(). + */ + protected ACLToken firstToken; + /** + * The last token in the list. New tokens are added here. This should be + * set to null before a new line is to be tokenized. + */ + protected ACLToken lastToken; + /** + * An array for storing information about lines. It is enlarged and shrunk + * automatically by the insertLines() and deleteLines() + * methods. + */ + protected LineInfo[] lineInfo; + /** + * The length of the lineInfo array. + */ + protected int length; + + + /** + * Creates a new TokenMarker. This DOES NOT create a lineInfo + * array; an initial call to insertLines() does that. + * + * @param index Description of Parameter + */ + /** + * The last tokenized line. + */ + protected int lastLine; + /** + * True if the next line should be painted. + */ + protected boolean nextLineRequested; + private byte token; + private int lastOffset; + private int lastKeyword; + private char matchChar; + private boolean matchCharBracket; + private boolean matchSpacesAllowed; + public ACLSLTokenMarker() { this(getKeywords()); lastLine = -1; } + // protected members public ACLSLTokenMarker(KeywordMap keywords) { lastLine = -1; this.keywords = keywords; } - private static KeywordMap getKeywords() { if (aclSLKeywords == null) { aclSLKeywords = new KeywordMap(false); @@ -98,7 +148,6 @@ private static KeywordMap getKeywords() { return aclSLKeywords; } - /** * Returns true if the next line should be repainted. This will return true * after a line has been tokenized that starts a multiline token that @@ -110,7 +159,6 @@ public boolean isNextLineRequested() { return nextLineRequested; } - public ACLToken markTokens(Segment line, int lineIndex) { if (lineIndex >= length) { throw new IllegalArgumentException("Tokenizing invalid line: " @@ -174,7 +222,6 @@ would set nextLineRequested (because the line end return firstToken; } - /** * Returns if the token marker supports tokens that span multiple lines. If * this is true, the object using this token marker is required to pass all @@ -190,7 +237,6 @@ public boolean supportsMultilineTokens() { return true; } - /** * Informs the token marker that lines have been inserted into the * document. This inserts a gap in the lineInfo array. @@ -214,7 +260,6 @@ public void insertLines(int index, int lines) { } - /** * Informs the token marker that line have been deleted from the document. * This removes the lines in question from the lineInfo array. @@ -232,7 +277,6 @@ public void deleteLines(int index, int lines) { index, lineInfo.length - len); } - public byte markTokensImpl(byte _token, Segment line, int lineIndex) { char[] array = line.array; int offset = line.offset; @@ -679,14 +723,6 @@ public byte markTokensImpl(byte _token, Segment line, int lineIndex) { return token; } - - /** - * Creates a new TokenMarker. This DOES NOT create a lineInfo - * array; an initial call to insertLines() does that. - * - * @param index Description of Parameter - */ - /** * Creates a new TokenMarker. This DOES NOT create a lineInfo * array; an initial call to insertLines() does that. @@ -731,7 +767,6 @@ protected void ensureCapacity(int index) { } } - /** * Adds a token to the token list. * @@ -764,7 +799,6 @@ protected void addToken(int length, byte id) { } } - private boolean doKeyword(Segment line, int i, char c) { int i1 = i + 1; @@ -807,9 +841,14 @@ private boolean doKeyword(Segment line, int i, char c) { return false; } - // ***EOF*** private static class KeywordMap { + private final Keyword[] map; + // protected members + protected int mapLength; + private boolean ignoreCase; + + /** * Creates a new KeywordMap. * @@ -834,7 +873,6 @@ public KeywordMap(boolean ignoreCase, int mapLength) { map = new Keyword[mapLength]; } - /** * Returns true if the keyword map is set to be case insensitive, false * otherwise. @@ -845,7 +883,6 @@ public boolean getIgnoreCase() { return ignoreCase; } - /** * Sets if the keyword map should be case insensitive. * @@ -856,7 +893,6 @@ public void setIgnoreCase(boolean ignoreCase) { this.ignoreCase = ignoreCase; } - /** * Looks up a key. * @@ -884,7 +920,6 @@ public byte lookup(Segment text, int offset, int length) { return ACLToken.NULL; } - /** * Adds a key-value mapping. * @@ -896,14 +931,12 @@ public void add(String keyword, byte id) { map[key] = new Keyword(keyword.toCharArray(), id, map[key]); } - protected int getStringMapKey(String s) { return (Character.toUpperCase(s.charAt(0)) + Character.toUpperCase(s.charAt(s.length() - 1))) % mapLength; } - protected int getSegmentMapKey(Segment s, int off, int len) { return (Character.toUpperCase(s.array[off]) + Character.toUpperCase(s.array[off + len - 1])) @@ -912,26 +945,17 @@ protected int getSegmentMapKey(Segment s, int off, int len) { // private members class Keyword { + public char[] keyword; + public byte id; + public Keyword next; public Keyword(char[] keyword, byte id, Keyword next) { this.keyword = keyword; this.id = id; this.next = next; } - - - public char[] keyword; - public byte id; - public Keyword next; } - - // protected members - protected int mapLength; - - private final Keyword[] map; - private boolean ignoreCase; } - /** * Inner class for storing information about tokenized lines. * @@ -939,13 +963,24 @@ public Keyword(char[] keyword, byte id, Keyword next) { * @created June 8, 2002 */ public class LineInfo { + /** + * The id of the last token of the line. + */ + public byte token; + /** + * This is for use by the token marker implementations themselves. It can + * be used to store anything that is an object and that needs to exist on + * a per-line basis. + */ + public Object obj; + + /** * Creates a new LineInfo object with token = Token.NULL and obj = null. */ public LineInfo() { } - /** * Creates a new LineInfo object with the specified parameters. * @@ -956,73 +991,7 @@ public LineInfo(byte token, Object obj) { this.token = token; this.obj = obj; } - - - /** - * The id of the last token of the line. - */ - public byte token; - - /** - * This is for use by the token marker implementations themselves. It can - * be used to store anything that is an object and that needs to exist on - * a per-line basis. - */ - public Object obj; } - - // public members - public final static byte S_ONE = ACLToken.INTERNAL_FIRST; - public final static byte S_TWO = (byte) (ACLToken.INTERNAL_FIRST + 1); - public final static byte S_END = (byte) (ACLToken.INTERNAL_FIRST + 2); - - private static KeywordMap aclSLKeywords; - - // protected members - - /** - * The first token in the list. This should be used as the return value - * from markTokens(). - */ - protected ACLToken firstToken; - - /** - * The last token in the list. New tokens are added here. This should be - * set to null before a new line is to be tokenized. - */ - protected ACLToken lastToken; - - /** - * An array for storing information about lines. It is enlarged and shrunk - * automatically by the insertLines() and deleteLines() - * methods. - */ - protected LineInfo[] lineInfo; - - /** - * The length of the lineInfo array. - */ - protected int length; - - /** - * The last tokenized line. - */ - protected int lastLine; - - /** - * True if the next line should be painted. - */ - protected boolean nextLineRequested; - - // private members - private final KeywordMap keywords; - private byte token; - private int lastOffset; - private int lastKeyword; - private char matchChar; - private boolean matchCharBracket; - private boolean matchSpacesAllowed; - } // ***EOF*** diff --git a/src/jade/tools/gui/ACLStatisticsFrame.java b/src/jade/tools/gui/ACLStatisticsFrame.java index 655f083..d71d749 100644 --- a/src/jade/tools/gui/ACLStatisticsFrame.java +++ b/src/jade/tools/gui/ACLStatisticsFrame.java @@ -48,6 +48,17 @@ public class ACLStatisticsFrame extends JFrame { + GridBagLayout gridBagLayout1 = new GridBagLayout(); + JLabel jLabel1 = new JLabel(); + JScrollPane tableScrollPane = new JScrollPane(); + JButton closeButton = new JButton(); + JComboBox itemComboBox = new JComboBox<>(); + JTable statisticsTable = new JTable(); + DefaultComboBoxModel itemBoxModel = new DefaultComboBoxModel<>(); + DefaultTreeModel aclTreeModel; + ACLStatiscticsTableModel aclTableModel; + + /** * Constructor for the ACLStatisticsFrame object * @@ -75,7 +86,6 @@ public ACLStatisticsFrame(DefaultTreeModel aclTreeModel) { } } - /** * Description of the Method * @@ -88,7 +98,6 @@ public static void show(DefaultTreeModel aclModel) { } - /** * Description of the Method * @@ -98,7 +107,6 @@ void closeButton_actionPerformed(ActionEvent e) { this.setVisible(false); } - /** * Description of the Method * @@ -115,7 +123,6 @@ void itemComboBox_itemStateChanged(ItemEvent e) { this.statisticsTable.updateUI(); } - /** * Sets the FrameIcon attribute of the ACLFrame object * @@ -126,7 +133,6 @@ private void setFrameIcon(String iconpath) { setIconImage(image.getImage()); } - /** * Description of the Method * @@ -158,9 +164,13 @@ private void jbInit() throws Exception { , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0)); } - private class ACLStatiscticsTableModel extends DefaultTableModel { + HashMap countTable = new HashMap<>(); + String theItem; + DefaultTreeModel aclModel; + + /** * Constructor for the StatisticsTableModel object * @@ -171,7 +181,6 @@ public ACLStatiscticsTableModel(DefaultTreeModel aclModel) { fillThis("performative"); } - /** * Gets the ColumnCount attribute of the StatisticsTableModel object * @@ -181,7 +190,6 @@ public int getColumnCount() { return 2; } - /** * Gets the ColumnName attribute of the StatisticsTableModel object * @@ -198,7 +206,6 @@ public String getColumnName(int column) { return "?"; } - /** * Gets the ValueAt attribute of the StatisticsTableModel object * @@ -220,7 +227,6 @@ public Object getValueAt(int row, int column) { return result; } - /** * Description of the Method * @@ -277,17 +283,13 @@ public void fillThis(String item) { } - - HashMap countTable = new HashMap<>(); - - String theItem; - DefaultTreeModel aclModel; - } - private class ACLStatisticsFrame_closeButton_actionAdapter implements ActionListener { + ACLStatisticsFrame adaptee; + + /** * Constructor for the ACLStatisticsFrame_closeButton_actionAdapter * object @@ -298,7 +300,6 @@ private class ACLStatisticsFrame_closeButton_actionAdapter implements ActionList this.adaptee = adaptee; } - /** * Description of the Method * @@ -307,12 +308,8 @@ private class ACLStatisticsFrame_closeButton_actionAdapter implements ActionList public void actionPerformed(ActionEvent e) { adaptee.closeButton_actionPerformed(e); } - - - ACLStatisticsFrame adaptee; } - private class SomeLabelRenderer extends JLabel implements ListCellRenderer { /** * Constructor for the SomeLabelRenderer object @@ -347,22 +344,22 @@ public Component getListCellRendererComponent(JList list, Object value, int i } } - - GridBagLayout gridBagLayout1 = new GridBagLayout(); - JLabel jLabel1 = new JLabel(); - JScrollPane tableScrollPane = new JScrollPane(); - JButton closeButton = new JButton(); - JComboBox itemComboBox = new JComboBox<>(); - JTable statisticsTable = new JTable(); - DefaultComboBoxModel itemBoxModel = new DefaultComboBoxModel<>(); - DefaultTreeModel aclTreeModel; - ACLStatiscticsTableModel aclTableModel; - } class ACLStatisticsFrame_itemComboBox_itemAdapter implements ItemListener { + /** + * This class contains a table model for the ACLStaticsFrame + *

+ * author Chris van Aart - Acklin B.V., the Netherlands + * + * @since April 26, 2002 + */ + + ACLStatisticsFrame adaptee; + + /** * Constructor for the ACLStatisticsFrame_itemComboBox_itemAdapter object * @@ -372,7 +369,6 @@ class ACLStatisticsFrame_itemComboBox_itemAdapter implements ItemListener { this.adaptee = adaptee; } - /** * Description of the Method * @@ -382,17 +378,6 @@ public void itemStateChanged(ItemEvent e) { adaptee.itemComboBox_itemStateChanged(e); } - - /** - * This class contains a table model for the ACLStaticsFrame - *

- * author Chris van Aart - Acklin B.V., the Netherlands - * - * @since April 26, 2002 - */ - - ACLStatisticsFrame adaptee; - // ***EOF*** } // ***EOF*** diff --git a/src/jade/tools/gui/ACLSyntaxDocument.java b/src/jade/tools/gui/ACLSyntaxDocument.java index 41e2065..0d0e6ce 100644 --- a/src/jade/tools/gui/ACLSyntaxDocument.java +++ b/src/jade/tools/gui/ACLSyntaxDocument.java @@ -40,6 +40,9 @@ * @since June 14, 2002 */ public class ACLSyntaxDocument extends PlainDocument { + // protected members + protected ACLSLTokenMarker tokenMarker; + /** * Returns the token marker that is to be used to split lines of this * document up into tokens. May return null if this document is not to be @@ -51,7 +54,6 @@ public ACLSLTokenMarker getTokenMarker() { return tokenMarker; } - /** * Sets the token marker that is to be used to split lines of this document * up into tokens. May throw an exception if this is not supported for this @@ -69,7 +71,6 @@ public void setTokenMarker(ACLSLTokenMarker tm) { tokenizeLines(); } - /** * Reparses the document, by passing all lines to the token marker. This * should be called after the document is first loaded. @@ -78,7 +79,6 @@ public void tokenizeLines() { tokenizeLines(0, getDefaultRootElement().getElementCount()); } - /** * Reparses the document, by passing the specified lines to the token * marker. This should be called after a large quantity of text is first @@ -109,7 +109,6 @@ public void tokenizeLines(int start, int len) { } } - /** * We overwrite this method to update the token marker state immediately so * that any event listeners get a consistent token marker. @@ -131,7 +130,6 @@ protected void fireInsertUpdate(DocumentEvent evt) { super.fireInsertUpdate(evt); } - /** * We overwrite this method to update the token marker state immediately so * that any event listeners get a consistent token marker. @@ -153,8 +151,5 @@ protected void fireRemoveUpdate(DocumentEvent evt) { super.fireRemoveUpdate(evt); } - // protected members - protected ACLSLTokenMarker tokenMarker; - } // ***EOF*** diff --git a/src/jade/tools/gui/ACLSytntaxStyle.java b/src/jade/tools/gui/ACLSytntaxStyle.java index 1115318..40cb7ba 100644 --- a/src/jade/tools/gui/ACLSytntaxStyle.java +++ b/src/jade/tools/gui/ACLSytntaxStyle.java @@ -38,6 +38,16 @@ */ public class ACLSytntaxStyle { + // private members + private final Color color; + private final boolean italics; + private final boolean bold; + JComponent theComp; + private Font lastFont; + private Font lastStyledFont; + private FontMetrics fontMetrics; + + public ACLSytntaxStyle(Color color, boolean italics, boolean bold, JComponent theComp) { this.color = color; this.italics = italics; @@ -45,7 +55,6 @@ public ACLSytntaxStyle(Color color, boolean italics, boolean bold, JComponent th this.theComp = theComp; } - /** * Returns the color specified in this style. * @@ -55,7 +64,6 @@ public Color getColor() { return color; } - /** * Returns true if italics is enabled for this style. * @@ -65,7 +73,6 @@ public boolean isItalics() { return italics; } - /** * Returns true if boldface is enabled for this style. * @@ -75,7 +82,6 @@ public boolean isBold() { return bold; } - /** * Returns the specified font, but with the style's bold and italic flags * applied. @@ -99,7 +105,6 @@ public Font getStyledFont(Font font) { return lastStyledFont; } - /** * Returns the font metrics for the styled font. * @@ -123,7 +128,6 @@ public FontMetrics getFontMetrics(Font font) { return fontMetrics; } - /** * Sets the foreground color and font of the specified graphics context to * that specified in this style. @@ -137,7 +141,6 @@ public void setGraphicsFlags(Graphics gfx, Font font) { gfx.setColor(color); } - /** * Returns a string representation of this object. * @@ -148,15 +151,5 @@ public String toString() { (italics ? ",italics" : "") + (bold ? ",bold" : "") + "]"; } - - JComponent theComp; - - // private members - private final Color color; - private final boolean italics; - private final boolean bold; - private Font lastFont; - private Font lastStyledFont; - private FontMetrics fontMetrics; } // ***EOF*** diff --git a/src/jade/tools/gui/ACLTextArea.java b/src/jade/tools/gui/ACLTextArea.java index 3880870..f27f694 100644 --- a/src/jade/tools/gui/ACLTextArea.java +++ b/src/jade/tools/gui/ACLTextArea.java @@ -51,6 +51,46 @@ * @since June 8, 2002 */ public class ACLTextArea extends JComponent { + // protected members + protected static String CENTER = "center"; + protected static String RIGHT = "right"; + protected static String BOTTOM = "bottom"; + protected static ACLTextArea focusedComponent; + protected static Timer caretTimer; + protected ACLTextAreaPainter painter; + protected JPopupMenu popup; + protected Timer scrollTimer; + protected EventListenerList listenerList; + protected MutableCaretEvent caretEvent; + protected boolean caretBlinks; + protected boolean caretVisible; + protected boolean blink; + protected boolean editable; + protected int firstLine; + protected int visibleLines; + protected int electricScroll; + protected int horizontalOffset; + protected JScrollBar vertical; + protected JScrollBar horizontal; + protected boolean scrollBarsInitialized; + protected InputHandler inputHandler; + protected ACLSyntaxDocument document; + protected DocumentHandler documentHandler; + protected Segment lineSegment; + protected int selectionStart; + protected int selectionStartLine; + protected int selectionEnd; + protected int selectionEndLine; + protected boolean biasLeft; + protected int bracketPosition; + protected int bracketLine; + protected int magicCaret; + protected boolean overwrite; + private String contentLanguage = ""; + private ACLMessage msg; + private String fieldName; + + /** * Creates a new JEditTextArea with the default settings. */ @@ -108,7 +148,6 @@ public ACLTextArea() { setTokenMarker(new ACLSLTokenMarker()); } - /** * Returns if this component can be traversed by pressing the Tab key. This * returns false. @@ -121,7 +160,6 @@ public final boolean isManagingFocus() { return true; } - /** * Returns the object responsible for painting this text area. * @@ -131,7 +169,6 @@ public final ACLTextAreaPainter getPainter() { return painter; } - /** * Returns the input handler. * @@ -141,6 +178,22 @@ public final InputHandler getInputHandler() { return inputHandler; } + /** + * Sets the input handler. + * + * @param inputHandler The new input handler + */ + public void setInputHandler(InputHandler inputHandler) { + if (this.inputHandler != null) { + removeKeyListener(this.inputHandler); + } + + if (inputHandler != null) { + addKeyListener(inputHandler); + } + + this.inputHandler = inputHandler; + } /** * Returns true if the caret is blinking, false otherwise. @@ -151,6 +204,19 @@ public final boolean isCaretBlinkEnabled() { return caretBlinks; } + /** + * Toggles caret blinking. + * + * @param caretBlinks True if the caret should blink, false otherwise + */ + public void setCaretBlinkEnabled(boolean caretBlinks) { + this.caretBlinks = caretBlinks; + if (!caretBlinks) { + blink = false; + } + + painter.invalidateSelectedLines(); + } /** * Returns true if the caret is visible, false otherwise. @@ -161,6 +227,18 @@ public final boolean isCaretVisible() { return (!caretBlinks || blink) && caretVisible; } + /** + * Sets if the caret should be visible. + * + * @param caretVisible True if the caret should be visible, false + * otherwise + */ + public void setCaretVisible(boolean caretVisible) { + this.caretVisible = caretVisible; + blink = true; + + painter.invalidateSelectedLines(); + } /** * Returns the number of lines from the top and button of the text area @@ -172,6 +250,16 @@ public final int getElectricScroll() { return electricScroll; } + /** + * Sets the number of lines from the top and bottom of the text area that + * are always visible + * + * @param electricScroll The number of lines always visible from the top + * or bottom + */ + public final void setElectricScroll(int electricScroll) { + this.electricScroll = electricScroll; + } /** * Returns the line displayed at the text area's origin. @@ -182,6 +270,24 @@ public final int getFirstLine() { return firstLine; } + /** + * Sets the line displayed at the text area's origin without updating the + * scroll bars. + * + * @param firstLine The new FirstLine value + */ + public void setFirstLine(int firstLine) { + if (firstLine == this.firstLine) { + return; + } + int oldFirstLine = this.firstLine; + this.firstLine = firstLine; + if (firstLine != vertical.getValue()) { + updateScrollBars(); + } + painter.scrollRepaint(oldFirstLine, firstLine); + painter.repaint(); + } /** * Returns the number of lines visible in this text area. @@ -192,7 +298,6 @@ public final int getVisibleLines() { return visibleLines; } - /** * Returns the horizontal offset of drawn lines. * @@ -202,6 +307,24 @@ public final int getHorizontalOffset() { return horizontalOffset; } + /** + * Sets the horizontal offset of drawn lines. This can be used to implement + * horizontal scrolling. + * + * @param horizontalOffset offset The new horizontal offset + */ + public void setHorizontalOffset(int horizontalOffset) { + if (horizontalOffset == this.horizontalOffset) { + return; + } + this.horizontalOffset = horizontalOffset; + if (horizontalOffset != horizontal.getValue()) { + updateScrollBars(); + } + + painter.invalidateLineRange(firstLine, firstLine + visibleLines); + painter.repaint(); + } /** * Returns the document this text area is editing. @@ -212,6 +335,28 @@ public final ACLSyntaxDocument getDocument() { return document; } + /** + * Sets the document this text area is editing. + * + * @param document The document + */ + public void setDocument(ACLSyntaxDocument document) { + if (this.document == document) { + return; + } + if (this.document != null) { + this.document.removeDocumentListener(documentHandler); + } + + this.document = document; + + document.addDocumentListener(documentHandler); + + select(0, 0); + updateScrollBars(); + painter.invalidateOffscreen(); + painter.repaint(); + } /** * Returns the document's token marker. Equivalent to calling getDocument().getTokenMarker() @@ -223,6 +368,15 @@ public final ACLSLTokenMarker getTokenMarker() { return document.getTokenMarker(); } + /** + * Sets the document's token marker. Equivalent to caling getDocument().setTokenMarker() + * . + * + * @param tokenMarker The token marker + */ + public final void setTokenMarker(ACLSLTokenMarker tokenMarker) { + document.setTokenMarker(tokenMarker); + } /** * Returns the length of the document. Equivalent to calling getDocument().getLength() @@ -234,7 +388,6 @@ public final int getDocumentLength() { return document.getLength(); } - /** * Returns the number of lines in the document. * @@ -244,7 +397,6 @@ public final int getLineCount() { return document.getDefaultRootElement().getElementCount(); } - /** * Returns the line containing the specified offset. * @@ -255,7 +407,6 @@ public final int getLineOfOffset(int offset) { return document.getDefaultRootElement().getElementIndex(offset); } - /** * Returns the specified substring of the document. * @@ -271,7 +422,6 @@ public final String getText(int start, int len) { } } - /** * Copies the specified substring of the document into a segment. If the * offsets are invalid, the segment will contain a null string. @@ -288,7 +438,6 @@ public final void getText(int start, int len, Segment segment) { } } - /** * Returns the text on the specified line. * @@ -300,7 +449,6 @@ public final String getLineText(int lineIndex) { return getText(start, getLineEndOffset(lineIndex) - start - 1); } - /** * Copies the text on the specified line into a segment. If the line is * invalid, the segment will contain a null string. @@ -313,7 +461,6 @@ public final void getLineText(int lineIndex, Segment segment) { getText(start, getLineEndOffset(lineIndex) - start - 1, segment); } - /** * Returns the selection start offset. * @@ -323,6 +470,16 @@ public final int getSelectionStart() { return selectionStart; } + /** + * Sets the selection start. The new selection will be the new selection + * start and the old selection end. + * + * @param selectionStart The selection start + * @see #select(int, int) + */ + public final void setSelectionStart(int selectionStart) { + select(selectionStart, selectionEnd); + } /** * Returns the selection start line. @@ -333,7 +490,6 @@ public final int getSelectionStartLine() { return selectionStartLine; } - /** * Returns the selection end offset. * @@ -343,6 +499,16 @@ public final int getSelectionEnd() { return selectionEnd; } + /** + * Sets the selection end. The new selection will be the old selection + * start and the bew selection end. + * + * @param selectionEnd The selection end + * @see #select(int, int) + */ + public final void setSelectionEnd(int selectionEnd) { + select(selectionStart, selectionEnd); + } /** * Returns the selection end line. @@ -353,7 +519,6 @@ public final int getSelectionEndLine() { return selectionEndLine; } - /** * Returns the caret position. This will either be the selection start or * the selection end, depending on which direction the selection was made @@ -365,6 +530,16 @@ public final int getCaretPosition() { return (biasLeft ? selectionStart : selectionEnd); } + /** + * Sets the caret position. The new selection will consist of the caret + * position only (hence no text will be selected) + * + * @param caret The caret position + * @see #select(int, int) + */ + public final void setCaretPosition(int caret) { + select(caret, caret); + } /** * Returns the caret line. @@ -375,7 +550,6 @@ public final int getCaretLine() { return (biasLeft ? selectionStartLine : selectionEndLine); } - /** * Returns the mark position. This will be the opposite selection bound to * the caret position. @@ -387,7 +561,6 @@ public final int getMarkPosition() { return (biasLeft ? selectionEnd : selectionStart); } - /** * Returns the mark line. * @@ -397,7 +570,6 @@ public final int getMarkLine() { return (biasLeft ? selectionEndLine : selectionStartLine); } - /** * Returns the selected text, or null if no selection is active. * @@ -411,129 +583,39 @@ public final String getSelectedText() { selectionEnd - selectionStart); } - - /** - * Returns true if this text area is editable, false otherwise. - * - * @return The Editable value - */ - public final boolean isEditable() { - return editable; - } - - - /** - * Returns the right click popup menu. - * - * @return The RightClickPopup value - */ - public final JPopupMenu getRightClickPopup() { - return popup; - } - - - /** - * Returns the `magic' caret position. This can be used to preserve the - * column position when moving up and down lines. - * - * @return The MagicCaretPosition value - */ - public final int getMagicCaretPosition() { - return magicCaret; - } - - /** - * Returns true if overwrite mode is enabled, false otherwise. - * - * @return The OverwriteEnabled value - */ - public final boolean isOverwriteEnabled() { - return overwrite; - } - - - /** - * Returns the position of the highlighted bracket (the bracket matching - * the one before the caret) - * - * @return The BracketPosition value - */ - public final int getBracketPosition() { - return bracketPosition; - } - - - /** - * Returns the line of the highlighted bracket (the bracket matching the - * one before the caret) - * - * @return The BracketLine value - */ - public final int getBracketLine() { - return bracketLine; - } - - - /** - * Sets the number of lines from the top and bottom of the text area that - * are always visible - * - * @param electricScroll The number of lines always visible from the top - * or bottom - */ - public final void setElectricScroll(int electricScroll) { - this.electricScroll = electricScroll; - } - - - /** - * Sets the document's token marker. Equivalent to caling getDocument().setTokenMarker() - * . - * - * @param tokenMarker The token marker - */ - public final void setTokenMarker(ACLSLTokenMarker tokenMarker) { - document.setTokenMarker(tokenMarker); - } - - - /** - * Sets the selection start. The new selection will be the new selection - * start and the old selection end. - * - * @param selectionStart The selection start - * @see #select(int, int) - */ - public final void setSelectionStart(int selectionStart) { - select(selectionStart, selectionEnd); - } - - - /** - * Sets the selection end. The new selection will be the old selection - * start and the bew selection end. + * Replaces the selection with the specified text. * - * @param selectionEnd The selection end - * @see #select(int, int) + * @param selectedText The replacement text for the selection */ - public final void setSelectionEnd(int selectionEnd) { - select(selectionStart, selectionEnd); - } + public void setSelectedText(String selectedText) { + if (!editable) { + throw new InternalError("Text component" + + " read only"); + } + try { + document.remove(selectionStart, + selectionEnd - selectionStart); + document.insertString(selectionStart, + selectedText, null); + setCaretPosition(selectionEnd); + } catch (BadLocationException bl) { + bl.printStackTrace(); + throw new InternalError("Cannot replace" + + " selection"); + } + } /** - * Sets the caret position. The new selection will consist of the caret - * position only (hence no text will be selected) + * Returns true if this text area is editable, false otherwise. * - * @param caret The caret position - * @see #select(int, int) + * @return The Editable value */ - public final void setCaretPosition(int caret) { - select(caret, caret); + public final boolean isEditable() { + return editable; } - /** * Sets if this component is editable. * @@ -544,6 +626,14 @@ public final void setEditable(boolean editable) { this.editable = editable; } + /** + * Returns the right click popup menu. + * + * @return The RightClickPopup value + */ + public final JPopupMenu getRightClickPopup() { + return popup; + } /** * Sets the right click popup menu. @@ -554,6 +644,15 @@ public final void setRightClickPopup(JPopupMenu popup) { this.popup = popup; } + /** + * Returns the `magic' caret position. This can be used to preserve the + * column position when moving up and down lines. + * + * @return The MagicCaretPosition value + */ + public final int getMagicCaretPosition() { + return magicCaret; + } /** * Sets the `magic' caret position. This can be used to preserve the column @@ -565,6 +664,14 @@ public final void setMagicCaretPosition(int magicCaret) { this.magicCaret = magicCaret; } + /** + * Returns true if overwrite mode is enabled, false otherwise. + * + * @return The OverwriteEnabled value + */ + public final boolean isOverwriteEnabled() { + return overwrite; + } /** * Sets if overwrite mode should be enabled. @@ -577,6 +684,25 @@ public final void setOverwriteEnabled(boolean overwrite) { painter.invalidateSelectedLines(); } + /** + * Returns the position of the highlighted bracket (the bracket matching + * the one before the caret) + * + * @return The BracketPosition value + */ + public final int getBracketPosition() { + return bracketPosition; + } + + /** + * Returns the line of the highlighted bracket (the bracket matching the + * one before the caret) + * + * @return The BracketLine value + */ + public final int getBracketLine() { + return bracketLine; + } /** * Blinks the caret. @@ -591,7 +717,6 @@ public final void blinkCaret() { } - /** * Recalculates the number of visible lines. This should not be called * directly. @@ -609,7 +734,6 @@ public final void recalculateVisibleLines() { updateScrollBars(); } - /** * Selects all text in the document. */ @@ -617,7 +741,6 @@ public final void selectAll() { select(0, getDocumentLength()); } - /** * Adds a caret change listener to this text area. * @@ -627,7 +750,6 @@ public final void addCaretListener(CaretListener listener) { listenerList.add(CaretListener.class, listener); } - /** * Removes a caret change listener from this text area. * @@ -637,7 +759,6 @@ public final void removeCaretListener(CaretListener listener) { listenerList.remove(CaretListener.class, listener); } - /** * Returns the start offset of the specified line. * @@ -655,7 +776,6 @@ public int getLineStartOffset(int line) { } } - /** * Returns the end offset of the specified line. * @@ -673,7 +793,6 @@ public int getLineEndOffset(int line) { } } - /** * Returns the length of the specified line. * @@ -691,7 +810,6 @@ public int getLineLength(int line) { } } - /** * Returns the entire text of this text area. * @@ -705,94 +823,20 @@ public String getText() { } } - - /** - * Sets the input handler. - * - * @param inputHandler The new input handler - */ - public void setInputHandler(InputHandler inputHandler) { - if (this.inputHandler != null) { - removeKeyListener(this.inputHandler); - } - - if (inputHandler != null) { - addKeyListener(inputHandler); - } - - this.inputHandler = inputHandler; - } - - - /** - * Toggles caret blinking. - * - * @param caretBlinks True if the caret should blink, false otherwise - */ - public void setCaretBlinkEnabled(boolean caretBlinks) { - this.caretBlinks = caretBlinks; - if (!caretBlinks) { - blink = false; - } - - painter.invalidateSelectedLines(); - } - - - /** - * Sets if the caret should be visible. - * - * @param caretVisible True if the caret should be visible, false - * otherwise - */ - public void setCaretVisible(boolean caretVisible) { - this.caretVisible = caretVisible; - blink = true; - - painter.invalidateSelectedLines(); - } - - - /** - * Sets the line displayed at the text area's origin without updating the - * scroll bars. - * - * @param firstLine The new FirstLine value - */ - public void setFirstLine(int firstLine) { - if (firstLine == this.firstLine) { - return; - } - int oldFirstLine = this.firstLine; - this.firstLine = firstLine; - if (firstLine != vertical.getValue()) { - updateScrollBars(); - } - painter.scrollRepaint(oldFirstLine, firstLine); - painter.repaint(); - } - - /** - * Sets the horizontal offset of drawn lines. This can be used to implement - * horizontal scrolling. + * Sets the entire text of this text area. * - * @param horizontalOffset offset The new horizontal offset + * @param text The new Text value */ - public void setHorizontalOffset(int horizontalOffset) { - if (horizontalOffset == this.horizontalOffset) { - return; - } - this.horizontalOffset = horizontalOffset; - if (horizontalOffset != horizontal.getValue()) { - updateScrollBars(); + public void setText(String text) { + try { + document.remove(0, document.getLength()); + document.insertString(0, text, null); + } catch (BadLocationException bl) { + bl.printStackTrace(); } - - painter.invalidateLineRange(firstLine, firstLine + visibleLines); - painter.repaint(); } - /** * A fast way of changing both the first line and horizontal offset. * @@ -831,76 +875,10 @@ public boolean setOrigin(int firstLine, int horizontalOffset) { return changed; } - - /** - * Sets the document this text area is editing. - * - * @param document The document - */ - public void setDocument(ACLSyntaxDocument document) { - if (this.document == document) { - return; - } - if (this.document != null) { - this.document.removeDocumentListener(documentHandler); - } - - this.document = document; - - document.addDocumentListener(documentHandler); - - select(0, 0); - updateScrollBars(); - painter.invalidateOffscreen(); - painter.repaint(); - } - - - /** - * Sets the entire text of this text area. - * - * @param text The new Text value - */ - public void setText(String text) { - try { - document.remove(0, document.getLength()); - document.insertString(0, text, null); - } catch (BadLocationException bl) { - bl.printStackTrace(); - } - } - - - /** - * Replaces the selection with the specified text. - * - * @param selectedText The replacement text for the selection - */ - public void setSelectedText(String selectedText) { - if (!editable) { - throw new InternalError("Text component" - + " read only"); - } - - try { - document.remove(selectionStart, - selectionEnd - selectionStart); - document.insertString(selectionStart, - selectedText, null); - setCaretPosition(selectionEnd); - } catch (BadLocationException bl) { - bl.printStackTrace(); - throw new InternalError("Cannot replace" - + " selection"); - } - } - - public void update() { this.register(msg, "Content"); } - /** * Description of the Method * @@ -937,7 +915,6 @@ public void register(Object arg, String fieldName) { this.setCaretPosition(0); } - /** * Description of the Method * @@ -948,7 +925,6 @@ public void unregister(Object arg, String str) { // msg.deleteObserver(this); } - /** * Description of the Method * @@ -970,7 +946,6 @@ public void focusLost(FocusEvent e) { } } - /** * Updates the state of the scroll bars. This should be called if the * number of lines in the document changes, or when the size of the text @@ -992,7 +967,6 @@ public void updateScrollBars() { } } - /** * Ensures that the caret is visible by scrolling the text area if * necessary. @@ -1009,7 +983,6 @@ public boolean scrollToCaret() { return scrollTo(line, offset); } - /** * Ensures that the specified line and offset is visible by scrolling the * text area if necessary. @@ -1059,7 +1032,6 @@ public boolean scrollTo(int line, int offset) { return setOrigin(newFirstLine, newHorizontalOffset); } - /** * Converts a line index to a y co-ordinate. * @@ -1072,7 +1044,6 @@ public int lineToY(int line) { - (fm.getLeading() + fm.getMaxDescent()); } - /** * Converts a y co-ordinate to a line index. * @@ -1086,7 +1057,6 @@ public int yToLine(int y) { y / height + firstLine)); } - /** * Converts an offset in a line into an x co-ordinate. * @@ -1162,7 +1132,6 @@ public int offsetToX(int line, int offset) { } } - /** * Converts an x co-ordinate to an offset within a line. * @@ -1265,7 +1234,6 @@ public int xToOffset(int line, int x) { } } - /** * Converts a point to an offset, from the start of the text. * @@ -1279,7 +1247,6 @@ public int xyToOffset(int x, int y) { return start + xToOffset(line, x); } - /** * Selects from the start offset to the end offset. This is the general * selection method used by all other selecting methods. The caret position @@ -1354,7 +1321,6 @@ public void select(int start, int end) { } - /** * Similar to setSelectedText(), but overstrikes the * appropriate number of characters if overwrite mode is enabled. @@ -1387,7 +1353,6 @@ public void overwriteSetSelectedText(String str) { } } - /** * Deletes the selected text from the text area and places it into the * clipboard. @@ -1399,7 +1364,6 @@ public void cut() { } } - /** * Places the selected text into the clipboard. */ @@ -1412,7 +1376,6 @@ public void copy() { } } - /** * Inserts the clipboard contents into the text. */ @@ -1434,7 +1397,6 @@ public void paste() { } } - /** * Called by the AWT when this component is removed from it's parent. This * stops any autoscrolling and clears the currently focused component. @@ -1451,7 +1413,6 @@ public void removeNotify() { } - /** * Description of the Method * @@ -1465,7 +1426,6 @@ protected void processFocusEvent(FocusEvent e) { } - protected void fireCaretEvent() { Object[] listeners = listenerList.getListenerList(); for (int i = listeners.length - 2; i >= 0; i--) { @@ -1476,7 +1436,6 @@ protected void fireCaretEvent() { } - protected void updateBracketHighlight(int newCaretPosition) { if (newCaretPosition == 0) { bracketPosition = bracketLine = -1; @@ -1498,7 +1457,6 @@ protected void updateBracketHighlight(int newCaretPosition) { bracketLine = bracketPosition = -1; } - protected void documentChanged(DocumentEvent evt) { DocumentEvent.ElementChange ch = evt.getChange( document.getDefaultRootElement()); @@ -1522,7 +1480,6 @@ protected void documentChanged(DocumentEvent evt) { } } - public static class TextUtilities { /** * Returns the offset of the bracket matching the one at the specified @@ -1651,7 +1608,6 @@ else if (x == cprime) { } } - static class CaretBlinker implements ActionListener { public void actionPerformed(ActionEvent evt) { if (focusedComponent != null @@ -1662,9 +1618,50 @@ public void actionPerformed(ActionEvent evt) { } } - private static class InputHandler implements KeyListener { + public final static ActionListener BACKSPACE = new backspace(); + public final static ActionListener DELETE = new delete(); + public final static ActionListener END = new end(false); + public final static ActionListener SELECT_END = new end(true); + public final static ActionListener INSERT_BREAK = new insert_break(); + public final static ActionListener INSERT_TAB = new insert_tab(); + public final static ActionListener HOME = new home(false); + public final static ActionListener SELECT_HOME = new home(true); + public final static ActionListener NEXT_CHAR = new next_char(false); + public final static ActionListener NEXT_LINE = new next_line(false); + public final static ActionListener NEXT_PAGE = new next_page(false); + public final static ActionListener NEXT_WORD = new next_word(false); + public final static ActionListener SELECT_NEXT_CHAR = new next_char(true); + public final static ActionListener SELECT_NEXT_LINE = new next_line(true); + public final static ActionListener SELECT_NEXT_PAGE = new next_page(true); + public final static ActionListener SELECT_NEXT_WORD = new next_word(true); + public final static ActionListener OVERWRITE = new overwrite(); + public final static ActionListener PREV_CHAR = new prev_char(false); + public final static ActionListener PREV_LINE = new prev_line(false); + public final static ActionListener PREV_PAGE = new prev_page(false); + public final static ActionListener PREV_WORD = new prev_word(false); + public final static ActionListener SELECT_PREV_CHAR = new prev_char(true); + public final static ActionListener SELECT_PREV_LINE = new prev_line(true); + public final static ActionListener SELECT_PREV_PAGE = new prev_page(true); + public final static ActionListener SELECT_PREV_WORD = new prev_word(true); + public final static ActionListener[] ACTIONS = { + BACKSPACE, DELETE, END, SELECT_END, INSERT_BREAK, + INSERT_TAB, HOME, SELECT_HOME, NEXT_CHAR, NEXT_LINE, + NEXT_PAGE, NEXT_WORD, SELECT_NEXT_CHAR, SELECT_NEXT_LINE, + SELECT_NEXT_PAGE, SELECT_NEXT_WORD, OVERWRITE, PREV_CHAR, + PREV_LINE, PREV_PAGE, PREV_WORD, SELECT_PREV_CHAR, + SELECT_PREV_LINE, SELECT_PREV_PAGE, SELECT_PREV_WORD}; + public final static String[] ACTION_NAMES = { + "backspace", "delete", "end", "select-end", "insert-break", + "insert-tab", "home", "select-home", "next-char", "next-line", + "next-page", "next-word", "select-next-char", "select-next-line", + "select-next-page", "select-next-word", "overwrite", "prev-char", + "prev-line", "prev-page", "prev-word", "select-prev-char", + "select-prev-line", "select-prev-page", "select-prev-word"}; + // private members + private final Hashtable bindings; + private Hashtable currentBindings; /** * Creates a new input handler with no key bindings defined. */ @@ -1672,7 +1669,6 @@ public InputHandler() { bindings = currentBindings = new Hashtable<>(); } - public static ACLTextArea getTextArea(EventObject evt) { if (evt != null) { @@ -1702,7 +1698,6 @@ public static ACLTextArea getTextArea(EventObject evt) { return null; } - /** * Converts a string to a keystroke. The string should be of the form * modifiers +shortcut where modifiers is any @@ -1752,7 +1747,6 @@ public static KeyStroke parseKeyStroke(String keyStroke) { return KeyStroke.getKeyStroke(ch, modifiers); } - /** * Sets up the default key bindings. */ @@ -1789,7 +1783,6 @@ public void addDefaultKeyBindings() { addKeyBinding("S+DOWN", SELECT_NEXT_LINE); } - /** * Adds a key binding to this input handler. The key binding is a list of * white space separated key strokes of the form [modifiers+]key @@ -1824,7 +1817,6 @@ public void addKeyBinding(String keyBinding, ActionListener action) { } } - /** * Removes a key binding from this input handler. This is not yet * implemented. @@ -1835,7 +1827,6 @@ public void removeKeyBinding(String keyBinding) { throw new InternalError("Not yet implemented"); } - /** * Removes all key bindings from this input handler. */ @@ -1843,7 +1834,6 @@ public void removeAllKeyBindings() { bindings.clear(); } - /** * Handle a key pressed event. This will look up the binding for the key * stroke and execute it. @@ -1896,7 +1886,6 @@ public void keyPressed(KeyEvent evt) { } } - /** * Handle a key released event. These are ignored. * @@ -1905,7 +1894,6 @@ public void keyPressed(KeyEvent evt) { public void keyReleased(KeyEvent evt) { } - /** * Handle a key typed event. This inserts the key into the text area. * @@ -1932,7 +1920,6 @@ public void keyTyped(KeyEvent evt) { } - public static class backspace implements ActionListener { public void actionPerformed(ActionEvent evt) { ACLTextArea textArea = getTextArea(evt); @@ -1960,7 +1947,6 @@ public void actionPerformed(ActionEvent evt) { } } - public static class delete implements ActionListener { public void actionPerformed(ActionEvent evt) { ACLTextArea textArea = getTextArea(evt); @@ -1988,13 +1974,7 @@ public void actionPerformed(ActionEvent evt) { } } - - public static class end implements ActionListener { - - public end(boolean select) { - this.select = select; - } - + public record end(boolean select) implements ActionListener { public void actionPerformed(ActionEvent evt) { @@ -2034,19 +2014,17 @@ public void actionPerformed(ActionEvent evt) { } } + } + public static class home implements ActionListener { private final boolean select; - } - public static class home implements ActionListener { - public home(boolean select) { this.select = select; } - public void actionPerformed(ActionEvent evt) { ACLTextArea textArea = getTextArea(evt); @@ -2079,12 +2057,8 @@ public void actionPerformed(ActionEvent evt) { } } - - - private final boolean select; } - public static class insert_break implements ActionListener { public void actionPerformed(ActionEvent evt) { ACLTextArea textArea = getTextArea(evt); @@ -2098,7 +2072,6 @@ public void actionPerformed(ActionEvent evt) { } } - public static class insert_tab implements ActionListener { public void actionPerformed(ActionEvent evt) { ACLTextArea textArea = getTextArea(evt); @@ -2112,14 +2085,15 @@ public void actionPerformed(ActionEvent evt) { } } - public static class next_char implements ActionListener { + private final boolean select; + + public next_char(boolean select) { this.select = select; } - public void actionPerformed(ActionEvent evt) { ACLTextArea textArea = getTextArea(evt); int caret = textArea.getCaretPosition(); @@ -2136,19 +2110,17 @@ public void actionPerformed(ActionEvent evt) { } } + } + public static class next_line implements ActionListener { private final boolean select; - } - public static class next_line implements ActionListener { - public next_line(boolean select) { this.select = select; } - public void actionPerformed(ActionEvent evt) { ACLTextArea textArea = getTextArea(evt); int caret = textArea.getCaretPosition(); @@ -2175,19 +2147,17 @@ public void actionPerformed(ActionEvent evt) { textArea.setMagicCaretPosition(magic); } + } + public static class next_page implements ActionListener { private final boolean select; - } - public static class next_page implements ActionListener { - public next_page(boolean select) { this.select = select; } - public void actionPerformed(ActionEvent evt) { ACLTextArea textArea = getTextArea(evt); int lineCount = textArea.getLineCount(); @@ -2213,19 +2183,17 @@ public void actionPerformed(ActionEvent evt) { } } + } + public static class next_word implements ActionListener { private final boolean select; - } - public static class next_word implements ActionListener { - public next_word(boolean select) { this.select = select; } - public void actionPerformed(ActionEvent evt) { ACLTextArea textArea = getTextArea(evt); int caret = textArea.getCaretPosition(); @@ -2270,12 +2238,8 @@ public void actionPerformed(ActionEvent evt) { } } - - - private final boolean select; } - public static class overwrite implements ActionListener { public void actionPerformed(ActionEvent evt) { ACLTextArea textArea = getTextArea(evt); @@ -2284,14 +2248,15 @@ public void actionPerformed(ActionEvent evt) { } } - public static class prev_char implements ActionListener { + private final boolean select; + + public prev_char(boolean select) { this.select = select; } - public void actionPerformed(ActionEvent evt) { ACLTextArea textArea = getTextArea(evt); int caret = textArea.getCaretPosition(); @@ -2308,19 +2273,17 @@ public void actionPerformed(ActionEvent evt) { } } + } + public static class prev_line implements ActionListener { private final boolean select; - } - - public static class prev_line implements ActionListener { public prev_line(boolean select) { this.select = select; } - public void actionPerformed(ActionEvent evt) { ACLTextArea textArea = getTextArea(evt); int caret = textArea.getCaretPosition(); @@ -2347,19 +2310,17 @@ public void actionPerformed(ActionEvent evt) { textArea.setMagicCaretPosition(magic); } + } + public static class prev_page implements ActionListener { private final boolean select; - } - - public static class prev_page implements ActionListener { public prev_page(boolean select) { this.select = select; } - public void actionPerformed(ActionEvent evt) { ACLTextArea textArea = getTextArea(evt); int firstLine = textArea.getFirstLine(); @@ -2381,19 +2342,17 @@ public void actionPerformed(ActionEvent evt) { } } + } + public static class prev_word implements ActionListener { private final boolean select; - } - - public static class prev_word implements ActionListener { public prev_word(boolean select) { this.select = select; } - public void actionPerformed(ActionEvent evt) { ACLTextArea textArea = getTextArea(evt); int caret = textArea.getCaretPosition(); @@ -2437,61 +2396,15 @@ public void actionPerformed(ActionEvent evt) { } } - - - private final boolean select; } - - - public final static ActionListener BACKSPACE = new backspace(); - public final static ActionListener DELETE = new delete(); - public final static ActionListener END = new end(false); - public final static ActionListener SELECT_END = new end(true); - public final static ActionListener INSERT_BREAK = new insert_break(); - public final static ActionListener INSERT_TAB = new insert_tab(); - public final static ActionListener HOME = new home(false); - public final static ActionListener SELECT_HOME = new home(true); - public final static ActionListener NEXT_CHAR = new next_char(false); - public final static ActionListener NEXT_LINE = new next_line(false); - public final static ActionListener NEXT_PAGE = new next_page(false); - public final static ActionListener NEXT_WORD = new next_word(false); - public final static ActionListener SELECT_NEXT_CHAR = new next_char(true); - public final static ActionListener SELECT_NEXT_LINE = new next_line(true); - public final static ActionListener SELECT_NEXT_PAGE = new next_page(true); - public final static ActionListener SELECT_NEXT_WORD = new next_word(true); - public final static ActionListener OVERWRITE = new overwrite(); - public final static ActionListener PREV_CHAR = new prev_char(false); - public final static ActionListener PREV_LINE = new prev_line(false); - public final static ActionListener PREV_PAGE = new prev_page(false); - public final static ActionListener PREV_WORD = new prev_word(false); - public final static ActionListener SELECT_PREV_CHAR = new prev_char(true); - public final static ActionListener SELECT_PREV_LINE = new prev_line(true); - public final static ActionListener SELECT_PREV_PAGE = new prev_page(true); - public final static ActionListener SELECT_PREV_WORD = new prev_word(true); - - public final static ActionListener[] ACTIONS = { - BACKSPACE, DELETE, END, SELECT_END, INSERT_BREAK, - INSERT_TAB, HOME, SELECT_HOME, NEXT_CHAR, NEXT_LINE, - NEXT_PAGE, NEXT_WORD, SELECT_NEXT_CHAR, SELECT_NEXT_LINE, - SELECT_NEXT_PAGE, SELECT_NEXT_WORD, OVERWRITE, PREV_CHAR, - PREV_LINE, PREV_PAGE, PREV_WORD, SELECT_PREV_CHAR, - SELECT_PREV_LINE, SELECT_PREV_PAGE, SELECT_PREV_WORD}; - - public final static String[] ACTION_NAMES = { - "backspace", "delete", "end", "select-end", "insert-break", - "insert-tab", "home", "select-home", "next-char", "next-line", - "next-page", "next-word", "select-next-char", "select-next-line", - "select-next-page", "select-next-word", "overwrite", "prev-char", - "prev-line", "prev-page", "prev-word", "select-prev-char", - "select-prev-line", "select-prev-page", "select-prev-word"}; - - // private members - private final Hashtable bindings; - private Hashtable currentBindings; } - class ScrollLayout implements LayoutManager { + // private members + private Component center; + private Component right; + private Component bottom; + public void addLayoutComponent(String name, Component comp) { if (name.equals(CENTER)) { center = comp; @@ -2503,7 +2416,6 @@ public void addLayoutComponent(String name, Component comp) { } - public void removeLayoutComponent(Component comp) { if (center == comp) { center = null; @@ -2519,7 +2431,6 @@ public void removeLayoutComponent(Component comp) { } - public Dimension preferredLayoutSize(Container parent) { Dimension dim = new Dimension(); Insets insets = getInsets(); @@ -2538,7 +2449,6 @@ public Dimension preferredLayoutSize(Container parent) { return dim; } - public Dimension minimumLayoutSize(Container parent) { Dimension dim = new Dimension(); Insets insets = getInsets(); @@ -2556,7 +2466,6 @@ public Dimension minimumLayoutSize(Container parent) { return dim; } - public void layoutContainer(Container parent) { Dimension size = parent.getSize(); Insets insets = getInsets(); @@ -2586,21 +2495,16 @@ public void layoutContainer(Container parent) { bottomHeight); */ } - - // private members - private Component center; - private Component right; - private Component bottom; } - class AutoScroll implements ActionListener, MouseMotionListener { + private int x, y; + public void actionPerformed(ActionEvent evt) { select(getMarkPosition(), xyToOffset(x, y)); } - public void mouseDragged(MouseEvent evt) { if (popup != null && popup.isVisible()) { return; @@ -2614,15 +2518,10 @@ public void mouseDragged(MouseEvent evt) { } - public void mouseMoved(MouseEvent evt) { } - - - private int x, y; } - class MutableCaretEvent extends CaretEvent { MutableCaretEvent() { super(ACLTextArea.this); @@ -2639,7 +2538,6 @@ public int getMark() { } } - class AdjustHandler implements AdjustmentListener { public void adjustmentValueChanged(AdjustmentEvent evt) { if (!scrollBarsInitialized) { @@ -2655,7 +2553,6 @@ public void adjustmentValueChanged(AdjustmentEvent evt) { } } - class ComponentHandler extends ComponentAdapter { public void componentResized(ComponentEvent evt) { recalculateVisibleLines(); @@ -2663,7 +2560,6 @@ public void componentResized(ComponentEvent evt) { } } - class DocumentHandler implements DocumentListener { public void insertUpdate(DocumentEvent evt) { documentChanged(evt); @@ -2747,7 +2643,6 @@ public void changedUpdate(DocumentEvent evt) { } } - class FocusHandler implements FocusListener { public void focusGained(FocusEvent evt) { setCaretVisible(true); @@ -2761,7 +2656,6 @@ public void focusLost(FocusEvent evt) { } } - class MouseHandler extends MouseAdapter { public void mousePressed(MouseEvent evt) { requestFocus(); @@ -2885,62 +2779,5 @@ private void doTripleClick(MouseEvent evt, int line, } } - - // protected members - protected static String CENTER = "center"; - protected static String RIGHT = "right"; - protected static String BOTTOM = "bottom"; - - protected static ACLTextArea focusedComponent; - protected static Timer caretTimer; - - protected ACLTextAreaPainter painter; - - protected JPopupMenu popup; - - protected Timer scrollTimer; - - protected EventListenerList listenerList; - protected MutableCaretEvent caretEvent; - - protected boolean caretBlinks; - protected boolean caretVisible; - protected boolean blink; - - protected boolean editable; - - protected int firstLine; - protected int visibleLines; - protected int electricScroll; - - protected int horizontalOffset; - - protected JScrollBar vertical; - protected JScrollBar horizontal; - protected boolean scrollBarsInitialized; - - protected InputHandler inputHandler; - protected ACLSyntaxDocument document; - protected DocumentHandler documentHandler; - - protected Segment lineSegment; - - protected int selectionStart; - protected int selectionStartLine; - protected int selectionEnd; - protected int selectionEndLine; - protected boolean biasLeft; - - protected int bracketPosition; - protected int bracketLine; - - protected int magicCaret; - protected boolean overwrite; - - private String contentLanguage = ""; - - private ACLMessage msg; - private String fieldName; - } // ***EOF*** diff --git a/src/jade/tools/gui/ACLTextAreaPainter.java b/src/jade/tools/gui/ACLTextAreaPainter.java index 7770486..e320d7d 100644 --- a/src/jade/tools/gui/ACLTextAreaPainter.java +++ b/src/jade/tools/gui/ACLTextAreaPainter.java @@ -42,6 +42,33 @@ * @since June 14, 2002 */ public class ACLTextAreaPainter extends JComponent implements TabExpander { + protected static boolean copyAreaBroken; + // protected members + protected ACLTextArea textArea; + protected ACLSytntaxStyle[] styles; + protected Color caretColor; + protected Color selectionColor; + protected Color lineHighlightColor; + protected Color bracketHighlightColor; + protected Color eolMarkerColor; + protected boolean blockCaret; + protected boolean lineHighlight; + protected boolean bracketHighlight; + protected boolean eolMarkers; + protected int cols; + protected int rows; + protected int tabSize; + protected FontMetrics fm; + protected Graphics offGfx; + protected Image offImg; + protected int firstInvalid; + protected int lastInvalid; + // package-private members + int currentLineIndex; + ACLToken currentLineTokens; + Segment currentLine; + + /** * Creates a new repaint manager. This should be not be called directly. * @@ -76,7 +103,6 @@ public ACLTextAreaPainter(ACLTextArea textArea) { copyAreaBroken = true; } - /** * Returns if this component can be traversed by pressing the Tab key. This * returns false. @@ -89,7 +115,6 @@ public final boolean isManagingFocus() { return false; } - /** * Returns the syntax styles used to paint colorized text. Entry n * will be used to paint tokens with id = n . @@ -101,99 +126,6 @@ public final ACLSytntaxStyle[] getStyles() { return styles; } - - /** - * Returns the caret color. - * - * @return The CaretColor value - */ - public final Color getCaretColor() { - return caretColor; - } - - - /** - * Returns the selection color. - * - * @return The SelectionColor value - */ - public final Color getSelectionColor() { - return selectionColor; - } - - - /** - * Returns the line highlight color. - * - * @return The LineHighlightColor value - */ - public final Color getLineHighlightColor() { - return lineHighlightColor; - } - - - /** - * Returns true if line highlight is enabled, false otherwise. - * - * @return The LineHighlightEnabled value - */ - public final boolean isLineHighlightEnabled() { - return lineHighlight; - } - - - /** - * Returns the bracket highlight color. - * - * @return The BracketHighlightColor value - */ - public final Color getBracketHighlightColor() { - return bracketHighlightColor; - } - - - /** - * Returns true if bracket highlighting is enabled, false otherwise. When - * bracket highlighting is enabled, the bracket matching the one before the - * caret (if any) is highlighted. - * - * @return The BracketHighlightEnabled value - */ - public final boolean isBracketHighlightEnabled() { - return bracketHighlight; - } - - - /** - * Returns true if the caret should be drawn as a block, false otherwise. - * - * @return The BlockCaretEnabled value - */ - public final boolean isBlockCaretEnabled() { - return blockCaret; - } - - - /** - * Returns the EOL marker color. - * - * @return The EOLMarkerColor value - */ - public final Color getEOLMarkerColor() { - return eolMarkerColor; - } - - - /** - * Returns true if EOL markers are drawn, false otherwise. - * - * @return The EOLMarkerEnabled value - */ - public final boolean isEOLMarkerEnabled() { - return eolMarkers; - } - - /** * Sets the syntax styles used to paint colorized text. Entry n will * be used to paint tokens with id = n . @@ -207,6 +139,14 @@ public final void setStyles(ACLSytntaxStyle[] styles) { repaint(); } + /** + * Returns the caret color. + * + * @return The CaretColor value + */ + public final Color getCaretColor() { + return caretColor; + } /** * Sets the caret color. @@ -218,6 +158,14 @@ public final void setCaretColor(Color caretColor) { invalidateSelectedLines(); } + /** + * Returns the selection color. + * + * @return The SelectionColor value + */ + public final Color getSelectionColor() { + return selectionColor; + } /** * Sets the selection color. @@ -229,6 +177,14 @@ public final void setSelectionColor(Color selectionColor) { invalidateSelectedLines(); } + /** + * Returns the line highlight color. + * + * @return The LineHighlightColor value + */ + public final Color getLineHighlightColor() { + return lineHighlightColor; + } /** * Sets the line highlight color. @@ -240,6 +196,14 @@ public final void setLineHighlightColor(Color lineHighlightColor) { invalidateSelectedLines(); } + /** + * Returns true if line highlight is enabled, false otherwise. + * + * @return The LineHighlightEnabled value + */ + public final boolean isLineHighlightEnabled() { + return lineHighlight; + } /** * Enables or disables current line highlighting. @@ -252,6 +216,14 @@ public final void setLineHighlightEnabled(boolean lineHighlight) { invalidateSelectedLines(); } + /** + * Returns the bracket highlight color. + * + * @return The BracketHighlightColor value + */ + public final Color getBracketHighlightColor() { + return bracketHighlightColor; + } /** * Sets the bracket highlight color. @@ -263,6 +235,16 @@ public final void setBracketHighlightColor(Color bracketHighlightColor) { invalidateLine(textArea.getBracketLine()); } + /** + * Returns true if bracket highlighting is enabled, false otherwise. When + * bracket highlighting is enabled, the bracket matching the one before the + * caret (if any) is highlighted. + * + * @return The BracketHighlightEnabled value + */ + public final boolean isBracketHighlightEnabled() { + return bracketHighlight; + } /** * Enables or disables bracket highlighting. When bracket highlighting is @@ -277,6 +259,14 @@ public final void setBracketHighlightEnabled(boolean bracketHighlight) { invalidateLine(textArea.getBracketLine()); } + /** + * Returns true if the caret should be drawn as a block, false otherwise. + * + * @return The BlockCaretEnabled value + */ + public final boolean isBlockCaretEnabled() { + return blockCaret; + } /** * Sets if the caret should be drawn as a block, false otherwise. @@ -289,6 +279,14 @@ public final void setBlockCaretEnabled(boolean blockCaret) { invalidateSelectedLines(); } + /** + * Returns the EOL marker color. + * + * @return The EOLMarkerColor value + */ + public final Color getEOLMarkerColor() { + return eolMarkerColor; + } /** * Sets the EOL marker color. @@ -301,6 +299,14 @@ public final void setEOLMarkerColor(Color eolMarkerColor) { repaint(); } + /** + * Returns true if EOL markers are drawn, false otherwise. + * + * @return The EOLMarkerEnabled value + */ + public final boolean isEOLMarkerEnabled() { + return eolMarkers; + } /** * Sets if EOL markers are to be drawn. @@ -313,7 +319,6 @@ public final void setEOLMarkerEnabled(boolean eolMarkers) { repaint(); } - /** * Queues a repaint of the changed lines only. */ @@ -329,7 +334,6 @@ public final void fastRepaint() { } - /** * Repaints the specified line. This is equivalent to calling _invalidateLine() * and repaint(). @@ -342,7 +346,6 @@ public final void invalidateLine(int line) { fastRepaint(); } - /** * Repaints the specified line range. This is equivalent to calling _invalidateLineRange() * then repaint(). @@ -355,7 +358,6 @@ public final void invalidateLineRange(int firstLine, int lastLine) { fastRepaint(); } - /** * Repaints the lines containing the selection. */ @@ -364,7 +366,6 @@ public final void invalidateSelectedLines() { textArea.getSelectionEndLine()); } - /** * Invalidates the offscreen graphics context. This should not be called * directly. @@ -374,7 +375,6 @@ public final void invalidateOffscreen() { offGfx = null; } - /** * Returns the font metrics used by this component. * @@ -384,7 +384,6 @@ public FontMetrics getFontMetrics() { return fm; } - /** * Returns if the copyArea() should not be used. * @@ -394,6 +393,15 @@ public boolean isCopyAreaBroken() { return copyAreaBroken; } + /** + * Disables the use of the copyArea() function (which is broken in JDK + * 1.2). + * + * @param copyAreaBroken The new CopyAreaBroken value + */ + public void setCopyAreaBroken(boolean copyAreaBroken) { + ACLTextAreaPainter.copyAreaBroken = copyAreaBroken; + } /** * Returns the painter's preferred size. @@ -410,7 +418,6 @@ public Dimension getPreferredSize() { */ } - /** * Returns the painter's minimum size. * @@ -420,7 +427,6 @@ public Dimension getMinimumSize() { return super.getMinimumSize(); } - /** * Sets the font for this component. This is overridden to update the * cached font metrics and to recalculate which lines are visible. @@ -433,18 +439,6 @@ public void setFont(Font font) { textArea.recalculateVisibleLines(); } - - /** - * Disables the use of the copyArea() function (which is broken in JDK - * 1.2). - * - * @param copyAreaBroken The new CopyAreaBroken value - */ - public void setCopyAreaBroken(boolean copyAreaBroken) { - ACLTextAreaPainter.copyAreaBroken = copyAreaBroken; - } - - /** * Paints any lines that changed since the last paint to the offscreen * graphics, then repaints the offscreen to the specified graphics context. @@ -493,7 +487,6 @@ public void update(Graphics g) { g.drawImage(offImg, 0, 0, null); } - /** * Same as update(g). * @@ -503,7 +496,6 @@ public void paint(Graphics g) { update(g); } - /** * Marks a line as needing a repaint, but doesn't actually repaint it until * repaint() is called manually. @@ -530,7 +522,6 @@ public void _invalidateLine(int line) { } } - /** * Marks a range of lines as needing a repaint, but doesn't actually * repaint them until repaint() is called. @@ -568,7 +559,6 @@ public void _invalidateLineRange(int firstLine, int lastLine) { lastInvalid = Math.min(lastInvalid, lastVisible); } - /** * Simulates scrolling from oldFirstLine to newFirstLine * by shifting the offscreen graphics and repainting any revealed lines. @@ -604,7 +594,6 @@ public void scrollRepaint(int oldFirstLine, int newFirstLine) { } } - /** * Implementation of TabExpander interface. Returns next tab stop after a * specified point. @@ -619,7 +608,6 @@ public float nextTabStop(float x, int tabOffset) { return (ntabs + 1) * tabSize + offset; } - protected boolean ensureOffscreenValid() { if (offImg == null || offGfx == null) { offImg = textArea.createImage(getWidth(), getHeight()); @@ -630,7 +618,6 @@ protected boolean ensureOffscreenValid() { } } - protected int offscreenRepaintLineRange(int firstLine, int lastLine) { if (offGfx == null) { return 0; @@ -646,7 +633,6 @@ protected int offscreenRepaintLineRange(int firstLine, int lastLine) { return line - firstLine; } - protected int offscreenRepaintLine(int line, int x) { ACLSLTokenMarker tokenMarker = textArea.getTokenMarker(); Font defaultFont = getFont(); @@ -682,7 +668,6 @@ protected int offscreenRepaintLine(int line, int x) { } } - protected void paintPlainLine(int line, Font defaultFont, Color defaultColor, int x, int y) { paintHighlight(line, y); @@ -700,7 +685,6 @@ protected void paintPlainLine(int line, Font defaultFont, } } - protected void paintSyntaxLine(ACLSLTokenMarker tokenMarker, int line, Font defaultFont, Color defaultColor, int x, int y) { textArea.getLineText(currentLineIndex, currentLine); @@ -722,7 +706,6 @@ protected void paintSyntaxLine(ACLSLTokenMarker tokenMarker, int line, } } - protected void paintHighlight(int line, int y) { /* Clear the line's bounding rectangle @@ -746,7 +729,6 @@ protected void paintHighlight(int line, int y) { } - protected void paintLineHighlight(int line, int y) { int height = fm.getHeight(); y += fm.getLeading() + fm.getMaxDescent(); @@ -792,7 +774,6 @@ protected void paintLineHighlight(int line, int y) { } - protected void paintBracketHighlight(int line, int y) { int position = textArea.getBracketPosition(); if (position == -1) { @@ -808,7 +789,6 @@ protected void paintBracketHighlight(int line, int y) { fm.getHeight() - 1); } - protected void paintCaret(int line, int y) { if (textArea.isCaretVisible()) { int offset = textArea.getCaretPosition() @@ -831,38 +811,5 @@ protected void paintCaret(int line, int y) { } } - - - protected static boolean copyAreaBroken; - - // protected members - protected ACLTextArea textArea; - - protected ACLSytntaxStyle[] styles; - protected Color caretColor; - protected Color selectionColor; - protected Color lineHighlightColor; - protected Color bracketHighlightColor; - protected Color eolMarkerColor; - - protected boolean blockCaret; - protected boolean lineHighlight; - protected boolean bracketHighlight; - protected boolean eolMarkers; - protected int cols; - protected int rows; - - protected int tabSize; - protected FontMetrics fm; - protected Graphics offGfx; - protected Image offImg; - - protected int firstInvalid; - protected int lastInvalid; - - // package-private members - int currentLineIndex; - ACLToken currentLineTokens; - Segment currentLine; } // ***EOF*** diff --git a/src/jade/tools/gui/ACLTextField.java b/src/jade/tools/gui/ACLTextField.java index 4437fe7..5363159 100644 --- a/src/jade/tools/gui/ACLTextField.java +++ b/src/jade/tools/gui/ACLTextField.java @@ -41,12 +41,14 @@ public class ACLTextField extends JTextField implements Observer { + private Object theObj; + private String fieldName; + public void setEditable(boolean theBool) { super.setEditable(true); super.setEnabled(theBool); } - /** * register an ACLMessage with the accompagnied membername * @@ -79,7 +81,6 @@ public void register(Object arg, String fieldName) { } - /** * unregister ACLMessage * @@ -90,7 +91,6 @@ public void unregister(Object arg, String str) { } - /** * update textField * @@ -112,7 +112,6 @@ public void update(Observable ob, Object arg) { } - /** * triggered when focus lossed * @@ -130,7 +129,6 @@ public void focusLost(FocusEvent e) { } } - /** * processFocusEvent listener * @@ -143,9 +141,5 @@ protected void processFocusEvent(FocusEvent e) { } } - - - private Object theObj; - private String fieldName; } // ***EOF*** diff --git a/src/jade/tools/gui/ACLTimeChooserDialog.java b/src/jade/tools/gui/ACLTimeChooserDialog.java index c57e906..e6f7b44 100644 --- a/src/jade/tools/gui/ACLTimeChooserDialog.java +++ b/src/jade/tools/gui/ACLTimeChooserDialog.java @@ -48,6 +48,30 @@ public class ACLTimeChooserDialog implements ActionListener { + /** + * Description of the Field + */ + public final static int ABSOLUTE = 0; + /** + * Description of the Field + */ + public final static int RELATIVE = 1; + /** + * Description of the Field + */ + public final static int OK = 1; + /** + * Description of the Field + */ + public final static int CANCEL = 0; + JToggleButton absButton; + JToggleButton relButton; + private Date date; + private int mode; + private int retVal; + private JDialog dlg; + private JTextField year, month, day, hour, min, sec; + /** * Constructor for the TimeChooserDialog object */ @@ -55,8 +79,6 @@ public ACLTimeChooserDialog() { retVal = CANCEL; date = null; } - - /** * Constructor for the TimeChooserDialog object * @@ -67,7 +89,6 @@ public ACLTimeChooserDialog(Date d) { date = d; } - /** * @param args The command line arguments */ @@ -77,7 +98,6 @@ public static void main(String[] args) { tc.showViewTimeDlg(null); } - /** * Gets the Date attribute of the TimeChooserDialog object * @@ -87,7 +107,6 @@ public Date getDate() { return (date); } - /** * Sets the Date attribute of the TimeChooserDialog object * @@ -97,7 +116,6 @@ public void setDate(Date d) { date = d; } - /** * Description of the Method * @@ -200,7 +218,6 @@ THIS PART IS RELATED TO THE EDITING OF RELATIVE TIMES (NOT YET IMPLEMENTED) return (retVal); } - /** * Description of the Method * @@ -257,7 +274,6 @@ public void showViewTimeDlg(JFrame parent) { dlg.setVisible(true); } - /** * Description of the Method * @@ -302,7 +318,6 @@ public void actionPerformed(ActionEvent e) { } - /** * Adds a feature to the TimeUnitLine attribute of the TimeChooserDialog * object @@ -368,31 +383,5 @@ private void addTimeUnitLine(JPanel tp, int timeUnit, final JTextField timeUnitE tp.add(up); } - - /** - * Description of the Field - */ - public final static int ABSOLUTE = 0; - /** - * Description of the Field - */ - public final static int RELATIVE = 1; - - /** - * Description of the Field - */ - public final static int OK = 1; - /** - * Description of the Field - */ - public final static int CANCEL = 0; - JToggleButton absButton; - JToggleButton relButton; - private Date date; - private int mode; - private int retVal; - private JDialog dlg; - private JTextField year, month, day, hour, min, sec; - } // ***EOF*** diff --git a/src/jade/tools/gui/ACLToken.java b/src/jade/tools/gui/ACLToken.java index 07c02b0..e47d48a 100644 --- a/src/jade/tools/gui/ACLToken.java +++ b/src/jade/tools/gui/ACLToken.java @@ -38,125 +38,106 @@ */ public class ACLToken { - /** - * Creates a new token. - * - * @param length The length of the token - * @param id The id of the token - */ - public ACLToken(int length, byte id) { - this.length = length; - this.id = id; - } - - - /** - * Returns a string representation of this token. - * - * @return Description of the Returned Value - */ - public String toString() { - return "[id=" + id + ",length=" + length + "]"; - } - - /** * Normal text token id. This should be used to mark normal text. */ public final static byte NULL = 0; - /** * Comment 1 token id. This can be used to mark a comment. */ public final static byte COMMENT1 = 1; - /** * Comment 2 token id. This can be used to mark a comment. */ public final static byte COMMENT2 = 2; - /** * Literal 1 token id. This can be used to mark a string literal (eg, C * mode uses this to mark "..." literals) */ public final static byte LITERAL1 = 3; - /** * Literal 2 token id. This can be used to mark an object literal (eg, Java * mode uses this to mark true, false, etc) */ public final static byte LITERAL2 = 4; - /** * Label token id. This can be used to mark labels (eg, C mode uses this to * mark ...: sequences) */ public final static byte LABEL = 5; - /** * Keyword 1 token id. This can be used to mark a keyword. This should be * used for general language constructs. */ public final static byte KEYWORD1 = 6; - /** * Keyword 2 token id. This can be used to mark a keyword. This should be * used for preprocessor commands, or variables. */ public final static byte KEYWORD2 = 7; - /** * Keyword 3 token id. This can be used to mark a keyword. This should be * used for data types. */ public final static byte KEYWORD3 = 8; - /** * Operator token id. This can be used to mark an operator. (eg, SQL mode * marks +, -, etc with this token type) */ public final static byte OPERATOR = 9; - /** * Invalid token id. This can be used to mark invalid or incomplete tokens, * so the user can easily spot syntax errors. */ public final static byte INVALID = 10; - /** * The total number of defined token ids. */ public final static byte ID_COUNT = 11; - /** * The first id that can be used for internal state in a token marker. */ public final static byte INTERNAL_FIRST = 100; - /** * The last id that can be used for internal state in a token marker. */ public final static byte INTERNAL_LAST = 126; - /** * The token type, that along with a length of 0 marks the end of the token * list. */ public final static byte END = 127; - /** * The length of this token. */ public int length; - /** * The id of this token. */ public byte id; - /** * The next token in the linked list. */ public ACLToken next; + + /** + * Creates a new token. + * + * @param length The length of the token + * @param id The id of the token + */ + public ACLToken(int length, byte id) { + this.length = length; + this.id = id; + } + + /** + * Returns a string representation of this token. + * + * @return Description of the Returned Value + */ + public String toString() { + return "[id=" + id + ",length=" + length + "]"; + } } // ***EOF*** diff --git a/src/jade/tools/gui/ACLTracePanel.java b/src/jade/tools/gui/ACLTracePanel.java index 00e0479..3147516 100644 --- a/src/jade/tools/gui/ACLTracePanel.java +++ b/src/jade/tools/gui/ACLTracePanel.java @@ -58,7 +58,52 @@ public class ACLTracePanel extends JPanel { //logging + public final static String DIRECTION_IN = "in"; + public final static String DIRECTION_OUT = "out"; + private static final DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM); private final Logger logger = Logger.getMyLogger(this.getClass().getName()); + private final JMenuItem deleteMenuItem = new JMenuItem(); + private final DefaultMutableTreeNode aclRoot = new DefaultMutableTreeNode("messagetrace"); + private final DefaultTreeModel aclModel = new DefaultTreeModel(aclRoot); + private final GridBagLayout gridBagLayout1 = new GridBagLayout(); + private final GridBagLayout gridBagLayout2 = new GridBagLayout(); + private final JScrollPane aclTreeScrollPane = new JScrollPane(); + private final JTree aclTree = new JTree(); + private final ACLTreeRenderer aclTreeRenderer = new ACLTreeRenderer(); + private final JPopupMenu thePopupMenu = new JPopupMenu(); + private final JMenuItem systemMenuItem = new JMenuItem(); + private final JMenuItem zoomMenuItem = new JMenuItem(); + private final int currentSelection = 0; + private final JMenuItem saveMenuItem = new JMenuItem(); + private final JMenuItem stasticsMenuItem = new JMenuItem(); + private final JMenuItem aboutMenuItem = new JMenuItem(); + private final ImageIcon sortIcon = + new ImageIcon(this.getClass().getResource("images/sort.gif")); + private final DefaultComboBoxModel sortComboBoxModel = new DefaultComboBoxModel<>(); + private final Agent agent; + JLabel jLabel1 = new JLabel(); + ButtonGroup sortingButtonGroup = new ButtonGroup(); + JComboBox sortComboBox = new JComboBox<>(); + JRadioButton ascRadioButton = new JRadioButton(); + JRadioButton descRadioButton = new JRadioButton(); + JButton sortButton = new JButton(); + JMenuItem saveQMenuItem = new JMenuItem(); + JMenuItem openQMenuItem = new JMenuItem(); + JMenuItem clearQMenuItem = new JMenuItem(); + Border border2; + Border border3; + private boolean sorting = false; + private int inMsgCount = 0, outMsgCount = 0; + private int aclIndex; + private File currentDir; + private int x, y; + + +// ***EOF*** + private ACLMessage currentACL; + private Border border1; + private TitledBorder titledBorder1; + /** * Constructor for the ACLTreePanel object @@ -84,12 +129,10 @@ public ACLTracePanel(Agent agent) { } } - public ACLMessage getCurrentACL() { return currentACL; } - public void doSystemOut() { if (currentACL == null) { return; @@ -98,7 +141,6 @@ public void doSystemOut() { logger.log(Logger.CONFIG, "\n" + currentACL.toString() + "\n"); } - /** * Adds a ACLMessageNode to the List * @@ -108,7 +150,6 @@ public void addMessageNode(ACLMessageNode theNode) { addMessageNode(theNode.getDirection(), theNode.getTime(), theNode.getMessage()); } - /** * Adds a ACLMessage to the List * @@ -119,8 +160,11 @@ public void addMessageNode(String direction, ACLMessage theACL) { String theTime = getTimeStamp(); addMessageNode(direction, theTime, theACL); } +// ***EOF*** +// ***EOF*** + /** * Adds a ACLMessage to the List * @@ -259,7 +303,7 @@ public void addMessageNode(String direction, String theTime, ACLMessage theACL) } aclTree.expandPath(new TreePath(aclRoot.getPath())); } - +// ***EOF*** /** * delete the current selected ACLMessage from the list @@ -277,7 +321,6 @@ public void deleteCurrent() { } } - /** * show about screen */ @@ -285,7 +328,6 @@ public void doShowAbout() { new AboutFrame().setVisible(true); } - /** * save the current selected ACLMessage to a textfile */ @@ -324,17 +366,19 @@ public void saveACL() { } } - +// ***EOF*** public void doShowCurrentACL() { showCurrentACL(x, y); } +// ***EOF*** public void showStastistics() { ACLStatisticsFrame.show(this.aclModel); } +// ***EOF*** public void saveQueue() { @@ -390,7 +434,6 @@ public void saveQueue() { } } - public void loadQueue() { UIManager.put("FileChooser.openButtonToolTipText", "Open ACLMessage Trace"); @@ -448,7 +491,6 @@ public void loadQueue() { } } - public void clearACLModel() { int size = aclModel.getChildCount(this.aclRoot); @@ -462,7 +504,6 @@ public void clearACLModel() { aclTree.repaint(); } - public void doSort() { int direction = this.sortComboBox.getSelectedIndex(); @@ -493,7 +534,6 @@ public void doSort() { } - /** * Gets the TimeStamp attribute of the ACLTreePanel object * @@ -504,7 +544,6 @@ String getTimeStamp() { return dateFormat.format(new Date()); } - /** * refresh the List */ @@ -513,7 +552,6 @@ void refresh() { aclTree.updateUI(); } - /** * triggered when mousePressed * @@ -550,7 +588,6 @@ void aclTree_mouseClicked(MouseEvent e) { } } - /** * triggered when systemMenuItem * @@ -562,7 +599,6 @@ void systemMenuItem_actionPerformed(ActionEvent e) { } } - /** * showCurrentACL * @@ -572,7 +608,6 @@ void zoomMenuItem_actionPerformed(ActionEvent e) { doShowCurrentACL(); } - /** * saveACL * @@ -582,7 +617,6 @@ void saveMenuItem_actionPerformed(ActionEvent e) { saveACL(); } - /** * show ACLStatisticsFrame * @@ -592,7 +626,6 @@ void stasticsMenuItem_actionPerformed(ActionEvent e) { showStastistics(); } - /** * listener for keyTyped * @@ -605,7 +638,6 @@ void aclTree_keyTyped(KeyEvent e) { } - /** * deleteMenuItem * @@ -615,52 +647,42 @@ void deleteMenuItem_actionPerformed(ActionEvent e) { this.deleteCurrent(); } - void sortButton_actionPerformed(ActionEvent e) { this.doSort(); } - void sortComboBox_itemStateChanged(ItemEvent e) { doSort(); } - void ascRadioButton_itemStateChanged(ItemEvent e) { doSort(); } - void descRadioButton_itemStateChanged(ItemEvent e) { doSort(); } - void aboutMenuItem_mouseClicked(MouseEvent e) { this.doShowAbout(); } - void saveQMenuItem_actionPerformed(ActionEvent e) { this.saveQueue(); } - void clearQMenuItem_actionPerformed(ActionEvent e) { this.clearACLModel(); } - void openQMenuItem_actionPerformed(ActionEvent e) { this.loadQueue(); } - void aboutMenuItem_actionPerformed(ActionEvent e) { this.doShowAbout(); } - private void fillSortComboBoxModel() { sortComboBoxModel.addElement("date"); sortComboBoxModel.addElement("direction"); @@ -670,7 +692,6 @@ private void fillSortComboBoxModel() { sortComboBoxModel.addElement("ontology"); } - /** * show the Current ACLMessage * @@ -684,7 +705,6 @@ private void showCurrentACL(int x, int y) { ACLFrame.show(currentACL, agent); } - /** * build up TreePanel * @@ -809,15 +829,23 @@ private void jbInit() throws Exception { sortingButtonGroup.add(descRadioButton); } - private class ACLMessageNodeComparator implements Comparator { + final static int DATE = 0; + final static int DIRECTION = 1; + final static int SENDER = 2; + final static int RECEIVER = 3; + final static int PERFORMATIVE = 4; + final static int ONTOLOGY = 5; + final static int SORT_ASCENDING = 1; + final static int SORT_DESCENDING = -1; + private final int sorting; + private final int mode; public ACLMessageNodeComparator(int mode, int sorting) { this.mode = mode; this.sorting = sorting; } - public int compare(Object o1, Object o2) { ACLMessageNode node1 = (ACLMessageNode) o1; ACLMessageNode node2 = (ACLMessageNode) o2; @@ -856,96 +884,69 @@ public int compare(Object o1, Object o2) { return sorting * comp1.compareTo(comp2); } - public boolean equals(Object obj) { throw new UnsupportedOperationException("Method equals() not yet implemented."); } - - final static int DATE = 0; - final static int DIRECTION = 1; - final static int SENDER = 2; - final static int RECEIVER = 3; - final static int PERFORMATIVE = 4; - final static int ONTOLOGY = 5; - - final static int SORT_ASCENDING = 1; - final static int SORT_DESCENDING = -1; - - private final int sorting; - private final int mode; - } + private class ACLTracePanel_sortComboBox_itemAdapter implements ItemListener { -// ***EOF*** + ACLTracePanel adaptee; - private class ACLTracePanel_sortComboBox_itemAdapter implements ItemListener { - ACLTracePanel_sortComboBox_itemAdapter(ACLTracePanel adaptee) { this.adaptee = adaptee; } - public void itemStateChanged(ItemEvent e) { adaptee.sortComboBox_itemStateChanged(e); } + } + private class ACLTracePanel_ascRadioButton_itemAdapter implements ItemListener { ACLTracePanel adaptee; - } - private class ACLTracePanel_ascRadioButton_itemAdapter implements ItemListener { - ACLTracePanel_ascRadioButton_itemAdapter(ACLTracePanel adaptee) { this.adaptee = adaptee; } - public void itemStateChanged(ItemEvent e) { adaptee.ascRadioButton_itemStateChanged(e); } + } + private class ACLTracePanel_descRadioButton_itemAdapter implements ItemListener { ACLTracePanel adaptee; - } - private class ACLTracePanel_descRadioButton_itemAdapter implements ItemListener { - ACLTracePanel_descRadioButton_itemAdapter(ACLTracePanel adaptee) { this.adaptee = adaptee; } - public void itemStateChanged(ItemEvent e) { adaptee.descRadioButton_itemStateChanged(e); } + } + private class ACLTracePanel_sortButton_actionAdapter implements ActionListener { ACLTracePanel adaptee; - } - - private class ACLTracePanel_sortButton_actionAdapter implements ActionListener { ACLTracePanel_sortButton_actionAdapter(ACLTracePanel adaptee) { this.adaptee = adaptee; } - public void actionPerformed(ActionEvent e) { adaptee.sortButton_actionPerformed(e); } - - - ACLTracePanel adaptee; } - private class ACLFileFilter extends javax.swing.filechooser.FileFilter { public ACLFileFilter() { @@ -971,13 +972,14 @@ public boolean accept(File pathName) { } } - private class TraceFileFilter extends javax.swing.filechooser.FileFilter { + private final String[] extensions = {".trc"}; + + public TraceFileFilter() { } - /** * The description of this filter. For example: "JPG and GIF Images" * @@ -988,21 +990,26 @@ public String getDescription() { return "ACLMessageTrace files (*.trc)"; } - public boolean accept(File pathName) { if (pathName.isDirectory()) { return true; } else return pathName.isFile() && (pathName.getName().endsWith(".trc")); } - - - private final String[] extensions = {".trc"}; } - private class AboutFrame extends JWindow { + GridBagLayout gridBagLayout1 = new GridBagLayout(); + JPanel contentPanel = new JPanel(); + GridBagLayout gridBagLayout2 = new GridBagLayout(); + JLabel jLabel1 = new JLabel(); + JLabel jLabel2 = new JLabel(); + JLabel logoLabel3 = new JLabel(); + JLabel jLabel4 = new JLabel(); + Border border1; + + public AboutFrame() { try { jbInit(); @@ -1016,117 +1023,94 @@ public AboutFrame() { } } - void logoLabel_mouseClicked(MouseEvent e) { this.setVisible(false); } - void logoLabel3_mousePressed(MouseEvent e) { this.setVisible(false); } - void jLabel2_mouseClicked(MouseEvent e) { this.setVisible(false); } - void logoLabel3_mouseClicked(MouseEvent e) { this.setVisible(false); } - void logoLabel_mouseEntered(MouseEvent e) { this.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); } - void logoLabel_mouseExited(MouseEvent e) { this.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } - void logoLabel3_mouseEntered(MouseEvent e) { this.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); } - void logoLabel3_mouseExited(MouseEvent e) { this.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } - void jLabel2_mouseEntered(MouseEvent e) { this.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); } - void jLabel2_mouseExited(MouseEvent e) { this.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } - void logoLabel_mousePressed(MouseEvent e) { this.setVisible(false); } - void logoLabel_mouseReleased(MouseEvent e) { this.setVisible(false); } - void jLabel2_mousePressed(MouseEvent e) { this.setVisible(false); } - void jLabel2_mouseReleased(MouseEvent e) { this.setVisible(false); } - void jLabel4_mouseClicked(MouseEvent e) { this.setVisible(false); } - void contentPanel_mouseClicked(MouseEvent e) { this.setVisible(false); } - void jLabel1_mouseClicked(MouseEvent e) { this.setVisible(false); } - void jLabel4_mouseEntered(MouseEvent e) { this.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); } - void jLabel1_mouseEntered(MouseEvent e) { this.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); } - void contentPanel_mouseEntered(MouseEvent e) { this.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); } - void jLabel4_mouseExited(MouseEvent e) { this.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } - void contentPanel_mouseExited(MouseEvent e) { this.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } - private void jbInit() throws Exception { // this.setClosable(true); //this.setOpaque(false); @@ -1233,22 +1217,13 @@ public void mouseExited(MouseEvent e) { , GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 20, 0), 0, 0)); } - - GridBagLayout gridBagLayout1 = new GridBagLayout(); - - JPanel contentPanel = new JPanel(); - GridBagLayout gridBagLayout2 = new GridBagLayout(); - JLabel jLabel1 = new JLabel(); - JLabel jLabel2 = new JLabel(); - JLabel logoLabel3 = new JLabel(); - JLabel jLabel4 = new JLabel(); - Border border1; - } - private class ACLTreePanel_stasticsMenuItem_actionAdapter implements ActionListener { + ACLTracePanel adaptee; + + /** * Constructor for the ACLTreePanel_stasticsMenuItem_actionAdapter object * @@ -1258,7 +1233,6 @@ private class ACLTreePanel_stasticsMenuItem_actionAdapter implements ActionListe this.adaptee = adaptee; } - /** * Description of the Method * @@ -1267,16 +1241,12 @@ private class ACLTreePanel_stasticsMenuItem_actionAdapter implements ActionListe public void actionPerformed(ActionEvent e) { adaptee.stasticsMenuItem_actionPerformed(e); } - - - ACLTracePanel adaptee; } -// ***EOF*** + private class ACLTreePanel_this_mouseAdapter extends MouseAdapter { -// ***EOF*** + ACLTracePanel adaptee; - private class ACLTreePanel_this_mouseAdapter extends MouseAdapter { /** * Constructor for the ACLTreePanel_this_mouseAdapter object @@ -1287,7 +1257,6 @@ private class ACLTreePanel_this_mouseAdapter extends MouseAdapter { this.adaptee = adaptee; } - /** * Description of the Method * @@ -1297,14 +1266,13 @@ public void mouseClicked(MouseEvent e) { } - - ACLTracePanel adaptee; - } -// ***EOF*** private class ACLTreePanel_aclTree_mouseAdapter extends MouseAdapter { + ACLTracePanel adaptee; + + /** * Constructor for the ACLTreePanel_aclTree_mouseAdapter object * @@ -1314,7 +1282,6 @@ private class ACLTreePanel_aclTree_mouseAdapter extends MouseAdapter { this.adaptee = adaptee; } - /** * Description of the Method * @@ -1323,14 +1290,13 @@ private class ACLTreePanel_aclTree_mouseAdapter extends MouseAdapter { public void mouseClicked(MouseEvent e) { adaptee.aclTree_mouseClicked(e); } + } + private class ACLTreePanel_systemMenuItem_actionAdapter implements ActionListener { ACLTracePanel adaptee; - } - private class ACLTreePanel_systemMenuItem_actionAdapter implements ActionListener { - /** * Constructor for the ACLTreePanel_systemMenuItem_actionAdapter object * @@ -1340,7 +1306,6 @@ private class ACLTreePanel_systemMenuItem_actionAdapter implements ActionListene this.adaptee = adaptee; } - /** * Description of the Method * @@ -1349,14 +1314,13 @@ private class ACLTreePanel_systemMenuItem_actionAdapter implements ActionListene public void actionPerformed(ActionEvent e) { adaptee.systemMenuItem_actionPerformed(e); } + } + private class ACLTreePanel_zoomMenuItem_actionAdapter implements ActionListener { ACLTracePanel adaptee; - } - private class ACLTreePanel_zoomMenuItem_actionAdapter implements ActionListener { - /** * Constructor for the ACLTreePanel_zoomMenuItem_actionAdapter object * @@ -1366,7 +1330,6 @@ private class ACLTreePanel_zoomMenuItem_actionAdapter implements ActionListener this.adaptee = adaptee; } - /** * Description of the Method * @@ -1375,13 +1338,12 @@ private class ACLTreePanel_zoomMenuItem_actionAdapter implements ActionListener public void actionPerformed(ActionEvent e) { adaptee.zoomMenuItem_actionPerformed(e); } + } + private class ACLTreePanel_saveMenuItem_actionAdapter implements ActionListener { ACLTracePanel adaptee; - } -// ***EOF*** - private class ACLTreePanel_saveMenuItem_actionAdapter implements ActionListener { /** * Constructor for the ACLTreePanel_saveMenuItem_actionAdapter object @@ -1392,7 +1354,6 @@ private class ACLTreePanel_saveMenuItem_actionAdapter implements ActionListener this.adaptee = adaptee; } - /** * Description of the Method * @@ -1401,14 +1362,12 @@ private class ACLTreePanel_saveMenuItem_actionAdapter implements ActionListener public void actionPerformed(ActionEvent e) { adaptee.saveMenuItem_actionPerformed(e); } + } + private class ACLTreePanel_aclTree_keyAdapter extends KeyAdapter { ACLTracePanel adaptee; - } -// ***EOF*** - - private class ACLTreePanel_aclTree_keyAdapter extends KeyAdapter { /** * Constructor for the ACLTreePanel_aclTree_keyAdapter object @@ -1419,7 +1378,6 @@ private class ACLTreePanel_aclTree_keyAdapter extends KeyAdapter { this.adaptee = adaptee; } - /** * Description of the Method * @@ -1428,14 +1386,12 @@ private class ACLTreePanel_aclTree_keyAdapter extends KeyAdapter { public void keyTyped(KeyEvent e) { adaptee.aclTree_keyTyped(e); } + } + private class ACLTreePanel_deleteMenuItem_actionAdapter implements ActionListener { ACLTracePanel adaptee; - } -// ***EOF*** - - private class ACLTreePanel_deleteMenuItem_actionAdapter implements ActionListener { /** * Constructor for the ACLTreePanel_deleteMenuItem_actionAdapter object @@ -1446,7 +1402,6 @@ private class ACLTreePanel_deleteMenuItem_actionAdapter implements ActionListene this.adaptee = adaptee; } - /** * Description of the Method * @@ -1455,12 +1410,8 @@ private class ACLTreePanel_deleteMenuItem_actionAdapter implements ActionListene public void actionPerformed(ActionEvent e) { adaptee.deleteMenuItem_actionPerformed(e); } - - - ACLTracePanel adaptee; } - /** * This class renderes the ACLTreePanel * @@ -1470,6 +1421,13 @@ public void actionPerformed(ActionEvent e) { private class ACLTreeRenderer extends JLabel implements TreeCellRenderer { + public ImageIcon rootIcon = new ImageIcon(this.getClass().getResource("images/inbox.gif")); + public ImageIcon nodeIcon = new ImageIcon(this.getClass().getResource("images/service.gif")); + public ImageIcon smallAgentIcon = new ImageIcon(this.getClass().getResource("images/smallagent.gif")); + public ImageIcon messageTypeIcon = new ImageIcon(this.getClass().getResource("images/messagetype.gif")); + public ImageIcon detailsIcon = new ImageIcon(this.getClass().getResource("images/details.gif")); + public ImageIcon incomingIcon = new ImageIcon(this.getClass().getResource("images/incoming.gif")); + public ImageIcon outgoingIcon = new ImageIcon(this.getClass().getResource("images/outgoing.gif")); /** * Constructor for the ACLTreeRenderer object */ @@ -1481,7 +1439,6 @@ private class ACLTreeRenderer extends JLabel implements TreeCellRenderer { } } - /** * Gets the TreeCellRendererComponent attribute of the ACLTreeRenderer * object @@ -1549,7 +1506,6 @@ public Component getTreeCellRendererComponent(JTree tree, Object value, boolean return this; } - /** * build up renderer * @@ -1559,18 +1515,8 @@ private void jbInit() throws Exception { this.setFont(new Font("SansSerif", Font.PLAIN, 11)); this.setOpaque(true); } - - - public ImageIcon rootIcon = new ImageIcon(this.getClass().getResource("images/inbox.gif")); - public ImageIcon nodeIcon = new ImageIcon(this.getClass().getResource("images/service.gif")); - public ImageIcon smallAgentIcon = new ImageIcon(this.getClass().getResource("images/smallagent.gif")); - public ImageIcon messageTypeIcon = new ImageIcon(this.getClass().getResource("images/messagetype.gif")); - public ImageIcon detailsIcon = new ImageIcon(this.getClass().getResource("images/details.gif")); - public ImageIcon incomingIcon = new ImageIcon(this.getClass().getResource("images/incoming.gif")); - public ImageIcon outgoingIcon = new ImageIcon(this.getClass().getResource("images/outgoing.gif")); } - private class SortRenderer extends JLabel implements ListCellRenderer { /** @@ -1605,119 +1551,60 @@ public Component getListCellRendererComponent(JList list, Object value, int inde } } - private class ACLTracePanel_aboutMenuItem_mouseAdapter extends MouseAdapter { + ACLTracePanel adaptee; + + ACLTracePanel_aboutMenuItem_mouseAdapter(ACLTracePanel adaptee) { this.adaptee = adaptee; } - public void mouseClicked(MouseEvent e) { adaptee.aboutMenuItem_mouseClicked(e); } + } + private class ACLTracePanel_clearQMenuItem_actionAdapter implements ActionListener { ACLTracePanel adaptee; - } - private class ACLTracePanel_clearQMenuItem_actionAdapter implements ActionListener { - ACLTracePanel_clearQMenuItem_actionAdapter(ACLTracePanel adaptee) { this.adaptee = adaptee; } - public void actionPerformed(ActionEvent e) { adaptee.clearQMenuItem_actionPerformed(e); } + } + private class ACLTracePanel_openQMenuItem_actionAdapter implements ActionListener { ACLTracePanel adaptee; - } - - private class ACLTracePanel_openQMenuItem_actionAdapter implements ActionListener { ACLTracePanel_openQMenuItem_actionAdapter(ACLTracePanel adaptee) { this.adaptee = adaptee; } - public void actionPerformed(ActionEvent e) { adaptee.openQMenuItem_actionPerformed(e); } + } + private class ACLTracePanel_aboutMenuItem_actionAdapter implements ActionListener { ACLTracePanel adaptee; - } - - private class ACLTracePanel_aboutMenuItem_actionAdapter implements ActionListener { ACLTracePanel_aboutMenuItem_actionAdapter(ACLTracePanel adaptee) { this.adaptee = adaptee; } - public void actionPerformed(ActionEvent e) { adaptee.aboutMenuItem_actionPerformed(e); } - - - ACLTracePanel adaptee; } - - - public final static String DIRECTION_IN = "in"; - public final static String DIRECTION_OUT = "out"; - - private static final DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM); - JLabel jLabel1 = new JLabel(); - ButtonGroup sortingButtonGroup = new ButtonGroup(); - JComboBox sortComboBox = new JComboBox<>(); - JRadioButton ascRadioButton = new JRadioButton(); - JRadioButton descRadioButton = new JRadioButton(); - JButton sortButton = new JButton(); - JMenuItem saveQMenuItem = new JMenuItem(); - JMenuItem openQMenuItem = new JMenuItem(); - JMenuItem clearQMenuItem = new JMenuItem(); - Border border2; - Border border3; - private boolean sorting = false; - private final JMenuItem deleteMenuItem = new JMenuItem(); - - private int inMsgCount = 0, outMsgCount = 0; - - private int aclIndex; - private final DefaultMutableTreeNode aclRoot = new DefaultMutableTreeNode("messagetrace"); - private final DefaultTreeModel aclModel = new DefaultTreeModel(aclRoot); - private final GridBagLayout gridBagLayout1 = new GridBagLayout(); - private final GridBagLayout gridBagLayout2 = new GridBagLayout(); - private final JScrollPane aclTreeScrollPane = new JScrollPane(); - private final JTree aclTree = new JTree(); - private final ACLTreeRenderer aclTreeRenderer = new ACLTreeRenderer(); - private final JPopupMenu thePopupMenu = new JPopupMenu(); - private final JMenuItem systemMenuItem = new JMenuItem(); - private final JMenuItem zoomMenuItem = new JMenuItem(); - - private final int currentSelection = 0; - private final JMenuItem saveMenuItem = new JMenuItem(); - private final JMenuItem stasticsMenuItem = new JMenuItem(); - private final JMenuItem aboutMenuItem = new JMenuItem(); - - private final ImageIcon sortIcon = - new ImageIcon(this.getClass().getResource("images/sort.gif")); - - private final DefaultComboBoxModel sortComboBoxModel = new DefaultComboBoxModel<>(); - private final Agent agent; - - private File currentDir; - - private int x, y; - private ACLMessage currentACL; - private Border border1; - private TitledBorder titledBorder1; } // ***EOF*** diff --git a/src/jade/tools/gui/AIDAddressList.java b/src/jade/tools/gui/AIDAddressList.java index a84d2f2..2f6e62e 100644 --- a/src/jade/tools/gui/AIDAddressList.java +++ b/src/jade/tools/gui/AIDAddressList.java @@ -44,6 +44,18 @@ public class AIDAddressList extends JPanel { + private final GridBagLayout gridBagLayout1 = new GridBagLayout(); + private final JList contentList = new JList<>(); + private final JButton viewButton = new JButton(); + private final JButton addButton = new JButton(); + private final JButton deleteButton = new JButton(); + private final DefaultListModel listModel = new DefaultListModel<>(); + private final JScrollPane contentScrollPane = new JScrollPane(); + private boolean editable = true; + private AIDAddressListListener theDataListener; + private AID theAID; + + /** * Constructor for the AIDAddressesList object */ @@ -55,7 +67,6 @@ public AIDAddressList() { } } - /** * Sets the Editable attribute of the AIDAddressesList object * @@ -69,7 +80,6 @@ public void setEditable(boolean theBool) { } } - /** * Description of the Method * @@ -90,7 +100,6 @@ public void register(AID theAID) { contentList.setModel(listModel); } - /** * Description of the Method */ @@ -102,7 +111,6 @@ public void doDelete() { } } - /** * Description of the Method */ @@ -117,7 +125,6 @@ public void doAdd() { } - /** * Description of the Method */ @@ -140,7 +147,6 @@ public void doView() { } } - /** * Description of the Method * @@ -150,7 +156,6 @@ void deleteButton_actionPerformed(ActionEvent e) { doDelete(); } - /** * Adds a feature to the Button_actionPerformed attribute of the * AIDAddressesList object @@ -162,7 +167,6 @@ void addButton_actionPerformed(ActionEvent e) { doAdd(); } - /** * Description of the Method * @@ -172,7 +176,6 @@ void viewButton_actionPerformed(ActionEvent e) { doView(); } - /** * Description of the Method * @@ -196,7 +199,6 @@ void contentList_keyPressed(KeyEvent e) { } - void contentList_mouseClicked(MouseEvent e) { if (e.getClickCount() > 1) { doView(); @@ -204,7 +206,6 @@ void contentList_mouseClicked(MouseEvent e) { } - /** * Description of the Method * @@ -262,7 +263,6 @@ public void keyPressed(KeyEvent e) { , GridBagConstraints.SOUTHEAST, GridBagConstraints.VERTICAL, new Insets(0, 0, 0, 0), 0, 0)); } - /** * This class listenes to the AIDAddressList * @@ -272,13 +272,16 @@ public void keyPressed(KeyEvent e) { private class AIDAddressListListener implements ListDataListener { + private String theRemovedAddress, theChangedAddress; + private AID itsAID; + + /** * Constructor for the AddressListListener object */ public AIDAddressListListener() { } - /** * Description of the Method * @@ -289,7 +292,6 @@ public void register(Object obj, String arg) { itsAID = (AID) obj; } - /** * Description of the Method * @@ -302,7 +304,6 @@ public void intervalAdded(ListDataEvent parm1) { itsAID.addAddresses(newAddress); } - /** * Description of the Method * @@ -312,7 +313,6 @@ public void registerRemovedAddress(String theRemovedAddress) { this.theRemovedAddress = theRemovedAddress; } - /** * Description of the Method * @@ -322,7 +322,6 @@ public void intervalRemoved(ListDataEvent parm1) { itsAID.removeAddresses(theRemovedAddress); } - /** * Description of the Method * @@ -332,7 +331,6 @@ public void registerChangedAddress(String theChangedAddress) { this.theChangedAddress = theChangedAddress; } - /** * Description of the Method * @@ -345,13 +343,8 @@ public void contentsChanged(ListDataEvent parm1) { itsAID.removeAddresses(currentAddress); itsAID.addAddresses(theChangedAddress); } - - - private String theRemovedAddress, theChangedAddress; - private AID itsAID; } - /** * This class show a dialog where the address of an AID can be viewed and * edited. @@ -362,6 +355,18 @@ public void contentsChanged(ListDataEvent parm1) { private class AIDAddressDialog extends JDialog { + private final String CANCELLED = "cancelled"; + GridBagLayout gridBagLayout1 = new GridBagLayout(); + JTextField theAddressField = new JTextField(); + JLabel jLabel1 = new JLabel(); + JPanel buttonPanel = new JPanel(); + JButton okButton = new JButton(); + JButton cancelButton = new JButton(); + private String OK = "ok"; + private String userAction; + private String itsAddress; + + /** * Constructor for the ACLAddressDialog object */ @@ -375,7 +380,6 @@ public AIDAddressDialog() { } } - /** * Gets the ItsAddress attribute of the ACLAddressDialog object * @@ -385,6 +389,15 @@ public String getItsAddress() { return itsAddress; } + /** + * Sets the ItsAddress attribute of the ACLAddressDialog object + * + * @param newItsAddress The new ItsAddress value + */ + public void setItsAddress(String newItsAddress) { + itsAddress = newItsAddress; + this.theAddressField.setText(itsAddress); + } /** * Gets the OK attribute of the ACLAddressDialog object @@ -395,7 +408,6 @@ public boolean getOK() { return userAction.equals(OK); } - /** * Sets the Editable attribute of the ACLAddressDialog object * @@ -409,18 +421,6 @@ public void setEditable(boolean theBool) { } } - - /** - * Sets the ItsAddress attribute of the ACLAddressDialog object - * - * @param newItsAddress The new ItsAddress value - */ - public void setItsAddress(String newItsAddress) { - itsAddress = newItsAddress; - this.theAddressField.setText(itsAddress); - } - - /** * Description of the Method * @@ -452,7 +452,6 @@ void jbInit() throws Exception { buttonPanel.add(cancelButton, null); } - /** * Description of the Method * @@ -463,7 +462,6 @@ void cancelButton_actionPerformed(ActionEvent e) { setVisible(false); } - /** * Description of the Method * @@ -475,7 +473,6 @@ void okButton_actionPerformed(ActionEvent e) { setVisible(false); } - /** * Gets the UserAction attribute of the ACLAddressDialog object * @@ -485,7 +482,6 @@ private String getUserAction() { return userAction; } - /** * Sets the UserAction attribute of the ACLAddressDialog object * @@ -495,34 +491,7 @@ private void setUserAction(String newUserAction) { userAction = newUserAction; } - - GridBagLayout gridBagLayout1 = new GridBagLayout(); - JTextField theAddressField = new JTextField(); - JLabel jLabel1 = new JLabel(); - JPanel buttonPanel = new JPanel(); - JButton okButton = new JButton(); - JButton cancelButton = new JButton(); - - private String OK = "ok"; - private final String CANCELLED = "cancelled"; - private String userAction; - private String itsAddress; - } - - private final GridBagLayout gridBagLayout1 = new GridBagLayout(); - private final JList contentList = new JList<>(); - private final JButton viewButton = new JButton(); - private final JButton addButton = new JButton(); - private final JButton deleteButton = new JButton(); - - private final DefaultListModel listModel = new DefaultListModel<>(); - private final JScrollPane contentScrollPane = new JScrollPane(); - - private boolean editable = true; - private AIDAddressListListener theDataListener; - private AID theAID; - } // ***EOF*** diff --git a/src/jade/tools/gui/AIDTextField.java b/src/jade/tools/gui/AIDTextField.java index 9207341..14342b3 100644 --- a/src/jade/tools/gui/AIDTextField.java +++ b/src/jade/tools/gui/AIDTextField.java @@ -42,6 +42,9 @@ public class AIDTextField extends JTextField implements Observer { + private AID itsAid; + private String fieldName; + /** * Description of the Method * @@ -61,7 +64,6 @@ public void register(Object arg, String fieldName) { } } - /** * Description of the Method * @@ -72,7 +74,6 @@ public void unregister(Object arg, String str) { // itsAid.deleteObserver(this); } - /** * Description of the Method * @@ -93,7 +94,6 @@ public void update(Observable ob, Object arg) { } } - /** * Description of the Method * @@ -111,7 +111,6 @@ public void focusLost(FocusEvent e) { } } - /** * Description of the Method * @@ -124,9 +123,5 @@ protected void processFocusEvent(FocusEvent e) { } } - - - private AID itsAid; - private String fieldName; } // ***EOF*** diff --git a/src/jade/tools/gui/EnvCommentsTextArea.java b/src/jade/tools/gui/EnvCommentsTextArea.java index 7a5fa4a..1a7ecf3 100644 --- a/src/jade/tools/gui/EnvCommentsTextArea.java +++ b/src/jade/tools/gui/EnvCommentsTextArea.java @@ -43,6 +43,9 @@ public class EnvCommentsTextArea extends JTextArea implements Observer { + private Object theObj; + private String fieldName; + /** * register an ACLMessage with the accompagnied membername * @@ -66,7 +69,6 @@ public void register(Object arg, String fieldName) { } - /** * unregister ACLMessage * @@ -77,7 +79,6 @@ public void unregister(Object arg, String str) { } - /** * update textField * @@ -99,7 +100,6 @@ public void update(Observable ob, Object arg) { } - /** * triggered when focus lossed * @@ -117,7 +117,6 @@ public void focusLost(FocusEvent e) { } } - /** * processFocusEvent listener * @@ -130,9 +129,5 @@ protected void processFocusEvent(FocusEvent e) { } } - - - private Object theObj; - private String fieldName; } // ***EOF*** diff --git a/src/jade/tools/introspector/Introspector.java b/src/jade/tools/introspector/Introspector.java index 2fe0764..6669f10 100644 --- a/src/jade/tools/introspector/Introspector.java +++ b/src/jade/tools/introspector/Introspector.java @@ -63,43 +63,6 @@ */ public class Introspector extends ToolAgent { - private Set allAgents = null; - private Hashtable preload = null; - - private class AMSRequester extends SimpleAchieveREInitiator { - - private final String actionName; - - - public AMSRequester(String an, ACLMessage request) { - super(Introspector.this, request); - actionName = an; - } - - protected void handleNotUnderstood(ACLMessage reply) { - myGUI.showError("NOT-UNDERSTOOD received during " + actionName); - } - - protected void handleRefuse(ACLMessage reply) { - myGUI.showError("REFUSE received during " + actionName); - } - - protected void handleAgree(ACLMessage reply) { - if (logger.isLoggable(Logger.FINEST)) - logger.log(Logger.FINEST, "AGREE received"); - } - - protected void handleFailure(ACLMessage reply) { - myGUI.showError("FAILURE received during " + actionName); - } - - protected void handleInform(ACLMessage reply) { - if (logger.isLoggable(Logger.FINEST)) - logger.log(Logger.FINEST, "INFORM received"); - } - - } // End of AMSRequester class - // GUI events public static final int STEP_EVENT = 1; public static final int BREAK_EVENT = 2; @@ -107,12 +70,8 @@ protected void handleInform(ACLMessage reply) { public static final int GO_EVENT = 4; public static final int KILL_EVENT = 5; public static final int SUSPEND_EVENT = 6; - - private IntrospectorGUI myGUI; private final Sensor guiSensor = new Sensor(); - private String myContainerName; private final Map windowMap = Collections.synchronizedMap(new TreeMap<>()); - // The set of agents that are observed in step-by-step mode private final Set stepByStepAgents = new HashSet<>(); // The set of agents that are observed in slow mode @@ -123,89 +82,11 @@ protected void handleInform(ACLMessage reply) { // Maps an observed agent with the ToolNotifier that notifies events // about that agent to this Introspector private final Map notifiers = new HashMap<>(); - private final SequentialBehaviour AMSSubscribe = new SequentialBehaviour(); - - class IntrospectorAMSListenerBehaviour extends AMSListenerBehaviour { - - protected void installHandlers(Map handlersTable) { - - handlersTable.put(IntrospectionVocabulary.META_RESETEVENTS, (EventHandler) ev -> { - ResetEvents re = (ResetEvents) ev; - myGUI.resetTree(); - }); - - handlersTable.put(IntrospectionVocabulary.ADDEDCONTAINER, (EventHandler) ev -> { - AddedContainer ac = (AddedContainer) ev; - ContainerID cid = ac.getContainer(); - String name = cid.getName(); - String address = cid.getAddress(); - try { - InetAddress addr = InetAddress.getByName(address); - myGUI.addContainer(name, addr); - } catch (UnknownHostException uhe) { - myGUI.addContainer(name, null); - } - }); - - handlersTable.put(IntrospectionVocabulary.REMOVEDCONTAINER, (EventHandler) ev -> { - RemovedContainer rc = (RemovedContainer) ev; - ContainerID cid = rc.getContainer(); - String name = cid.getName(); - myGUI.removeContainer(name); - }); - - handlersTable.put(IntrospectionVocabulary.BORNAGENT, (EventHandler) ev -> { - BornAgent ba = (BornAgent) ev; - ContainerID cid = ba.getWhere(); - // ContainerID is null in case of foreign agents registered with the local AMS or virtual agents - // FIXME: Such agents should be shown somewhere - if (cid != null) { - String container = cid.getName(); - AID agent = ba.getAgent(); - allAgents.add(agent); - myGUI.addAgent(container, agent); - if (preloadContains(agent.getName()) != null) - Introspector.this.addAgent(agent); - if (agent.equals(getAID())) - myContainerName = container; - } - }); - - handlersTable.put(IntrospectionVocabulary.DEADAGENT, (EventHandler) ev -> { - DeadAgent da = (DeadAgent) ev; - ContainerID cid = da.getWhere(); - // ContainerID is null in case of foreign agents registered with the local AMS or virtual agents - if (cid != null) { - String container = cid.getName(); - AID agent = da.getAgent(); - allAgents.remove(agent); - MainWindow m = windowMap.get(agent); - if (m != null) { - myGUI.closeInternal(m); - windowMap.remove(agent); - } - myGUI.removeAgent(container, agent); - } - }); - - handlersTable.put(IntrospectionVocabulary.MOVEDAGENT, (EventHandler) ev -> { - MovedAgent ma = (MovedAgent) ev; - AID agent = ma.getAgent(); - ContainerID from = ma.getFrom(); - myGUI.removeAgent(from.getName(), agent); - ContainerID to = ma.getTo(); - myGUI.addAgent(to.getName(), agent); - - if (windowMap.containsKey(agent)) { - MainWindow m = windowMap.get(agent); - // FIXME: We should clean behaviours and pending messages here - requestDebugOn(agent); - } - }); - - } // End of installHandlers() method - } + private Set allAgents = null; + private Hashtable preload = null; + private IntrospectorGUI myGUI; + private String myContainerName; public void toolSetup() { @@ -348,7 +229,6 @@ public void removeAgent(final AID name) { } } - /** * Cleanup during agent shutdown. This method cleans things up when * RMA agent is destroyed, disconnecting from AMS @@ -385,7 +265,6 @@ public void toolTakeDown() { myGUI.disposeAsync(); } - /** * Callback method for platform management GUI. */ @@ -393,6 +272,252 @@ public AgentTreeModel getModel() { return myGUI.getModel(); } + private void proceed(AID id) { + String pendingReplyWith = pendingReplies.remove(id); + AID tn = notifiers.get(id); + if (pendingReplyWith != null && tn != null) { + ACLMessage msg = new ACLMessage(ACLMessage.INFORM); + msg.addReceiver(tn); + msg.setInReplyTo(pendingReplyWith); + send(msg); + } + } + + /** + * The doDelete() method is re-defined because if the Introspector is + * killed while it is debugging the AMS a deadlock occurs. In fact, + * while exiting, the Introspector can't make the debugged agents + * proceed. At the same time however the Introspector can't proceed as it + * is waiting for the answer to its AMS deregistration + */ + public void doDelete() { + AID amsId = getAMS(); + if (windowMap.containsKey(amsId)) { + try { + final MainWindow m = windowMap.get(amsId); + myGUI.closeInternal(m); + windowMap.remove(amsId); + + stepByStepAgents.remove(amsId); + slowAgents.remove(amsId); + proceed(amsId); + + ACLMessage msg = getRequest(); + msg.setOntology(JADEManagementOntology.NAME); + DebugOff dbgOff = new DebugOff(); + dbgOff.setDebugger(getAID()); + dbgOff.addDebuggedAgents(amsId); + Action a = new Action(); + a.setActor(getAMS()); + a.setAction(dbgOff); + + getContentManager().fillContent(msg, a); + + addBehaviour(new AMSRequester("DebugOff", msg) { + public int onEnd() { + myAgent.doDelete(); + return 0; + } + }); + } catch (Exception fe) { + fe.printStackTrace(); + } + } else { + super.doDelete(); + } + } + + /** + * Search keys in preload for a string which matches (using isMatch method) + * the agent name. + * + * @param agentName The agent name. + * @return String The key which matched. + */ + protected String preloadContains(String agentName) { + for (Enumeration enumeration = preload.keys(); enumeration.hasMoreElements(); ) { + String key = enumeration.nextElement(); + if (isMatch(key, agentName)) { + return key; + } + } + return null; + } + + /** + * Given two strings determine if they match. We iterate over the match expression + * string from left to right as follows: + *
    + *
  1. If we encounter a '*' in the expression token they match. + *
  2. If there aren't any more characters in the subject string token they don't match. + *
  3. If we encounter a '?' in the expression token we ignore the subject string's + * character and move on to the next iteration. + *
  4. If the character in the expression token isn't equal to the character in + * the subject string they don't match. + *
+ * If we complete the iteration they match only if there are the same number of + * characters in both strings. + * + * @param aMatchExpression An expression string with special significance to '?' and '*'. + * @param aString The subject string. + * @return True if they match, false otherwise. + */ + protected boolean isMatch(String aMatchExpression, String aString) { + int expressionLength = aMatchExpression.length(); + for (int i = 0; i < expressionLength; i++) { + char expChar = aMatchExpression.charAt(i); + if (expChar == '*') + return true; // * matches the remainder of anything + if (i == aString.length()) + return false; // if we run out of characters they don't match + if (expChar == '?') + continue; // ? matches any single character so keep going + if (expChar != aString.charAt(i)) + return false; // if non wild then must be exactly equal + } + return (expressionLength == aString.length()); + } + + private void parsePreloadDescription(String aDescription) { + StringTokenizer st = new StringTokenizer(aDescription); + String name = st.nextToken(); + if (!name.endsWith("*")) { + int atPos = name.lastIndexOf('@'); + if (atPos == -1) { + name = name + "@" + getHap(); + } + } + + int performativeCount = ACLMessage.getAllPerformativeNames().length; + boolean[] filter = new boolean[performativeCount]; + boolean initVal = (!st.hasMoreTokens()); + for (int i = 0; i < performativeCount; i++) { + filter[i] = initVal; + } + while (st.hasMoreTokens()) { + int perfIndex = ACLMessage.getInteger(st.nextToken()); + if (perfIndex != -1) { + filter[perfIndex] = true; + } + } + preload.put(name, filter); + } + + private class AMSRequester extends SimpleAchieveREInitiator { + + private final String actionName; + + + public AMSRequester(String an, ACLMessage request) { + super(Introspector.this, request); + actionName = an; + } + + protected void handleNotUnderstood(ACLMessage reply) { + myGUI.showError("NOT-UNDERSTOOD received during " + actionName); + } + + protected void handleRefuse(ACLMessage reply) { + myGUI.showError("REFUSE received during " + actionName); + } + + protected void handleAgree(ACLMessage reply) { + if (logger.isLoggable(Logger.FINEST)) + logger.log(Logger.FINEST, "AGREE received"); + } + + protected void handleFailure(ACLMessage reply) { + myGUI.showError("FAILURE received during " + actionName); + } + + protected void handleInform(ACLMessage reply) { + if (logger.isLoggable(Logger.FINEST)) + logger.log(Logger.FINEST, "INFORM received"); + } + + } // End of AMSRequester class + + class IntrospectorAMSListenerBehaviour extends AMSListenerBehaviour { + + protected void installHandlers(Map handlersTable) { + + handlersTable.put(IntrospectionVocabulary.META_RESETEVENTS, (EventHandler) ev -> { + ResetEvents re = (ResetEvents) ev; + myGUI.resetTree(); + }); + + handlersTable.put(IntrospectionVocabulary.ADDEDCONTAINER, (EventHandler) ev -> { + AddedContainer ac = (AddedContainer) ev; + ContainerID cid = ac.getContainer(); + String name = cid.getName(); + String address = cid.getAddress(); + try { + InetAddress addr = InetAddress.getByName(address); + myGUI.addContainer(name, addr); + } catch (UnknownHostException uhe) { + myGUI.addContainer(name, null); + } + }); + + handlersTable.put(IntrospectionVocabulary.REMOVEDCONTAINER, (EventHandler) ev -> { + RemovedContainer rc = (RemovedContainer) ev; + ContainerID cid = rc.getContainer(); + String name = cid.getName(); + myGUI.removeContainer(name); + }); + + handlersTable.put(IntrospectionVocabulary.BORNAGENT, (EventHandler) ev -> { + BornAgent ba = (BornAgent) ev; + ContainerID cid = ba.getWhere(); + // ContainerID is null in case of foreign agents registered with the local AMS or virtual agents + // FIXME: Such agents should be shown somewhere + if (cid != null) { + String container = cid.getName(); + AID agent = ba.getAgent(); + allAgents.add(agent); + myGUI.addAgent(container, agent); + if (preloadContains(agent.getName()) != null) + Introspector.this.addAgent(agent); + if (agent.equals(getAID())) + myContainerName = container; + } + }); + + handlersTable.put(IntrospectionVocabulary.DEADAGENT, (EventHandler) ev -> { + DeadAgent da = (DeadAgent) ev; + ContainerID cid = da.getWhere(); + // ContainerID is null in case of foreign agents registered with the local AMS or virtual agents + if (cid != null) { + String container = cid.getName(); + AID agent = da.getAgent(); + allAgents.remove(agent); + MainWindow m = windowMap.get(agent); + if (m != null) { + myGUI.closeInternal(m); + windowMap.remove(agent); + } + myGUI.removeAgent(container, agent); + } + }); + + handlersTable.put(IntrospectionVocabulary.MOVEDAGENT, (EventHandler) ev -> { + MovedAgent ma = (MovedAgent) ev; + AID agent = ma.getAgent(); + ContainerID from = ma.getFrom(); + myGUI.removeAgent(from.getName(), agent); + ContainerID to = ma.getTo(); + myGUI.addAgent(to.getName(), agent); + + if (windowMap.containsKey(agent)) { + MainWindow m = windowMap.get(agent); + // FIXME: We should clean behaviours and pending messages here + requestDebugOn(agent); + } + }); + + } // End of installHandlers() method + } + /* Listens to introspective messages and dispatches them. */ @@ -515,7 +640,6 @@ public void action() { } // End of inner class IntrospectionListenerBehaviour - /** * Inner class ControlListenerBehaviour. * This is a behaviour that listen for messages from ToolNotifiers @@ -553,137 +677,6 @@ public void action() { } // End of inner class ControlListenerBehaviour - private void proceed(AID id) { - String pendingReplyWith = pendingReplies.remove(id); - AID tn = notifiers.get(id); - if (pendingReplyWith != null && tn != null) { - ACLMessage msg = new ACLMessage(ACLMessage.INFORM); - msg.addReceiver(tn); - msg.setInReplyTo(pendingReplyWith); - send(msg); - } - } - - /** - * The doDelete() method is re-defined because if the Introspector is - * killed while it is debugging the AMS a deadlock occurs. In fact, - * while exiting, the Introspector can't make the debugged agents - * proceed. At the same time however the Introspector can't proceed as it - * is waiting for the answer to its AMS deregistration - */ - public void doDelete() { - AID amsId = getAMS(); - if (windowMap.containsKey(amsId)) { - try { - final MainWindow m = windowMap.get(amsId); - myGUI.closeInternal(m); - windowMap.remove(amsId); - - stepByStepAgents.remove(amsId); - slowAgents.remove(amsId); - proceed(amsId); - - ACLMessage msg = getRequest(); - msg.setOntology(JADEManagementOntology.NAME); - DebugOff dbgOff = new DebugOff(); - dbgOff.setDebugger(getAID()); - dbgOff.addDebuggedAgents(amsId); - Action a = new Action(); - a.setActor(getAMS()); - a.setAction(dbgOff); - - getContentManager().fillContent(msg, a); - - addBehaviour(new AMSRequester("DebugOff", msg) { - public int onEnd() { - myAgent.doDelete(); - return 0; - } - }); - } catch (Exception fe) { - fe.printStackTrace(); - } - } else { - super.doDelete(); - } - } - - /** - * Search keys in preload for a string which matches (using isMatch method) - * the agent name. - * - * @param agentName The agent name. - * @return String The key which matched. - */ - protected String preloadContains(String agentName) { - for (Enumeration enumeration = preload.keys(); enumeration.hasMoreElements(); ) { - String key = enumeration.nextElement(); - if (isMatch(key, agentName)) { - return key; - } - } - return null; - } - - /** - * Given two strings determine if they match. We iterate over the match expression - * string from left to right as follows: - *
    - *
  1. If we encounter a '*' in the expression token they match. - *
  2. If there aren't any more characters in the subject string token they don't match. - *
  3. If we encounter a '?' in the expression token we ignore the subject string's - * character and move on to the next iteration. - *
  4. If the character in the expression token isn't equal to the character in - * the subject string they don't match. - *
- * If we complete the iteration they match only if there are the same number of - * characters in both strings. - * - * @param aMatchExpression An expression string with special significance to '?' and '*'. - * @param aString The subject string. - * @return True if they match, false otherwise. - */ - protected boolean isMatch(String aMatchExpression, String aString) { - int expressionLength = aMatchExpression.length(); - for (int i = 0; i < expressionLength; i++) { - char expChar = aMatchExpression.charAt(i); - if (expChar == '*') - return true; // * matches the remainder of anything - if (i == aString.length()) - return false; // if we run out of characters they don't match - if (expChar == '?') - continue; // ? matches any single character so keep going - if (expChar != aString.charAt(i)) - return false; // if non wild then must be exactly equal - } - return (expressionLength == aString.length()); - } - - private void parsePreloadDescription(String aDescription) { - StringTokenizer st = new StringTokenizer(aDescription); - String name = st.nextToken(); - if (!name.endsWith("*")) { - int atPos = name.lastIndexOf('@'); - if (atPos == -1) { - name = name + "@" + getHap(); - } - } - - int performativeCount = ACLMessage.getAllPerformativeNames().length; - boolean[] filter = new boolean[performativeCount]; - boolean initVal = (!st.hasMoreTokens()); - for (int i = 0; i < performativeCount; i++) { - filter[i] = initVal; - } - while (st.hasMoreTokens()) { - int perfIndex = ACLMessage.getInteger(st.nextToken()); - if (perfIndex != -1) { - filter[perfIndex] = true; - } - } - preload.put(name, filter); - } - /** * Inner class RequestListenerBehaviour. * This behaviour serves requests to start debugging agents. diff --git a/src/jade/tools/introspector/Sensor.java b/src/jade/tools/introspector/Sensor.java index e5b7378..fda20c6 100644 --- a/src/jade/tools/introspector/Sensor.java +++ b/src/jade/tools/introspector/Sensor.java @@ -30,7 +30,7 @@ import java.util.Vector; /** - * @author Giovanni Caire - TILab + * @author Giovanni Caire - TILab */ public class Sensor { private final Vector eventQueue = new Vector<>(); diff --git a/src/jade/tools/introspector/SensorManager.java b/src/jade/tools/introspector/SensorManager.java index 05ae938..5740b98 100644 --- a/src/jade/tools/introspector/SensorManager.java +++ b/src/jade/tools/introspector/SensorManager.java @@ -29,7 +29,7 @@ import jade.util.Event; /** - * @author Giovanni Caire - TILab + * @author Giovanni Caire - TILab */ public abstract class SensorManager extends CyclicBehaviour { private final Sensor mySensor; diff --git a/src/jade/tools/introspector/gui/AboutBoxAction.java b/src/jade/tools/introspector/gui/AboutBoxAction.java index 80e1c9f..b869eaf 100644 --- a/src/jade/tools/introspector/gui/AboutBoxAction.java +++ b/src/jade/tools/introspector/gui/AboutBoxAction.java @@ -41,11 +41,9 @@ public class AboutBoxAction extends AbstractAction { private final JFrame gui; - private JLabel label; private final String imageFile = "images/jadelogo.jpg"; - - Color dark_blue = new Color(0, 0, 160); + private JLabel label; public AboutBoxAction(JFrame gui) { super("About Introspector"); diff --git a/src/jade/tools/introspector/gui/BehaviourPanel.java b/src/jade/tools/introspector/gui/BehaviourPanel.java index b4b3b92..9eb751b 100644 --- a/src/jade/tools/introspector/gui/BehaviourPanel.java +++ b/src/jade/tools/introspector/gui/BehaviourPanel.java @@ -39,11 +39,11 @@ */ public class BehaviourPanel extends JSplitPane { private final JTree behaviourTree; + private final TreeMouseListener treeListener; private JTextArea text; private JScrollPane behaviourScroll; private JScrollPane textScroll; private JPanel treePanel; - private final TreeMouseListener treeListener; private Icon readyIcon; private Icon runningIcon; private Icon blockedIcon; diff --git a/src/jade/tools/introspector/gui/BehaviourTreeNode.java b/src/jade/tools/introspector/gui/BehaviourTreeNode.java index a49aa46..ed2fe26 100644 --- a/src/jade/tools/introspector/gui/BehaviourTreeNode.java +++ b/src/jade/tools/introspector/gui/BehaviourTreeNode.java @@ -49,15 +49,19 @@ public BehaviourTreeNode(BehaviourID beh, String s) { state = s; } + public String getState() { + return state; + } + /*public BehaviourTreeNode(BehaviourID beh, boolean bl) { behaviour = beh; blocked = bl; } - + public void setBlocked(boolean b) { blocked = b; } - + public boolean isBlocked() { return blocked; }*/ @@ -65,10 +69,6 @@ public void setState(String s) { state = s; } - public String getState() { - return state; - } - public String toString() { return behaviour.toString(); } diff --git a/src/jade/tools/introspector/gui/GuiProperties.java b/src/jade/tools/introspector/gui/GuiProperties.java index 453f5ef..a6fbf86 100644 --- a/src/jade/tools/introspector/gui/GuiProperties.java +++ b/src/jade/tools/introspector/gui/GuiProperties.java @@ -37,16 +37,17 @@ /** * This class loads the icons used. + * * @see jade.gui.GuiProperties */ public class GuiProperties { - protected static UIDefaults MyDefaults; - protected static GuiProperties foo = new GuiProperties(); public static final String ImagePath = ""; //loging private static final Logger logger = Logger.getMyLogger(GuiProperties.class.getName()); + protected static UIDefaults MyDefaults; + protected static GuiProperties foo = new GuiProperties(); static { Object[] icons = { diff --git a/src/jade/tools/introspector/gui/MainBar.java b/src/jade/tools/introspector/gui/MainBar.java index 17c5b43..ed47f37 100644 --- a/src/jade/tools/introspector/gui/MainBar.java +++ b/src/jade/tools/introspector/gui/MainBar.java @@ -32,10 +32,10 @@ * @version $Date: 2002-08-28 16:50:19 +0200 (mer, 28 ago 2002) $ $Revision: 3351 $ */ public class MainBar extends JMenuBar { + private final MainBarListener listener; private JMenu stateMenu; private JMenu viewMenu; private JMenu debugMenu; - private JCheckBoxMenuItem viewMessageItem; private JCheckBoxMenuItem vewBehaviourItem; private JMenuItem exitItem; @@ -48,8 +48,6 @@ public class MainBar extends JMenuBar { private JMenuItem slowItem; private JMenuItem goItem; - private final MainBarListener listener; - public MainBar(MainBarListener list) { super(); diff --git a/src/jade/tools/introspector/gui/MainBarListener.java b/src/jade/tools/introspector/gui/MainBarListener.java index e955106..7fe9e4d 100644 --- a/src/jade/tools/introspector/gui/MainBarListener.java +++ b/src/jade/tools/introspector/gui/MainBarListener.java @@ -40,11 +40,10 @@ * @version $Date: 2004-07-19 17:54:06 +0200 (lun, 19 lug 2004) $ $Revision: 5217 $ */ public class MainBarListener implements ActionListener { + private static final Logger logger = Logger.getMyLogger(MainBarListener.class.getName()); private final MainWindow mainWnd; private final Sensor introspectorSensor; - private static final Logger logger = Logger.getMyLogger(MainBarListener.class.getName()); - public MainBarListener(MainWindow main, Sensor s) { mainWnd = main; introspectorSensor = s; diff --git a/src/jade/tools/introspector/gui/StatePanel.java b/src/jade/tools/introspector/gui/StatePanel.java index 64ae914..8852e72 100644 --- a/src/jade/tools/introspector/gui/StatePanel.java +++ b/src/jade/tools/introspector/gui/StatePanel.java @@ -46,9 +46,15 @@ */ public class StatePanel extends JPanel { - private int state; - private final ButtonGroup leds; + private final Icon ledOff = new ImageIcon(getClass().getResource("images/rbs.gif")); + private final Icon ledOn = new ImageIcon(getClass().getResource("images/rbrs.gif")); + private final Icon button = new ImageIcon(getClass().getResource("images/rb.gif")); + private final Icon pressedButton = new ImageIcon(getClass().getResource("images/rbp.gif")); + private final Font myFont = new Font("Monospaced", Font.BOLD, 10); + private final MainBarListener listener; + private final Map ledMap = new HashMap<>(); + private int state; private JRadioButton waitingLed; private JRadioButton activeLed; private JRadioButton suspendedLed; @@ -60,16 +66,6 @@ public class StatePanel extends JPanel { private JButton wakeUpAction; private JButton killAction; - private final Icon ledOff = new ImageIcon(getClass().getResource("images/rbs.gif")); - private final Icon ledOn = new ImageIcon(getClass().getResource("images/rbrs.gif")); - private final Icon button = new ImageIcon(getClass().getResource("images/rb.gif")); - private final Icon pressedButton = new ImageIcon(getClass().getResource("images/rbp.gif")); - private final Font myFont = new Font("Monospaced", Font.BOLD, 10); - - private final MainBarListener listener; - - private final Map ledMap = new HashMap<>(); - public StatePanel(MainBarListener list) { super(); leds = new ButtonGroup(); diff --git a/src/jade/tools/introspector/gui/TableMouseListener.java b/src/jade/tools/introspector/gui/TableMouseListener.java index 72738c1..2cecb6e 100644 --- a/src/jade/tools/introspector/gui/TableMouseListener.java +++ b/src/jade/tools/introspector/gui/TableMouseListener.java @@ -36,8 +36,8 @@ * @author Andrea Squeri,Corti Denis,Ballestracci Paolo - Universita` di Parma */ class TableMouseListener implements MouseListener { - private MessagePanel parent; private final TablePopupMenu popMenu; + private MessagePanel parent; TableMouseListener() { popMenu = new TablePopupMenu(); diff --git a/src/jade/tools/introspector/gui/TablePopupMenu.java b/src/jade/tools/introspector/gui/TablePopupMenu.java index f7bfc5a..a957a4c 100644 --- a/src/jade/tools/introspector/gui/TablePopupMenu.java +++ b/src/jade/tools/introspector/gui/TablePopupMenu.java @@ -60,11 +60,11 @@ public TablePopupMenu() { } - public void setTable(JTable t) { - table = t; - } - public JTable getTable() { return table; } + + public void setTable(JTable t) { + table = t; + } } diff --git a/src/jade/tools/introspector/gui/TableUpdater.java b/src/jade/tools/introspector/gui/TableUpdater.java index 2f9ad5e..c0e6934 100644 --- a/src/jade/tools/introspector/gui/TableUpdater.java +++ b/src/jade/tools/introspector/gui/TableUpdater.java @@ -61,10 +61,8 @@ public TableUpdater(MessagePanel wnd, SentMessage sm) { ACLCodec codec = new StringACLCodec(); msg = codec.decode(s.getBytes(charset), charset); msg.setEnvelope(e); - } catch (ACLCodec.CodecException aclce) { + } catch (ACLCodec.CodecException | UnsupportedEncodingException aclce) { aclce.printStackTrace(); - } catch (UnsupportedEncodingException exception) { - exception.printStackTrace(); } } @@ -83,10 +81,8 @@ public TableUpdater(MessagePanel wnd, PostedMessage pm) { ACLCodec codec = new StringACLCodec(); msg = codec.decode(s.getBytes(charset), charset); msg.setEnvelope(e); - } catch (ACLCodec.CodecException aclce) { + } catch (ACLCodec.CodecException | UnsupportedEncodingException aclce) { aclce.printStackTrace(); - } catch (UnsupportedEncodingException exception) { - exception.printStackTrace(); } } @@ -105,10 +101,8 @@ public TableUpdater(MessagePanel wnd, ReceivedMessage rm) { ACLCodec codec = new StringACLCodec(); msg = codec.decode(s.getBytes(charset), charset); msg.setEnvelope(e); - } catch (ACLCodec.CodecException aclce) { + } catch (ACLCodec.CodecException | UnsupportedEncodingException aclce) { aclce.printStackTrace(); - } catch (UnsupportedEncodingException exception) { - exception.printStackTrace(); } } diff --git a/src/jade/tools/introspector/gui/TreeAgentPopupMenu.java b/src/jade/tools/introspector/gui/TreeAgentPopupMenu.java index 4a8ee5c..8ef620f 100644 --- a/src/jade/tools/introspector/gui/TreeAgentPopupMenu.java +++ b/src/jade/tools/introspector/gui/TreeAgentPopupMenu.java @@ -36,9 +36,9 @@ class TreeAgentPopupMenu extends JPopupMenu { + private final AgentTree tree; Introspector debugger; String agentName; - private final AgentTree tree; public TreeAgentPopupMenu(Introspector d, AgentTree t) { debugger = d; diff --git a/src/jade/tools/introspector/gui/TreePanel.java b/src/jade/tools/introspector/gui/TreePanel.java index eb8caeb..18d910e 100644 --- a/src/jade/tools/introspector/gui/TreePanel.java +++ b/src/jade/tools/introspector/gui/TreePanel.java @@ -40,12 +40,12 @@ */ class TreePanel extends JPanel implements TreeSelectionListener { + private final JSplitPane pane; + private final IntrospectorGUI mainWnd; public JTextArea selArea; AgentTree treeAgent; // FIXME: It should be private private JScrollPane scroll; private JSplitPane pan; - private final JSplitPane pane; - private final IntrospectorGUI mainWnd; private PopUpMouser popM; public TreePanel(IntrospectorGUI mainWnd) { diff --git a/src/jade/tools/introspector/gui/TreePopupMenuListener.java b/src/jade/tools/introspector/gui/TreePopupMenuListener.java index ac201aa..9374d2f 100644 --- a/src/jade/tools/introspector/gui/TreePopupMenuListener.java +++ b/src/jade/tools/introspector/gui/TreePopupMenuListener.java @@ -35,8 +35,8 @@ * @author Andrea Squeri,Corti Denis,Ballestracci Paolo - Universita` di Parma */ public class TreePopupMenuListener implements ActionListener { - private boolean addBehaviour; private final JTree myTree; + private boolean addBehaviour; public TreePopupMenuListener(JTree tree) { myTree = tree; diff --git a/src/jade/tools/introspector/gui/TreeUpdater.java b/src/jade/tools/introspector/gui/TreeUpdater.java index a0425b0..19b5136 100644 --- a/src/jade/tools/introspector/gui/TreeUpdater.java +++ b/src/jade/tools/introspector/gui/TreeUpdater.java @@ -45,16 +45,15 @@ */ public class TreeUpdater implements Runnable { + private static final int ADD_NODE = 0; + private static final int REMOVE_NODE = 1; + private static final int CHANGE_NODE = 2; private final BehaviourID behaviour; private final BehaviourPanel gui; private final int action; //private boolean blocked; private final String state; - private static final int ADD_NODE = 0; - private static final int REMOVE_NODE = 1; - private static final int CHANGE_NODE = 2; - public TreeUpdater(AddedBehaviour b, BehaviourPanel bp) { behaviour = b.getBehaviour(); gui = bp; @@ -84,6 +83,10 @@ public TreeUpdater(ChangedBehaviourState b, BehaviourPanel bp) { state = b.getTo(); } + public static void description(JTextArea t, BehaviourID b) { + t.setText("Name:\t" + b.getName() + "\nClass:\t" + b.getClassName() + "\nKind:\t" + b.getKind()); + } + public void createTree(DefaultMutableTreeNode r, Iterator v) { while (v.hasNext()) { BehaviourID b = v.next(); @@ -138,7 +141,7 @@ public void run() { break; } } - + /* If we didn't find the node in the tree, add it now. if (!bFound) action = ADD_NODE; @@ -169,8 +172,4 @@ public void run() { } } } - - public static void description(JTextArea t, BehaviourID b) { - t.setText("Name:\t" + b.getName() + "\nClass:\t" + b.getClassName() + "\nKind:\t" + b.getKind()); - } } diff --git a/src/jade/tools/logging/JavaLoggingLogManagerImpl.java b/src/jade/tools/logging/JavaLoggingLogManagerImpl.java index ebd9b8c..1ec8c11 100644 --- a/src/jade/tools/logging/JavaLoggingLogManagerImpl.java +++ b/src/jade/tools/logging/JavaLoggingLogManagerImpl.java @@ -41,6 +41,7 @@ public class JavaLoggingLogManagerImpl implements LogManager { public static final String JAVA_LOGGING_LOG_MANAGER_CLASS = "jade.tools.logging.JavaLoggingLogManagerImpl"; private static final String DEFAULT_ROOT_LOGGER_NAME = "__ROOT_LOGGER"; private static final List levels = new ArrayList<>(); + private static final String LOGGER_FRIENDLY_NAME = "Java Util Logging"; static { levels.add(new LevelInfo(Level.ALL.getName(), Level.ALL.intValue())); @@ -54,9 +55,7 @@ public class JavaLoggingLogManagerImpl implements LogManager { levels.add(new LevelInfo(Level.OFF.getName(), Level.OFF.intValue())); } - private final java.util.logging.LogManager logManager = java.util.logging.LogManager.getLogManager(); - private static final String LOGGER_FRIENDLY_NAME = "Java Util Logging"; private List loggers = null; private ArrayList rootHandlers = null; //root handlers specified in configuration file. diff --git a/src/jade/tools/logging/LogHelperAgent.java b/src/jade/tools/logging/LogHelperAgent.java index 24b83ab..732c164 100644 --- a/src/jade/tools/logging/LogHelperAgent.java +++ b/src/jade/tools/logging/LogHelperAgent.java @@ -53,9 +53,9 @@ */ public class LogHelperAgent extends Agent { + private final Codec codec = new SLCodec(); private String logManagerClass = JavaLoggingLogManagerImpl.JAVA_LOGGING_LOG_MANAGER_CLASS; //default logManagerClass if not specified. private Logger logger; - private final Codec codec = new SLCodec(); private LogManager logManager = null; private AMSSubscriber myAMSSubscriber = null; @@ -85,6 +85,21 @@ protected void takeDown() { } } + private void amsSubscribe(final AID owner) { + myAMSSubscriber = new AMSSubscriber() { + protected void installHandlers(Map handlersTable) { + handlersTable.put(IntrospectionVocabulary.DEADAGENT, (EventHandler) ev -> { + DeadAgent da = (DeadAgent) ev; + if (da.getAgent().equals(owner)) { + // My Owner is dead --> suicide + doDelete(); + } + }); + } + }; + + addBehaviour(myAMSSubscriber); + } /** * Inner class LogHelperAgentBehaviour @@ -165,21 +180,4 @@ private void handleSetLevel(SetLevel action, Action actExpr, ACLMessage reply) t reply.setPerformative(ACLMessage.INFORM); } } // END of inner class LogHelperAgentBehaviour - - - private void amsSubscribe(final AID owner) { - myAMSSubscriber = new AMSSubscriber() { - protected void installHandlers(Map handlersTable) { - handlersTable.put(IntrospectionVocabulary.DEADAGENT, (EventHandler) ev -> { - DeadAgent da = (DeadAgent) ev; - if (da.getAgent().equals(owner)) { - // My Owner is dead --> suicide - doDelete(); - } - }); - } - }; - - addBehaviour(myAMSSubscriber); - } } diff --git a/src/jade/tools/logging/gui/ContainerLogWindow.java b/src/jade/tools/logging/gui/ContainerLogWindow.java index 1273dcd..ac3c968 100644 --- a/src/jade/tools/logging/gui/ContainerLogWindow.java +++ b/src/jade/tools/logging/gui/ContainerLogWindow.java @@ -65,13 +65,11 @@ public class ContainerLogWindow extends JInternalFrame implements InternalFrameL private final String containerName; private final AID controller; private final LogManagerGUI mainGui; - - private LogManager myLogManager; private final LogTable myTable; private final JComboBox levelCombo; private final JTextField loggingSystemTF; - private final AbstractAction setLoggingSystemAction = new SetLoggingSystemAction(this); + private LogManager myLogManager; public ContainerLogWindow(Agent a, String containerName, AID controller, LogManager logManager, LogManagerGUI gui) throws FIPAException { super(containerName); @@ -118,7 +116,7 @@ public ContainerLogWindow(Agent a, String containerName, AID controller, LogMana getContentPane().add(new JScrollPane(table), BorderLayout.CENTER); //Allows the modification to the value in the cell - levelCombo = new JComboBox(); + levelCombo = new JComboBox<>(); List levels = myLogManager.getLogLevels(); for (LevelInfo level : levels) { levelCombo.addItem(level.getName()); @@ -147,8 +145,8 @@ private List retrieveLogInfo() throws FIPAException { } // Now sort log info in alphabetical order List infos = new ArrayList<>(tmp.size()); - for (Object o : tmp) { - LoggerInfo li = (LoggerInfo) o; + for (LoggerInfo o : tmp) { + LoggerInfo li = o; String name = li.toString(); int i = 0; while (i < infos.size() && name.compareTo(infos.get(i).toString()) >= 0) { @@ -221,92 +219,6 @@ private int getLevelValue(String name) { return 0; } - /** - * Inner class LogTable - */ - private class LogTable extends AbstractTableModel { - private List logInfos; - - public LogTable(List infos) { - logInfos = infos; - } - - public void refresh(List infos) { - logInfos = infos; - validate(); - } - - public int getRowCount() { - return logInfos.size(); - } - - public int getColumnCount() { - return 4; - } - - - // Level and file cells are editables - public boolean isCellEditable(int row, int column) { - return column == LEVEL_COLUMN || column == FILE_COLUMN; - } - - public Object getValueAt(int row, int column) { - LoggerInfo info = logInfos.get(row); - switch (column) { - case NAME_COLUMN: - return info.getName(); - case LEVEL_COLUMN: - return getLevelName(info.getLevel()); - case HANDLERS_COLUMN: - StringBuffer sb = new StringBuffer(); - List l = info.getHandlers(); - if (l != null) { - Iterator it = l.iterator(); - while (it.hasNext()) { - sb.append(it.next()); - if (it.hasNext()) { - sb.append(", "); - } - } - } - return sb.toString(); - case FILE_COLUMN: - return info.getFile(); - } - return null; - } - - public void setValueAt(Object value, int row, int column) { - LoggerInfo info = logInfos.get(row); - try { - if (column == LEVEL_COLUMN) { - int level = getLevelValue((String) value); - setLogLevel(info.getName(), level); - info.setLevel(level); - } else if (column == FILE_COLUMN) { - setLogFile(info.getName(), (String) value); - info.setFile((String) value); - } - } catch (FIPAException fe) { - int res = JOptionPane.showConfirmDialog(mainGui, "Cannot set " + getColumnName(column) + " to logger " + info.getName() + " in container " + containerName + "\nWould you like to see the message?", "WARNING", JOptionPane.YES_NO_OPTION); - if (res == JOptionPane.YES_OPTION) { - AclGui.showMsgInDialog(fe.getACLMessage(), mainGui); - } - } - } - - public String getColumnName(int column) { - return switch (column) { - case NAME_COLUMN -> "Logger Name"; - case LEVEL_COLUMN -> "Level"; - case HANDLERS_COLUMN -> "Handlers"; - case FILE_COLUMN -> "Log file"; - default -> null; - }; - } - } // END of inner class LogTable - - /////////////////////////////////// // Action handling methods /////////////////////////////////// @@ -330,7 +242,6 @@ void setLoggingSystem() { } } - //////////////////////////////////////////// // Private utility methods //////////////////////////////////////////// @@ -418,5 +329,90 @@ private void remoteSetLogFile(AID helper, String name, String file) throws FIPAE throw new FIPAException(e.getMessage()); } } + + /** + * Inner class LogTable + */ + private class LogTable extends AbstractTableModel { + private List logInfos; + + public LogTable(List infos) { + logInfos = infos; + } + + public void refresh(List infos) { + logInfos = infos; + validate(); + } + + public int getRowCount() { + return logInfos.size(); + } + + public int getColumnCount() { + return 4; + } + + + // Level and file cells are editables + public boolean isCellEditable(int row, int column) { + return column == LEVEL_COLUMN || column == FILE_COLUMN; + } + + public Object getValueAt(int row, int column) { + LoggerInfo info = logInfos.get(row); + switch (column) { + case NAME_COLUMN: + return info.getName(); + case LEVEL_COLUMN: + return getLevelName(info.getLevel()); + case HANDLERS_COLUMN: + StringBuilder sb = new StringBuilder(); + List l = info.getHandlers(); + if (l != null) { + Iterator it = l.iterator(); + while (it.hasNext()) { + sb.append(it.next()); + if (it.hasNext()) { + sb.append(", "); + } + } + } + return sb.toString(); + case FILE_COLUMN: + return info.getFile(); + } + return null; + } + + public void setValueAt(Object value, int row, int column) { + LoggerInfo info = logInfos.get(row); + try { + if (column == LEVEL_COLUMN) { + int level = getLevelValue((String) value); + setLogLevel(info.getName(), level); + info.setLevel(level); + } else if (column == FILE_COLUMN) { + setLogFile(info.getName(), (String) value); + info.setFile((String) value); + } + } catch (FIPAException fe) { + int res = JOptionPane.showConfirmDialog(mainGui, "Cannot set " + getColumnName(column) + " to logger " + info.getName() + " in container " + containerName + "\nWould you like to see the message?", "WARNING", JOptionPane.YES_NO_OPTION); + if (res == JOptionPane.YES_OPTION) { + AclGui.showMsgInDialog(fe.getACLMessage(), mainGui); + } + } + } + + public String getColumnName(int column) { + return switch (column) { + case NAME_COLUMN -> "Logger Name"; + case LEVEL_COLUMN -> "Level"; + case HANDLERS_COLUMN -> "Handlers"; + case FILE_COLUMN -> "Log file"; + default -> null; + }; + } + } // END of inner class LogTable } diff --git a/src/jade/tools/logging/gui/LogManagerGUI.java b/src/jade/tools/logging/gui/LogManagerGUI.java index c4d5f2a..f855ee1 100644 --- a/src/jade/tools/logging/gui/LogManagerGUI.java +++ b/src/jade/tools/logging/gui/LogManagerGUI.java @@ -193,7 +193,7 @@ public void refreshLocalPlatformName(final String name) { ///////////////////////////////////////////////////// void startManagingLog() { AgentTree.Node node = agentTree.getSelectedNode(); - if (node != null && node instanceof AgentTree.ContainerNode) { + if (node instanceof AgentTree.ContainerNode) { String containerName = node.getName(); System.out.println("Container name = " + containerName); ContainerLogWindow window = managedContainers.get(containerName); @@ -231,7 +231,7 @@ void startManagingLog() { void stopManagingLog() { AgentTree.Node node = agentTree.getSelectedNode(); - if (node != null && node instanceof AgentTree.ContainerNode) { + if (node instanceof AgentTree.ContainerNode) { String containerName = node.getName(); final ContainerLogWindow window = managedContainers.remove(containerName); if (window != null) { diff --git a/src/jade/tools/logging/ontology/GetAllLoggers.java b/src/jade/tools/logging/ontology/GetAllLoggers.java index 2b20cc5..58b35d9 100644 --- a/src/jade/tools/logging/ontology/GetAllLoggers.java +++ b/src/jade/tools/logging/ontology/GetAllLoggers.java @@ -16,19 +16,19 @@ public GetAllLoggers(String type, String filter) { this.filter = filter; } - public void setType(String type) { - this.type = type; - } - public String getType() { return type; } - public void setFilter(String filter) { - this.filter = filter; + public void setType(String type) { + this.type = type; } public String getFilter() { return filter; } + + public void setFilter(String filter) { + this.filter = filter; + } } diff --git a/src/jade/tools/logging/ontology/LogManagementOntology.java b/src/jade/tools/logging/ontology/LogManagementOntology.java index f26d01f..78c2427 100644 --- a/src/jade/tools/logging/ontology/LogManagementOntology.java +++ b/src/jade/tools/logging/ontology/LogManagementOntology.java @@ -45,17 +45,6 @@ public class LogManagementOntology extends Ontology implements LogManagementVoca // The singleton instance of this ontology private static final Ontology theInstance = new LogManagementOntology(); - /** - * This method returns the unique instance (according to the singleton - * pattern) of the Log-Management-ontology. - * - * @return The singleton Ontology object, containing the - * schemas for the elements of the Log-Management-ontology. - */ - public static Ontology getInstance() { - return theInstance; - } - private LogManagementOntology() { super(NAME, ExceptionOntology.getInstance(), new ReflectiveIntrospector()); @@ -92,4 +81,15 @@ private LogManagementOntology() { oe.printStackTrace(); } } + + /** + * This method returns the unique instance (according to the singleton + * pattern) of the Log-Management-ontology. + * + * @return The singleton Ontology object, containing the + * schemas for the elements of the Log-Management-ontology. + */ + public static Ontology getInstance() { + return theInstance; + } } diff --git a/src/jade/tools/logging/ontology/LoggerInfo.java b/src/jade/tools/logging/ontology/LoggerInfo.java index 50af22a..69fb49d 100644 --- a/src/jade/tools/logging/ontology/LoggerInfo.java +++ b/src/jade/tools/logging/ontology/LoggerInfo.java @@ -19,38 +19,38 @@ public LoggerInfo(String name, int level) { setLevel(level); } - public void setName(String name) { - this.name = name; - } - public String getName() { return name; } - public void setLevel(int level) { - this.level = level; + public void setName(String name) { + this.name = name; } public int getLevel() { return level; } - public void setHandlers(List handlers) { - this.handlers = handlers; + public void setLevel(int level) { + this.level = level; } public List getHandlers() { return handlers; } - public void setFile(String file) { - this.file = file; + public void setHandlers(List handlers) { + this.handlers = handlers; } public String getFile() { return file; } + public void setFile(String file) { + this.file = file; + } + public String toString() { return name; } diff --git a/src/jade/tools/logging/ontology/SetFile.java b/src/jade/tools/logging/ontology/SetFile.java index 66ae87e..10b7493 100644 --- a/src/jade/tools/logging/ontology/SetFile.java +++ b/src/jade/tools/logging/ontology/SetFile.java @@ -20,14 +20,14 @@ public SetFile(String file) { setFile(file); } - public void setFile(String file) { - this.file = file; - } - public String getFile() { return file; } + public void setFile(String file) { + this.file = file; + } + public String getLogger() { return logger; } diff --git a/src/jade/tools/logging/ontology/SetLevel.java b/src/jade/tools/logging/ontology/SetLevel.java index 67afff8..ef937cc 100644 --- a/src/jade/tools/logging/ontology/SetLevel.java +++ b/src/jade/tools/logging/ontology/SetLevel.java @@ -16,14 +16,14 @@ public SetLevel(String logger, int level) { this.level = level; } - public void setLevel(int level) { - this.level = level; - } - public int getLevel() { return level; } + public void setLevel(int level) { + this.level = level; + } + public String getLogger() { return logger; } diff --git a/src/jade/tools/rma/ActionProcessor.java b/src/jade/tools/rma/ActionProcessor.java index 395aa61..3ca2b2e 100644 --- a/src/jade/tools/rma/ActionProcessor.java +++ b/src/jade/tools/rma/ActionProcessor.java @@ -36,9 +36,6 @@ */ class ActionProcessor { - private final MainPanel panel; - private RMAAction action; - public static final String START_ACTION = "Start new Agent"; public static final String MANAGE_MTPS_ACTION = "Manage Installed MTPs"; public static final String INSTALL_MTP_ACTION = "Install a new MTP"; @@ -71,8 +68,9 @@ class ActionProcessor { public static final String REMOVEREMOTEAMS_ACTION = "Remove Remote Platform"; public static final String REFRESHAMSAGENT_ACTION = "Refresh Agent List"; public static final String REGISTERREMOTEAGENTWITHAMS_ACTION = "Register Remote Agent with local AMS"; - public static final Map actions = new HashMap<>(); + private final MainPanel panel; + private RMAAction action; public ActionProcessor(rma anRma, MainWindow mWnd, MainPanel panel) { this.panel = panel; diff --git a/src/jade/tools/rma/DummyAgentAction.java b/src/jade/tools/rma/DummyAgentAction.java index 21d15c4..5a3865f 100644 --- a/src/jade/tools/rma/DummyAgentAction.java +++ b/src/jade/tools/rma/DummyAgentAction.java @@ -33,13 +33,12 @@ class DummyAgentAction extends ContainerAction { + private final rma myRMA; /** * Progressive Number to give always a new name to DummyAgent */ private int progressiveNumber = 0; - private final rma myRMA; - public DummyAgentAction(rma anRMA, ActionProcessor actPro) { super("DummyAgentActionIcon", "Start DummyAgent", actPro); progressiveNumber = 0; diff --git a/src/jade/tools/rma/InstallMTPDialog.java b/src/jade/tools/rma/InstallMTPDialog.java index ff19906..fec51ab 100644 --- a/src/jade/tools/rma/InstallMTPDialog.java +++ b/src/jade/tools/rma/InstallMTPDialog.java @@ -33,6 +33,19 @@ */ class InstallMTPDialog extends JDialog { + // Variables declaration - do not modify//GEN-BEGIN:variables + private JPanel topPanel; + private JLabel containerLabel; + private DefaultComboBoxModel containerList; + private JComboBox containerChoice; + private JLabel classLabel; + private JTextField classField; + private JLabel addressLabel; + private JTextField addressField; + private JPanel bottomPanel; + private JButton buttonOK; + private JButton buttonCancel; + private boolean confirmed = false; /** * Creates new form InstallMTPDialog */ @@ -192,26 +205,11 @@ private void closeDialog(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_clos confirmed = false; destroy(); }//GEN-LAST:event_closeDialog + // End of variables declaration//GEN-END:variables private void destroy() { setVisible(false); dispose(); } - // Variables declaration - do not modify//GEN-BEGIN:variables - private JPanel topPanel; - private JLabel containerLabel; - private DefaultComboBoxModel containerList; - private JComboBox containerChoice; - private JLabel classLabel; - private JTextField classField; - private JLabel addressLabel; - private JTextField addressField; - private JPanel bottomPanel; - private JButton buttonOK; - private JButton buttonCancel; - // End of variables declaration//GEN-END:variables - - private boolean confirmed = false; - } diff --git a/src/jade/tools/rma/IntrospectorAction.java b/src/jade/tools/rma/IntrospectorAction.java index 75027c0..daa632e 100644 --- a/src/jade/tools/rma/IntrospectorAction.java +++ b/src/jade/tools/rma/IntrospectorAction.java @@ -35,13 +35,12 @@ class IntrospectorAction extends ContainerAction { + private final rma myRMA; /** * Progressive Number to give always a new name to IntrospectoAgent */ private int progressiveNumber = 0; - private final rma myRMA; - public IntrospectorAction(rma anRMA, ActionProcessor actPro) { super("IntrospectorActionIcon", "Start IntrospectorAgent", actPro); progressiveNumber = 0; diff --git a/src/jade/tools/rma/LogManagerAgentAction.java b/src/jade/tools/rma/LogManagerAgentAction.java index 55f522c..2a66fbe 100644 --- a/src/jade/tools/rma/LogManagerAgentAction.java +++ b/src/jade/tools/rma/LogManagerAgentAction.java @@ -31,13 +31,12 @@ class LogManagerAgentAction extends ContainerAction { + private final rma myRMA; /** * Progressive Number to give always a new name to DummyAgent */ private int progressiveNumber = 0; - private final rma myRMA; - public LogManagerAgentAction(rma anRMA, ActionProcessor actPro) { super("LoggerAgentActionIcon", "Start LogManagerAgent", actPro); progressiveNumber = 0; diff --git a/src/jade/tools/rma/MainMenu.java b/src/jade/tools/rma/MainMenu.java index 26f5491..3bf91a6 100644 --- a/src/jade/tools/rma/MainMenu.java +++ b/src/jade/tools/rma/MainMenu.java @@ -41,12 +41,6 @@ class MainMenu extends JMenuBar { private JMenuItem tmp; - void paintM(boolean enable, RMAAction obj) { - tmp = menu.add(obj); - tmp.setEnabled(enable); - } - - public MainMenu(Frame mainWnd, ActionProcessor actPro) { super(); @@ -105,4 +99,9 @@ public MainMenu(Frame mainWnd, ActionProcessor actPro) { // builds the popupmenu } // End Builder + + void paintM(boolean enable, RMAAction obj) { + tmp = menu.add(obj); + tmp.setEnabled(enable); + } } diff --git a/src/jade/tools/rma/MainPanel.java b/src/jade/tools/rma/MainPanel.java index 0eab342..c8dc533 100644 --- a/src/jade/tools/rma/MainPanel.java +++ b/src/jade/tools/rma/MainPanel.java @@ -53,19 +53,18 @@ */ class MainPanel extends JPanel implements DropTargetListener, TreeSelectionListener { - private APDescriptionPanel APDescription_panel; + //logging + private static final Logger logger = Logger.getMyLogger(MainPanel.class.getName()); private final AgentTree treeAgent; // FIXME: It should be private private final TablePanel table; - private JScrollPane scroll; private final JSplitPane pan; - private JSplitPane pane; private final MainWindow mainWnd; + private APDescriptionPanel APDescription_panel; + private JScrollPane scroll; + private JSplitPane pane; private PopupMouser popM; private rma myRma = null; - //logging - private static final Logger logger = Logger.getMyLogger(MainPanel.class.getName()); - public MainPanel(rma anRMA, MainWindow mainWnd) { @@ -180,26 +179,6 @@ public void drop(DropTargetDropEvent dropEvent) { } //~ for(int i=0;i { - List addrs = addresses.get(where); - if (addrs == null) { - addrs = new LinkedList<>(); - addresses.put(where, addrs); - } + List addrs = addresses.computeIfAbsent(where, k -> new LinkedList<>()); addrs.add(address); manageDlg.setData(containerNames, addresses); }; diff --git a/src/jade/tools/rma/ManageMTPsDialog.java b/src/jade/tools/rma/ManageMTPsDialog.java index 6181d14..6921c31 100644 --- a/src/jade/tools/rma/ManageMTPsDialog.java +++ b/src/jade/tools/rma/ManageMTPsDialog.java @@ -19,8 +19,12 @@ public class ManageMTPsDialog extends JDialog { private static final Object[] EMPTY_LIST = new Object[0]; - - + private final rma myRMA; + private final Frame owner; + private Map> data; + // Variables declaration - do not modify//GEN-BEGIN:variables + private JPanel lists; + private JList containers; private final AbstractAction addMTPAction = new AbstractAction("Add MTP...") { public void actionPerformed(ActionEvent ev) { @@ -28,7 +32,7 @@ public void actionPerformed(ActionEvent ev) { myRMA.installMTP(name); } }; - + private JList addresses; private final AbstractAction removeMTPAction = new AbstractAction("Remove MTP") { public void actionPerformed(ActionEvent ev) { @@ -41,8 +45,10 @@ public void actionPerformed(ActionEvent ev) { } }; - - + private JPanel buttons; + private JButton addMTP; + private JButton removeMTP; + private JButton closeDlg; /** * Creates new form ManageMTPsDialog */ @@ -194,20 +200,6 @@ private void closeDialog(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_clos setVisible(false); dispose(); }//GEN-LAST:event_closeDialog - - - private final rma myRMA; - private final Frame owner; - private Map> data; - - // Variables declaration - do not modify//GEN-BEGIN:variables - private JPanel lists; - private JList containers; - private JList addresses; - private JPanel buttons; - private JButton addMTP; - private JButton removeMTP; - private JButton closeDlg; // End of variables declaration//GEN-END:variables } diff --git a/src/jade/tools/rma/MoveDialog.java b/src/jade/tools/rma/MoveDialog.java index e48c4d0..b056195 100644 --- a/src/jade/tools/rma/MoveDialog.java +++ b/src/jade/tools/rma/MoveDialog.java @@ -127,18 +127,6 @@ protected MoveDialog(String agentNameP, Frame frame) { setVisible(true); } - public Dimension getPreferredSize() { - return (new Dimension(450, 170)); - } - - public void actionPerformed(ActionEvent evt) { - choice = CANCEL_BUTTON; - if (evt.getSource() == OKButton) { - choice = OK_BUTTON; - } - dispose(); - } - public static int showMoveDialog(String agent, Frame owner, boolean editable) { choice = CANCEL_BUTTON; agentName.setEditable(editable); @@ -152,17 +140,28 @@ public static String getAgentName() { return agentName.getText(); } + public static void setAgentName(String agentNameP) { + agentName.setText(agentNameP); + } public static String getContainer() { return container.getText(); } - public static void setAgentName(String agentNameP) { - agentName.setText(agentNameP); - } - public static void setContainer(String containerP) { container.setText(containerP); } + public Dimension getPreferredSize() { + return (new Dimension(450, 170)); + } + + public void actionPerformed(ActionEvent evt) { + choice = CANCEL_BUTTON; + if (evt.getSource() == OKButton) { + choice = OK_BUTTON; + } + dispose(); + } + } \ No newline at end of file diff --git a/src/jade/tools/rma/StartDialog.java b/src/jade/tools/rma/StartDialog.java index f25a0f7..d668e6c 100644 --- a/src/jade/tools/rma/StartDialog.java +++ b/src/jade/tools/rma/StartDialog.java @@ -45,6 +45,15 @@ public class StartDialog extends JDialog implements ActionListener { + public final static int OK_BUTTON = 0; + public final static int CANCEL_BUTTON = 1; + private final static String ttAgentName = "Name of the Agent to start"; + private final static String ttClassname = "Class Name of the Agent to start"; + private final static String ttArguments = "Arguments passed to the agent constructor"; + private final static String ttOwner = "The user under which the agent has to be started"; + private final static String ttContainer = "Container on which the Agent will start"; + private final static String ttSelectClassname = "Search in classpath for classes extending Agent"; + private static final StartDialog dialog; protected static ExtTextField extTextFieldAgentName; protected static Panel panelClassname; protected static JButton jButtonSelectClassname; @@ -53,98 +62,17 @@ public class StartDialog extends JDialog implements ActionListener { protected static JTextField jTextFieldContainer; protected static JTextField jTextFieldArguments; protected static JTextField jTextFieldAgentUser; - protected static JLabel jLabelAgentName = new JLabel("Agent Name"); protected static JLabel jLabelClassname = new JLabel("Class Name"); protected static JLabel jLabelArguments = new JLabel("Arguments"); protected static JLabel jLabelOwner = new JLabel("Owner"); protected static JLabel jLabelContainer = new JLabel("Container"); - protected static JButton jButtonOk = new JButton("OK"); protected static JButton jButtonCancel = new JButton("Cancel"); - - private final static String ttAgentName = "Name of the Agent to start"; - private final static String ttClassname = "Class Name of the Agent to start"; - private final static String ttArguments = "Arguments passed to the agent constructor"; - private final static String ttOwner = "The user under which the agent has to be started"; - private final static String ttContainer = "Container on which the Agent will start"; - private final static String ttSelectClassname = "Search in classpath for classes extending Agent"; - - public final static int OK_BUTTON = 0; - public final static int CANCEL_BUTTON = 1; - - private static final StartDialog dialog; - private static int choice = CANCEL_BUTTON; private static String classname; private static String agentname; - private ClassSelectionDialog csd; - - private static class AgentClassFilter implements ClassFinderFilter { - private final static String[] excluded = new String[]{ - "jade.domain.ams", - "jade.tools.ToolNotifier", - "jade.tools.logging.LogHelperAgent" - }; - - // Exclude all classes that are - // - Not concrete (abstract or interfaces) - // - Contained in the jade.core package (a part from the jade.core.Agent class itself) - // - Explicitly mentioned in the "exclude" array - public boolean include(Class superClazz, Class clazz) { - String clazzName = clazz.getName(); - int modifiers = clazz.getModifiers(); - boolean doInclude = ((modifiers & (ClassSelectionDialog.ACC_ABSTRACT | ClassSelectionDialog.ACC_INTERFACE)) == 0); - if (doInclude) { - if (clazzName.startsWith("jade.core")) { - doInclude = Agent.class.getName().equals(clazzName); - } - } - if (doInclude) { - for (int i = 0; i < excluded.length; i++) { - if (excluded[i].equals(clazzName)) { - doInclude = false; - break; - } - } - } - return doInclude; - } - } - - private static class ExtTextField extends JTextField implements ActionListener, DocumentListener { - - private StartDialog startDialog; - - public ExtTextField() { - super(0); - addActionListener(this); - Document doc = this.getDocument(); - doc.addDocumentListener(this); - } - - public void setStartDialog(StartDialog startDialog) { - this.startDialog = startDialog; - } - - public void actionPerformed(ActionEvent e) { - // nothing to do - } - - public void insertUpdate(DocumentEvent e) { - startDialog.updateOkButtonEnabled(); - } - - public void removeUpdate(DocumentEvent e) { - startDialog.updateOkButtonEnabled(); - } - - public void changedUpdate(DocumentEvent e) { - // nothing to do - } - } - static { classname = ""; agentname = ""; @@ -214,6 +142,8 @@ public void changedUpdate(DocumentEvent e) { dialog = new StartDialog(); } + private ClassSelectionDialog csd; + protected StartDialog() { super((Frame) null, "Insert Start Parameters", true); @@ -245,6 +175,50 @@ protected StartDialog() { getContentPane().add(jButtonCancel); } + public static int showStartNewDialog(String containerName, Frame owner) { + choice = CANCEL_BUTTON; + + extTextFieldAgentName.setEditable(true); + jTextFieldContainer.setEditable(false); + + setContainer(containerName); + dialog.doShow(""); + + return choice; + } + + public static String getAgentName() { + return agentname; + } + + public static void setAgentName(String agentNameP) { + extTextFieldAgentName.setText(agentNameP); + } + + public static String getClassName() { + return classname; + } + + public static void setClassName(String classNameP) { + jComboBoxClassnameCombo.setSelectedItem(classNameP); + } + + public static String getArguments() { + return jTextFieldArguments.getText().trim(); + } + + public static String getAgentUser() { + return jTextFieldAgentUser.getText().trim(); + } + + public static String getContainer() { + return jTextFieldContainer.getText(); + } + + public static void setContainer(String containerP) { + jTextFieldContainer.setText(containerP); + } + public void doShow(String agentNameP) { extTextFieldAgentName.setText(agentNameP); jComboBoxClassnameCombo.setSelectedItem(classname); @@ -306,48 +280,68 @@ public void actionPerformed(ActionEvent evt) { } } - public static int showStartNewDialog(String containerName, Frame owner) { - choice = CANCEL_BUTTON; - - extTextFieldAgentName.setEditable(true); - jTextFieldContainer.setEditable(false); - - setContainer(containerName); - dialog.doShow(""); + private static class AgentClassFilter implements ClassFinderFilter { + private final static String[] excluded = new String[]{ + "jade.domain.ams", + "jade.tools.ToolNotifier", + "jade.tools.logging.LogHelperAgent" + }; - return choice; + // Exclude all classes that are + // - Not concrete (abstract or interfaces) + // - Contained in the jade.core package (a part from the jade.core.Agent class itself) + // - Explicitly mentioned in the "exclude" array + public boolean include(Class superClazz, Class clazz) { + String clazzName = clazz.getName(); + int modifiers = clazz.getModifiers(); + boolean doInclude = ((modifiers & (ClassSelectionDialog.ACC_ABSTRACT | ClassSelectionDialog.ACC_INTERFACE)) == 0); + if (doInclude) { + if (clazzName.startsWith("jade.core")) { + doInclude = Agent.class.getName().equals(clazzName); + } + } + if (doInclude) { + for (String s : excluded) { + if (s.equals(clazzName)) { + doInclude = false; + break; + } + } + } + return doInclude; + } } - public static String getAgentName() { - return agentname; - } + private static class ExtTextField extends JTextField implements ActionListener, DocumentListener { - public static String getClassName() { - return classname; - } + private StartDialog startDialog; - public static String getArguments() { - return jTextFieldArguments.getText().trim(); - } + public ExtTextField() { + super(0); + addActionListener(this); + Document doc = this.getDocument(); + doc.addDocumentListener(this); + } - public static String getAgentUser() { - return jTextFieldAgentUser.getText().trim(); - } + public void setStartDialog(StartDialog startDialog) { + this.startDialog = startDialog; + } - public static String getContainer() { - return jTextFieldContainer.getText(); - } + public void actionPerformed(ActionEvent e) { + // nothing to do + } - public static void setAgentName(String agentNameP) { - extTextFieldAgentName.setText(agentNameP); - } + public void insertUpdate(DocumentEvent e) { + startDialog.updateOkButtonEnabled(); + } - public static void setClassName(String classNameP) { - jComboBoxClassnameCombo.setSelectedItem(classNameP); - } + public void removeUpdate(DocumentEvent e) { + startDialog.updateOkButtonEnabled(); + } - public static void setContainer(String containerP) { - jTextFieldContainer.setText(containerP); + public void changedUpdate(DocumentEvent e) { + // nothing to do + } } } diff --git a/src/jade/tools/rma/TablePanel.java b/src/jade/tools/rma/TablePanel.java index 140453e..497fd27 100644 --- a/src/jade/tools/rma/TablePanel.java +++ b/src/jade/tools/rma/TablePanel.java @@ -43,23 +43,21 @@ class TablePanel extends JPanel { + /** + * @clientCardinality + **/ + final String[] names = {"name", "addresses", "state", "owner"}; JTable tableView; JScrollPane scrollpane; JScrollPane tableAggregate; Dimension origin = new Dimension(0, 0); - JComponent selectionModeButtons; JComponent resizeModeButtons; - JPanel mainPanel; JPanel controlPanel; - TableModel dataModel; // final - /** - * @clientCardinality - **/ - final String[] names = {"name", "addresses", "state", "owner"}; + TableModel dataModel; // Create the dummy data (a few rows of names) /** * @clientCardinality diff --git a/src/jade/tools/rma/rma.java b/src/jade/tools/rma/rma.java index 2a5d5e7..e736a75 100644 --- a/src/jade/tools/rma/rma.java +++ b/src/jade/tools/rma/rma.java @@ -69,232 +69,11 @@ */ public class rma extends ToolAgent { - private APDescription myPlatformProfile; - - // Sends requests to the AMS - private class AMSClientBehaviour extends SimpleAchieveREInitiator { - - private final String actionName; - - - public AMSClientBehaviour(String an, ACLMessage request) { - super(rma.this, request); - actionName = an; - } - - - protected void handleNotUnderstood(ACLMessage reply) { - myGUI.showErrorDialog("NOT-UNDERSTOOD received by RMA during " + actionName, reply); - } - - protected void handleRefuse(ACLMessage reply) { - myGUI.showErrorDialog("REFUSE received during " + actionName, reply); - } - - protected void handleAgree(ACLMessage reply) { - if (logger.isLoggable(Logger.FINE)) - logger.log(Logger.FINE, "AGREE received" + reply); - } - - protected void handleFailure(ACLMessage reply) { - myGUI.showErrorDialog("FAILURE received during " + actionName, reply); - } - - protected void handleInform(ACLMessage reply) { - if (logger.isLoggable(Logger.FINE)) - logger.log(Logger.FINE, "INFORM received" + reply); - } - - } // End of AMSClientBehaviour class - - - private class handleAddRemotePlatformBehaviour extends AMSClientBehaviour { - - public handleAddRemotePlatformBehaviour(String an, ACLMessage request) { - super(an, request); - - } - - protected void handleInform(ACLMessage msg) { - if (logger.isLoggable(Logger.FINE)) - logger.log(Logger.FINE, "arrived a new APDescription"); - try { - AID sender = msg.getSender(); - Result r = (Result) getContentManager().extractContent(msg); - Iterator i = r.getItems().iterator(); - Object APDesc = i.next(); - if (APDesc != null) { - myGUI.addRemotePlatformFolder(); - myGUI.addRemotePlatform(sender, (APDescription) APDesc); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - }//end handleAddRemotePlatformBehaviour - - private class handleRefreshRemoteAgentBehaviour extends AMSClientBehaviour { - - private final APDescription platform; - - public handleRefreshRemoteAgentBehaviour(String an, ACLMessage request, APDescription ap) { - super(an, request); - platform = ap; - - } - - protected void handleInform(ACLMessage msg) { - if (logger.isLoggable(Logger.FINE)) - logger.log(Logger.FINE, "arrived a new agents from a remote platform"); - try { - AID sender = msg.getSender(); - Result r = (Result) getContentManager().extractContent(msg); - Iterator i = r.getItems().iterator(); - myGUI.refreshRemoteAgentsInRemotePlatform(platform, i); - } catch (Exception e) { - e.printStackTrace(); - } - } - - }//end handleAddRemotePlatformBehaviour - - private final SequentialBehaviour AMSSubscribe = new SequentialBehaviour(); - + private APDescription myPlatformProfile; private transient MainWindow myGUI; - private String myContainerName; - class RMAAMSListenerBehaviour extends AMSListenerBehaviour { - protected void installHandlers(Map handlersTable) { - - // Fill the event handler table. - - handlersTable.put(IntrospectionVocabulary.META_RESETEVENTS, (EventHandler) ev -> { - ResetEvents re = (ResetEvents) ev; - myGUI.resetTree(); - }); - - handlersTable.put(IntrospectionVocabulary.ADDEDCONTAINER, (EventHandler) ev -> { - AddedContainer ac = (AddedContainer) ev; - ContainerID cid = ac.getContainer(); - String name = cid.getName(); - String address = cid.getAddress(); - try { - InetAddress addr = InetAddress.getByName(address); - myGUI.addContainer(name, addr); - } catch (UnknownHostException uhe) { - myGUI.addContainer(name, null); - } - }); - - - handlersTable.put(IntrospectionVocabulary.REMOVEDCONTAINER, (EventHandler) ev -> { - RemovedContainer rc = (RemovedContainer) ev; - ContainerID cid = rc.getContainer(); - String name = cid.getName(); - myGUI.removeContainer(name); - }); - - handlersTable.put(IntrospectionVocabulary.BORNAGENT, (EventHandler) ev -> { - BornAgent ba = (BornAgent) ev; - ContainerID cid = ba.getWhere(); - // ContainerID is null in case of foreign agents registered with the local AMS or virtual agents - // FIXME: Such agents should be shown somewhere - if (cid != null) { - String container = cid.getName(); - AID agent = ba.getAgent(); - myGUI.addAgent(container, agent, ba.getState(), ba.getOwnership()); - if (agent.equals(getAID())) - myContainerName = container; - } - }); - - handlersTable.put(IntrospectionVocabulary.DEADAGENT, (EventHandler) ev -> { - DeadAgent da = (DeadAgent) ev; - ContainerID cid = da.getWhere(); - // ContainerID is null in case of foreign agents registered with the local AMS or virtual agents - if (cid != null) { - String container = cid.getName(); - AID agent = da.getAgent(); - myGUI.removeAgent(container, agent); - } - }); - - handlersTable.put(IntrospectionVocabulary.SUSPENDEDAGENT, (EventHandler) ev -> { - SuspendedAgent sa = (SuspendedAgent) ev; - ContainerID cid = sa.getWhere(); - String container = cid.getName(); - AID agent = sa.getAgent(); - myGUI.modifyAgent(container, agent, AMSAgentDescription.SUSPENDED, null); - }); - - handlersTable.put(IntrospectionVocabulary.RESUMEDAGENT, (EventHandler) ev -> { - ResumedAgent ra = (ResumedAgent) ev; - ContainerID cid = ra.getWhere(); - String container = cid.getName(); - AID agent = ra.getAgent(); - myGUI.modifyAgent(container, agent, AMSAgentDescription.ACTIVE, null); - }); - - handlersTable.put(IntrospectionVocabulary.FROZENAGENT, (EventHandler) ev -> { - FrozenAgent fa = (FrozenAgent) ev; - String oldContainer = fa.getWhere().getName(); - String newContainer = fa.getBufferContainer().getName(); - AID agent = fa.getAgent(); - myGUI.modifyFrozenAgent(oldContainer, newContainer, agent); - }); - - handlersTable.put(IntrospectionVocabulary.THAWEDAGENT, (EventHandler) ev -> { - ThawedAgent ta = (ThawedAgent) ev; - String oldContainer = ta.getWhere().getName(); - String newContainer = ta.getBufferContainer().getName(); - AID agent = ta.getAgent(); - myGUI.modifyThawedAgent(oldContainer, newContainer, agent); - }); - - handlersTable.put(IntrospectionVocabulary.CHANGEDAGENTOWNERSHIP, (EventHandler) ev -> { - ChangedAgentOwnership cao = (ChangedAgentOwnership) ev; - ContainerID cid = cao.getWhere(); - String container = cid.getName(); - AID agent = cao.getAgent(); - myGUI.modifyAgent(container, agent, null, cao.getTo()); - }); - - handlersTable.put(IntrospectionVocabulary.MOVEDAGENT, (EventHandler) ev -> { - MovedAgent ma = (MovedAgent) ev; - AID agent = ma.getAgent(); - ContainerID from = ma.getFrom(); - ContainerID to = ma.getTo(); - myGUI.moveAgent(from.getName(), to.getName(), agent); - }); - - handlersTable.put(IntrospectionVocabulary.ADDEDMTP, (EventHandler) ev -> { - AddedMTP amtp = (AddedMTP) ev; - String address = amtp.getAddress(); - ContainerID where = amtp.getWhere(); - myGUI.addAddress(address, where.getName()); - }); - - handlersTable.put(IntrospectionVocabulary.REMOVEDMTP, (EventHandler) ev -> { - RemovedMTP rmtp = (RemovedMTP) ev; - String address = rmtp.getAddress(); - ContainerID where = rmtp.getWhere(); - myGUI.removeAddress(address, where.getName()); - }); - - //handle the APDescription provided by the AMS - handlersTable.put(IntrospectionVocabulary.PLATFORMDESCRIPTION, (EventHandler) ev -> { - PlatformDescription pd = (PlatformDescription) ev; - myPlatformProfile = pd.getPlatform(); - myGUI.refreshLocalPlatformName(myPlatformProfile.getName()); - }); - - } - } // END of inner class RMAAMSListenerBehaviour - - /** * This method starts the RMA behaviours to allow the agent * to carry on its duties within JADE agent platform. @@ -423,7 +202,6 @@ public void afterThaw() { send(getSubscribe()); } - /** * Callback method for platform management GUI. */ @@ -539,7 +317,6 @@ public void suspendAgent(AID name) { } } - /** * Callback method for platform management GUI. */ @@ -671,7 +448,6 @@ public void loadContainer(String name, String repository) { } } - /** * Callback method for platform management GUI. */ @@ -947,7 +723,6 @@ public void addRemotePlatform(AID remoteAMS) { } } - public void addRemotePlatformFromURL(String url) { try { @@ -1020,7 +795,6 @@ public void removeRemotePlatform(APDescription platform) { myGUI.removeRemotePlatform(platform.getName()); } - //make a search on a specified ams in order to return //all the agents registered with that ams. public void refreshRemoteAgent(APDescription platform, AID ams) { @@ -1077,4 +851,219 @@ public void registerRemoteAgentWithAMS(AMSAgentDescription amsd) { e.printStackTrace(); } } + + // Sends requests to the AMS + private class AMSClientBehaviour extends SimpleAchieveREInitiator { + + private final String actionName; + + + public AMSClientBehaviour(String an, ACLMessage request) { + super(rma.this, request); + actionName = an; + } + + + protected void handleNotUnderstood(ACLMessage reply) { + myGUI.showErrorDialog("NOT-UNDERSTOOD received by RMA during " + actionName, reply); + } + + protected void handleRefuse(ACLMessage reply) { + myGUI.showErrorDialog("REFUSE received during " + actionName, reply); + } + + protected void handleAgree(ACLMessage reply) { + if (logger.isLoggable(Logger.FINE)) + logger.log(Logger.FINE, "AGREE received" + reply); + } + + protected void handleFailure(ACLMessage reply) { + myGUI.showErrorDialog("FAILURE received during " + actionName, reply); + } + + protected void handleInform(ACLMessage reply) { + if (logger.isLoggable(Logger.FINE)) + logger.log(Logger.FINE, "INFORM received" + reply); + } + + } // End of AMSClientBehaviour class + + private class handleAddRemotePlatformBehaviour extends AMSClientBehaviour { + + public handleAddRemotePlatformBehaviour(String an, ACLMessage request) { + super(an, request); + + } + + protected void handleInform(ACLMessage msg) { + if (logger.isLoggable(Logger.FINE)) + logger.log(Logger.FINE, "arrived a new APDescription"); + try { + AID sender = msg.getSender(); + Result r = (Result) getContentManager().extractContent(msg); + Iterator i = r.getItems().iterator(); + Object APDesc = i.next(); + if (APDesc != null) { + myGUI.addRemotePlatformFolder(); + myGUI.addRemotePlatform(sender, (APDescription) APDesc); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + }//end handleAddRemotePlatformBehaviour + + private class handleRefreshRemoteAgentBehaviour extends AMSClientBehaviour { + + private final APDescription platform; + + public handleRefreshRemoteAgentBehaviour(String an, ACLMessage request, APDescription ap) { + super(an, request); + platform = ap; + + } + + protected void handleInform(ACLMessage msg) { + if (logger.isLoggable(Logger.FINE)) + logger.log(Logger.FINE, "arrived a new agents from a remote platform"); + try { + AID sender = msg.getSender(); + Result r = (Result) getContentManager().extractContent(msg); + Iterator i = r.getItems().iterator(); + myGUI.refreshRemoteAgentsInRemotePlatform(platform, i); + } catch (Exception e) { + e.printStackTrace(); + } + } + + }//end handleAddRemotePlatformBehaviour + + class RMAAMSListenerBehaviour extends AMSListenerBehaviour { + protected void installHandlers(Map handlersTable) { + + // Fill the event handler table. + + handlersTable.put(IntrospectionVocabulary.META_RESETEVENTS, (EventHandler) ev -> { + ResetEvents re = (ResetEvents) ev; + myGUI.resetTree(); + }); + + handlersTable.put(IntrospectionVocabulary.ADDEDCONTAINER, (EventHandler) ev -> { + AddedContainer ac = (AddedContainer) ev; + ContainerID cid = ac.getContainer(); + String name = cid.getName(); + String address = cid.getAddress(); + try { + InetAddress addr = InetAddress.getByName(address); + myGUI.addContainer(name, addr); + } catch (UnknownHostException uhe) { + myGUI.addContainer(name, null); + } + }); + + + handlersTable.put(IntrospectionVocabulary.REMOVEDCONTAINER, (EventHandler) ev -> { + RemovedContainer rc = (RemovedContainer) ev; + ContainerID cid = rc.getContainer(); + String name = cid.getName(); + myGUI.removeContainer(name); + }); + + handlersTable.put(IntrospectionVocabulary.BORNAGENT, (EventHandler) ev -> { + BornAgent ba = (BornAgent) ev; + ContainerID cid = ba.getWhere(); + // ContainerID is null in case of foreign agents registered with the local AMS or virtual agents + // FIXME: Such agents should be shown somewhere + if (cid != null) { + String container = cid.getName(); + AID agent = ba.getAgent(); + myGUI.addAgent(container, agent, ba.getState(), ba.getOwnership()); + if (agent.equals(getAID())) + myContainerName = container; + } + }); + + handlersTable.put(IntrospectionVocabulary.DEADAGENT, (EventHandler) ev -> { + DeadAgent da = (DeadAgent) ev; + ContainerID cid = da.getWhere(); + // ContainerID is null in case of foreign agents registered with the local AMS or virtual agents + if (cid != null) { + String container = cid.getName(); + AID agent = da.getAgent(); + myGUI.removeAgent(container, agent); + } + }); + + handlersTable.put(IntrospectionVocabulary.SUSPENDEDAGENT, (EventHandler) ev -> { + SuspendedAgent sa = (SuspendedAgent) ev; + ContainerID cid = sa.getWhere(); + String container = cid.getName(); + AID agent = sa.getAgent(); + myGUI.modifyAgent(container, agent, AMSAgentDescription.SUSPENDED, null); + }); + + handlersTable.put(IntrospectionVocabulary.RESUMEDAGENT, (EventHandler) ev -> { + ResumedAgent ra = (ResumedAgent) ev; + ContainerID cid = ra.getWhere(); + String container = cid.getName(); + AID agent = ra.getAgent(); + myGUI.modifyAgent(container, agent, AMSAgentDescription.ACTIVE, null); + }); + + handlersTable.put(IntrospectionVocabulary.FROZENAGENT, (EventHandler) ev -> { + FrozenAgent fa = (FrozenAgent) ev; + String oldContainer = fa.getWhere().getName(); + String newContainer = fa.getBufferContainer().getName(); + AID agent = fa.getAgent(); + myGUI.modifyFrozenAgent(oldContainer, newContainer, agent); + }); + + handlersTable.put(IntrospectionVocabulary.THAWEDAGENT, (EventHandler) ev -> { + ThawedAgent ta = (ThawedAgent) ev; + String oldContainer = ta.getWhere().getName(); + String newContainer = ta.getBufferContainer().getName(); + AID agent = ta.getAgent(); + myGUI.modifyThawedAgent(oldContainer, newContainer, agent); + }); + + handlersTable.put(IntrospectionVocabulary.CHANGEDAGENTOWNERSHIP, (EventHandler) ev -> { + ChangedAgentOwnership cao = (ChangedAgentOwnership) ev; + ContainerID cid = cao.getWhere(); + String container = cid.getName(); + AID agent = cao.getAgent(); + myGUI.modifyAgent(container, agent, null, cao.getTo()); + }); + + handlersTable.put(IntrospectionVocabulary.MOVEDAGENT, (EventHandler) ev -> { + MovedAgent ma = (MovedAgent) ev; + AID agent = ma.getAgent(); + ContainerID from = ma.getFrom(); + ContainerID to = ma.getTo(); + myGUI.moveAgent(from.getName(), to.getName(), agent); + }); + + handlersTable.put(IntrospectionVocabulary.ADDEDMTP, (EventHandler) ev -> { + AddedMTP amtp = (AddedMTP) ev; + String address = amtp.getAddress(); + ContainerID where = amtp.getWhere(); + myGUI.addAddress(address, where.getName()); + }); + + handlersTable.put(IntrospectionVocabulary.REMOVEDMTP, (EventHandler) ev -> { + RemovedMTP rmtp = (RemovedMTP) ev; + String address = rmtp.getAddress(); + ContainerID where = rmtp.getWhere(); + myGUI.removeAddress(address, where.getName()); + }); + + //handle the APDescription provided by the AMS + handlersTable.put(IntrospectionVocabulary.PLATFORMDESCRIPTION, (EventHandler) ev -> { + PlatformDescription pd = (PlatformDescription) ev; + myPlatformProfile = pd.getPlatform(); + myGUI.refreshLocalPlatformName(myPlatformProfile.getName()); + }); + + } + } // END of inner class RMAAMSListenerBehaviour } diff --git a/src/jade/tools/sl/SLFormatter.java b/src/jade/tools/sl/SLFormatter.java index c54a65d..23d2e30 100644 --- a/src/jade/tools/sl/SLFormatter.java +++ b/src/jade/tools/sl/SLFormatter.java @@ -39,36 +39,15 @@ * @version 1.0 */ public class SLFormatter { - static String spacing = "\n "; private static final int INDENT_EXPRESSION = 2; private static final int INDENT_ARGUMENT = 2; private static final int SHORT_EXPRESSION_LENGTH = 40; + static String spacing = "\n "; /** - * Private class to iterate over a string. - * This has a next() and hasNext() inspired by the standard Iterator - * interface. - * (It might appear that java.text.StringCharacterIterator would - * work, but its implementation of next() doesn't match the - * standard iterator - it returns the value after incrementing - * the index, and so always skips the first character). + * Default constructor. */ - private static class myStringIterator { - public String string; - public int index; - - myStringIterator(String s) { - string = s; - index = 0; - } - - char next() { - return string.charAt(index++); - } - - boolean hasNext() { - return index < string.length(); - } + public SLFormatter() { } /** @@ -112,7 +91,7 @@ public static String format(String s) { } private static String format(myStringIterator src, int indentation) { - StringBuffer result = new StringBuffer(); + StringBuilder result = new StringBuilder(); char current, previous = 0; int indentStep = INDENT_EXPRESSION; boolean insideQuote = false; @@ -173,9 +152,30 @@ public static void main(String[] args) { } /** - * Default constructor. + * Private class to iterate over a string. + * This has a next() and hasNext() inspired by the standard Iterator + * interface. + * (It might appear that java.text.StringCharacterIterator would + * work, but its implementation of next() doesn't match the + * standard iterator - it returns the value after incrementing + * the index, and so always skips the first character). */ - public SLFormatter() { + private static class myStringIterator { + public String string; + public int index; + + myStringIterator(String s) { + string = s; + index = 0; + } + + char next() { + return string.charAt(index++); + } + + boolean hasNext() { + return index < string.length(); + } } } diff --git a/src/jade/tools/sniffer/AboutBoxAction.java b/src/jade/tools/sniffer/AboutBoxAction.java index 4b792e5..264af04 100644 --- a/src/jade/tools/sniffer/AboutBoxAction.java +++ b/src/jade/tools/sniffer/AboutBoxAction.java @@ -37,11 +37,9 @@ public class AboutBoxAction extends AbstractAction { private final JFrame gui; - private JLabel label; private final String imageFile = "images/jadelogo.jpg"; - - Color dark_blue = new Color(0, 0, 160); + private JLabel label; public AboutBoxAction(JFrame gui) { super("About SNIFFER"); diff --git a/src/jade/tools/sniffer/AbstractPopup.java b/src/jade/tools/sniffer/AbstractPopup.java index 1427b98..2ed70bb 100644 --- a/src/jade/tools/sniffer/AbstractPopup.java +++ b/src/jade/tools/sniffer/AbstractPopup.java @@ -37,16 +37,17 @@ /** * AbstractPopup is the superclass of the actions * performed by PopupMenu on the Canvas. - * + *

* This class is abstract because it does not define the * ActionPerformed(ActionEvent evt) method. In every subClass of * AbstractPopup this method performs a specific action. - * + *

* Subclasses of AbstractPopup are: - * @see PopSniffAgent - * @see PopNoSniffAgent - * @see PopShowAgent - * @see ViewMessage + * + * @see PopSniffAgent + * @see PopNoSniffAgent + * @see PopShowAgent + * @see ViewMessage */ diff --git a/src/jade/tools/sniffer/Agent.java b/src/jade/tools/sniffer/Agent.java index 12ddd52..7a56000 100644 --- a/src/jade/tools/sniffer/Agent.java +++ b/src/jade/tools/sniffer/Agent.java @@ -40,23 +40,18 @@ /** * Adds properties and methods for representing * agents on the Agent Canvas as rectangles. - * */ public class Agent implements Serializable { - public static int i = 0; public static final int hRet = 30; public static final int bRet = 50; public static final int yRet = 20; - - - public String agentName; + public static int i = 0; private final AID myAID; - private final int pos = 0; - + public String agentName; /** * This flag is true for agents on canvas and false for agents * out of the canvas. diff --git a/src/jade/tools/sniffer/AgentAction.java b/src/jade/tools/sniffer/AgentAction.java index 9038c60..054c0e4 100644 --- a/src/jade/tools/sniffer/AgentAction.java +++ b/src/jade/tools/sniffer/AgentAction.java @@ -36,7 +36,8 @@ * This class is useful to represent the actions that must perform * with the agents. * see FixedAction - * @see SnifferAction + * + * @see SnifferAction */ abstract class AgentAction extends SnifferAction { diff --git a/src/jade/tools/sniffer/ClearCanvasAction.java b/src/jade/tools/sniffer/ClearCanvasAction.java index 30365bb..59b912d 100644 --- a/src/jade/tools/sniffer/ClearCanvasAction.java +++ b/src/jade/tools/sniffer/ClearCanvasAction.java @@ -42,7 +42,7 @@ /** * Clears the Message Canvas. - * + *

* see FixedAction */ diff --git a/src/jade/tools/sniffer/DisplayLogFileAction.java b/src/jade/tools/sniffer/DisplayLogFileAction.java index 2e492fc..82da5bc 100644 --- a/src/jade/tools/sniffer/DisplayLogFileAction.java +++ b/src/jade/tools/sniffer/DisplayLogFileAction.java @@ -50,8 +50,8 @@ public class DisplayLogFileAction extends FixedAction { - private final MainPanel mainPanel; private static final Logger logger = Logger.getMyLogger(DisplayLogFileAction.class.getName()); + private final MainPanel mainPanel; public DisplayLogFileAction(ActionProcessor actPro, MainPanel mainPanel) { super("DisplayLogFileActionIcon", "Open Snapshot File", actPro); diff --git a/src/jade/tools/sniffer/DoNotSnifferAction.java b/src/jade/tools/sniffer/DoNotSnifferAction.java index 3719608..b7e93e1 100644 --- a/src/jade/tools/sniffer/DoNotSnifferAction.java +++ b/src/jade/tools/sniffer/DoNotSnifferAction.java @@ -41,6 +41,7 @@ /** * For don't sniff the Agent in the tree. + * * @see DoSnifferAction * @see ShowOnlyAction */ diff --git a/src/jade/tools/sniffer/DoSnifferAction.java b/src/jade/tools/sniffer/DoSnifferAction.java index f7de610..3812fed 100644 --- a/src/jade/tools/sniffer/DoSnifferAction.java +++ b/src/jade/tools/sniffer/DoSnifferAction.java @@ -41,6 +41,7 @@ /** * For sniff the Agent in the tree. + * * @see DoNotSnifferAction * @see ShowOnlyAction */ @@ -48,9 +49,9 @@ public class DoSnifferAction extends AgentAction { private final MainPanel mainPanel; - private Agent agent; private final Sniffer mySniffer; private final List sniffedAgents = new ArrayList<>(); + private Agent agent; public DoSnifferAction(ActionProcessor actPro, MainPanel mainPanel, Sniffer mySniffer) { super("DoSnifferActionIcon", "Do sniff this agent(s)", actPro); @@ -62,10 +63,12 @@ public void doAction(AgentTree.AgentNode node) { doSniff(node.getName()); } - /** Given an agent name, sniff it. + /** + * Given an agent name, sniff it. + * * @param agentName - the String name of the agent. - * Note, this was originally buried in doAction, but we want the ability to - * sniff with just a name. + * Note, this was originally buried in doAction, but we want the ability to + * sniff with just a name. */ public void doSniff(String agentName) { String realName = checkString(agentName); diff --git a/src/jade/tools/sniffer/ExitAction.java b/src/jade/tools/sniffer/ExitAction.java index 2e8178a..e82b07e 100644 --- a/src/jade/tools/sniffer/ExitAction.java +++ b/src/jade/tools/sniffer/ExitAction.java @@ -35,7 +35,7 @@ /** - Invokes the agent Sniffer to delete itself, closing the Gui and unregistering. + * Invokes the agent Sniffer to delete itself, closing the Gui and unregistering. * see FixedAction */ diff --git a/src/jade/tools/sniffer/FixedAction.java b/src/jade/tools/sniffer/FixedAction.java index 2d76cbd..f8d7e35 100644 --- a/src/jade/tools/sniffer/FixedAction.java +++ b/src/jade/tools/sniffer/FixedAction.java @@ -33,8 +33,9 @@ /** * This class is useful to represent the actions that must perform * with the agents. - * @see AgentAction - * @see SnifferAction + * + * @see AgentAction + * @see SnifferAction */ abstract class FixedAction extends SnifferAction { diff --git a/src/jade/tools/sniffer/GuiProperties.java b/src/jade/tools/sniffer/GuiProperties.java index 7a80280..9e546b5 100644 --- a/src/jade/tools/sniffer/GuiProperties.java +++ b/src/jade/tools/sniffer/GuiProperties.java @@ -37,14 +37,13 @@ /** * This class loads the icons used in the toolbar and menus - * */ public class GuiProperties { + public static final String ImagePath = ""; protected static UIDefaults MyDefaults; protected static GuiProperties foo = new GuiProperties(); - public static final String ImagePath = ""; static { Object[] icons = { diff --git a/src/jade/tools/sniffer/MMCanvas.java b/src/jade/tools/sniffer/MMCanvas.java index 783b0be..d44d7cb 100644 --- a/src/jade/tools/sniffer/MMCanvas.java +++ b/src/jade/tools/sniffer/MMCanvas.java @@ -65,17 +65,10 @@ public class MMCanvas private static final int H_TOL = 4; private static final int timeUnitWidth = 20; private static final int xOffset = 38; - private int positionAgent = 0; - - - private int x1, x2, y; private final MainWindow mWnd; private final PanelCanvas panCan; /* To resize and modify the scroll bars */ private final MainPanel mPan; - private int horDim = 400; - private int vertDim = 200; private final boolean typeCanv; - private boolean nameShown = false; private final List noSniffAgents = new ArrayList<>(); //#DOTNET_EXCLUDE_BEGIN private final Font font1 = new Font("Helvetica", Font.ITALIC, 12); @@ -94,9 +87,6 @@ public class MMCanvas private Panel myPanel; #DOTNET_INCLUDE_END*/ private final MMCanvas otherCanv; - public AgentList al; - public MessageList ml; - // These vars are used to make messages grouped by conversationID appear as the // same color. It makes it easier to pick out various conversations. private final HashMap mapToColor = new HashMap<>(); @@ -105,6 +95,13 @@ public class MMCanvas private final Color[] colorTable = {new Color(200, 0, 150), Color.blue, new Color(230, 230, 0), Color.red, Color.black, Color.magenta, Color.cyan, Color.pink, new Color(0, 200, 150), Color.green}; private final Color noConversationColor = Color.gray; + public AgentList al; + public MessageList ml; + private int positionAgent = 0; + private int x1, x2, y; + private int horDim = 400; + private int vertDim = 200; + private boolean nameShown = false; //#DOTNET_EXCLUDE_END /*#DOTNET_INCLUDE_BEGIN private Color colorTable[] = @@ -990,16 +987,6 @@ public AgentList getAgentList() { return al; } - /** - * Returns an handler to the message list. The message list contains all - * sniffed messages displayed on the Message Canavs as blue arrows - * - * @return handler to the message list - */ - public MessageList getMessageList() { - return ml; - } - /** * Set the agent list handler as the parameter passed then repaints the canvas * @@ -1011,6 +998,16 @@ public void setAgentList(AgentList savedList) { repaintBothCanvas(); } + /** + * Returns an handler to the message list. The message list contains all + * sniffed messages displayed on the Message Canavs as blue arrows + * + * @return handler to the message list + */ + public MessageList getMessageList() { + return ml; + } + /** * Set the message list handler as the parameter passed then repaints the canvas * diff --git a/src/jade/tools/sniffer/MainMenu.java b/src/jade/tools/sniffer/MainMenu.java index f100ff7..681152e 100644 --- a/src/jade/tools/sniffer/MainMenu.java +++ b/src/jade/tools/sniffer/MainMenu.java @@ -54,29 +54,15 @@ public class MainMenu extends JMenuBar public class MainMenuSniffer extends MainMenu #DOTNET_INCLUDE_END*/ { - //#DOTNET_EXCLUDE_BEGIN - private JMenuItem tmp; - private JMenu menu; //#DOTNET_EXCLUDE_END /*#DOTNET_INCLUDE_BEGIN private MenuItem menu; private MenuItem tmp; #DOTNET_INCLUDE_END*/ private final ActionProcessor actPro; - - void paintM(boolean enable, SnifferAction obj) { - //#DOTNET_EXCLUDE_BEGIN - tmp = menu.add(obj); - tmp.setEnabled(enable); - //#DOTNET_EXCLUDE_END - /*#DOTNET_INCLUDE_BEGIN - tmp = new MenuItem(); - tmp.set_Text( obj.getActionName() ); - tmp.add_Click( new System.EventHandler(obj.OnClick) ); - tmp.set_Enabled( enable ); - menu.get_MenuItems().Add( tmp ); - #DOTNET_INCLUDE_END*/ - } + //#DOTNET_EXCLUDE_BEGIN + private JMenuItem tmp; + private JMenu menu; //#DOTNET_EXCLUDE_BEGIN public MainMenu(MainWindow mainWnd, ActionProcessor actPro) { @@ -147,4 +133,18 @@ public MainMenuSniffer(MainWindow mainWnd,ActionProcessor actPro) { #DOTNET_INCLUDE_END*/ } + void paintM(boolean enable, SnifferAction obj) { + //#DOTNET_EXCLUDE_BEGIN + tmp = menu.add(obj); + tmp.setEnabled(enable); + //#DOTNET_EXCLUDE_END + /*#DOTNET_INCLUDE_BEGIN + tmp = new MenuItem(); + tmp.set_Text( obj.getActionName() ); + tmp.add_Click( new System.EventHandler(obj.OnClick) ); + tmp.set_Enabled( enable ); + menu.get_MenuItems().Add( tmp ); + #DOTNET_INCLUDE_END*/ + } + } diff --git a/src/jade/tools/sniffer/MainPanel.java b/src/jade/tools/sniffer/MainPanel.java index 754b6ae..668b44f 100644 --- a/src/jade/tools/sniffer/MainPanel.java +++ b/src/jade/tools/sniffer/MainPanel.java @@ -45,6 +45,7 @@ /** * Sets the tree and the two canvas inside the MainWindow + * * @see PanelCanvas */ @@ -55,13 +56,12 @@ public class MainPanel /*#DOTNET_INCLUDE_BEGIN extends Panel #DOTNET_INCLUDE_END*/ { + private final JSplitPane pane; + private final Font font = new Font("Helvetica", Font.ITALIC, 12); + public JTextArea textArea; protected AgentTree treeAgent; //#DOTNET_EXCLUDE_BEGIN protected PanelCanvas panelcan; - private final JSplitPane pane; - private PopupMouser popM; - public JTextArea textArea; - private final Font font = new Font("Helvetica", Font.ITALIC, 12); //#DOTNET_EXCLUDE_END /*#DOTNET_INCLUDE_BEGIN private System.Drawing.Font font = new System.Drawing.Font("Helvetica",12, FontStyle.Italic); @@ -70,6 +70,7 @@ public class MainPanel private Panel myPanel; #DOTNET_INCLUDE_END*/ int pos; + private PopupMouser popM; public MainPanel(Sniffer mySniffer, MainWindow mwnd) { //#DOTNET_EXCLUDE_BEGIN diff --git a/src/jade/tools/sniffer/MainWindow.java b/src/jade/tools/sniffer/MainWindow.java index 22daab2..ad9a441 100644 --- a/src/jade/tools/sniffer/MainWindow.java +++ b/src/jade/tools/sniffer/MainWindow.java @@ -46,7 +46,7 @@ * This class performs the Sniffer main-windows GUI setup. Also provides method for * asynchronous disposal at takedown. * - * @see JFrame + * @see JFrame */ @@ -58,14 +58,14 @@ public class MainWindow extends Form { #DOTNET_INCLUDE_END*/ - protected MainPanel mainPanel; - protected ActionProcessor actPro; // Making this public allows us to get directly to the sniff agent action. //#DOTNET_EXCLUDE_BEGIN private final PopupMenuAgent popA; //#DOTNET_EXCLUDE_END private final Sniffer mySniffer; private final ExtendedProperties myProperties; private final String snifferLogo = "images/sniffer.gif"; + protected MainPanel mainPanel; + protected ActionProcessor actPro; // Making this public allows us to get directly to the sniff agent action. /*#DOTNET_INCLUDE_BEGIN private System.Windows.Forms.Panel MainPanelW; private System.Windows.Forms.Splitter splitter2; @@ -293,7 +293,7 @@ private void InitializeComponent () /** * Tells the Agent Tree to add a container. * - * @param name name of the container to be added + * @param name name of the container to be added */ public void addContainer(final String name, final InetAddress addr) { @@ -316,7 +316,7 @@ public void addContainer(final String name, final InetAddress addr) { /** * Tells the Agent Tree to remove a specified container. * - * @param name cont name of the container to be removed + * @param name cont name of the container to be removed */ public void removeContainer(final String name) { @@ -332,7 +332,7 @@ public void removeContainer(final String name) { /** * Tells the Agent Tree to add an agent. * - * @param containerName name of the container to contain the new agent + * @param containerName name of the container to contain the new agent */ public void addAgent(final String containerName, final AID agentID) { @@ -356,8 +356,8 @@ public void addAgent(final String containerName, final AID agentID) { /** * Tells the Agent Tree to remove a specified agent. * - * @param containerName name of the container containing the agent - * @param agentID name of the agent to be removed + * @param containerName name of the container containing the agent + * @param agentID name of the agent to be removed */ public void removeAgent(final String containerName, final AID agentID) { @@ -381,7 +381,7 @@ public void removeAgent(final String containerName, final AID agentID) { /** * Displays a dialog box with the error string. * - * @param errMsg error message to print + * @param errMsg error message to print */ public void showError(String errMsg) { @@ -410,7 +410,7 @@ private void setUI(String ui) { } /** - enables Motif L&F + * enables Motif L&F */ public void setUI2Motif() { @@ -418,7 +418,7 @@ public void setUI2Motif() { } /** - enables Windows L&F + * enables Windows L&F */ public void setUI2Windows() { @@ -426,7 +426,7 @@ public void setUI2Windows() { } /** - enables Multi L&F + * enables Multi L&F */ public void setUI2Multi() { @@ -434,7 +434,7 @@ public void setUI2Multi() { } /** - enables Metal L&F + * enables Metal L&F */ public void setUI2Metal() { setUI("metal.MetalLookAndFeel"); diff --git a/src/jade/tools/sniffer/Message.java b/src/jade/tools/sniffer/Message.java index b593a18..905bc96 100644 --- a/src/jade/tools/sniffer/Message.java +++ b/src/jade/tools/sniffer/Message.java @@ -44,18 +44,16 @@ public class Message extends ACLMessage implements Serializable { - private final AID unicastReceiver; - - private int x1, x2, y; - private final int[] xCoords = new int[3]; - private final int[] yCoords = new int[3]; - public static final int step = 80; public static final int offset = 45; public static final int r = 8; + private final AID unicastReceiver; + private final int[] xCoords = new int[3]; + private final int[] yCoords = new int[3]; private final int yDim = 0; private final int xS = 0; private final int xD = 0; + private int x1, x2, y; private int messageNumber = 0; /* TO BE REMOVED diff --git a/src/jade/tools/sniffer/PanelCanvas.java b/src/jade/tools/sniffer/PanelCanvas.java index afbf828..160e817 100644 --- a/src/jade/tools/sniffer/PanelCanvas.java +++ b/src/jade/tools/sniffer/PanelCanvas.java @@ -39,6 +39,7 @@ * Makes the two canvas.One is the agent canvas which is useful * for drawing the agent's box and other is the message canvas * which useful for drawing the message with blue arrows. + * * @see MainPanel */ @@ -50,8 +51,6 @@ public class PanelCanvas extends Panel #DOTNET_INCLUDE_END*/ { - protected MMCanvas canvAgent; - protected MMCanvas canvMess; //#DOTNET_EXCLUDE_BEGIN private final PopMouserMessage popMess; private final PopMouserAgent popAgent; @@ -62,6 +61,8 @@ public class PanelCanvas private PopupMessage popMess; #DOTNET_INCLUDE_END*/ private final Sniffer mySniffer; + protected MMCanvas canvAgent; + protected MMCanvas canvMess; public PanelCanvas(MainWindow mWnd, MainPanel mPan, Sniffer mySniffer) { /*#DOTNET_INCLUDE_BEGIN diff --git a/src/jade/tools/sniffer/PopMouserAgent.java b/src/jade/tools/sniffer/PopMouserAgent.java index dda6158..8063e78 100644 --- a/src/jade/tools/sniffer/PopMouserAgent.java +++ b/src/jade/tools/sniffer/PopMouserAgent.java @@ -36,6 +36,7 @@ /** * This is the listener for the canvas of agents + * * @see PopMouserMessage */ diff --git a/src/jade/tools/sniffer/PopMouserMessage.java b/src/jade/tools/sniffer/PopMouserMessage.java index ccdeef4..ebe89ad 100644 --- a/src/jade/tools/sniffer/PopMouserMessage.java +++ b/src/jade/tools/sniffer/PopMouserMessage.java @@ -37,6 +37,7 @@ /** * This is the listener for the canvas of messages + * * @see PopMouserAgent */ diff --git a/src/jade/tools/sniffer/PopNoSniffAgent.java b/src/jade/tools/sniffer/PopNoSniffAgent.java index d8e86db..bbf7969 100644 --- a/src/jade/tools/sniffer/PopNoSniffAgent.java +++ b/src/jade/tools/sniffer/PopNoSniffAgent.java @@ -48,6 +48,7 @@ /** * This class includes the method ActionPerformed that is * associated with the PopupMenu of the Agent in the canvas. + * * @see PopSniffAgent * @see PopShowAgent */ diff --git a/src/jade/tools/sniffer/PopShowAgent.java b/src/jade/tools/sniffer/PopShowAgent.java index 7ca5180..fcc3074 100644 --- a/src/jade/tools/sniffer/PopShowAgent.java +++ b/src/jade/tools/sniffer/PopShowAgent.java @@ -48,6 +48,7 @@ /** * This class includes the method ActionPerformed that is * associated with the PopupMenu of the Agent in the canvas. + * * @see PopSniffAgent * @see PopNoSniffAgent */ diff --git a/src/jade/tools/sniffer/PopSniffAgent.java b/src/jade/tools/sniffer/PopSniffAgent.java index 83d243f..dd4355b 100644 --- a/src/jade/tools/sniffer/PopSniffAgent.java +++ b/src/jade/tools/sniffer/PopSniffAgent.java @@ -48,6 +48,7 @@ /** * This class includes the method ActionPerformed that is * associated with the PopupMenu of the Agent in the canvas. + * * @see PopNoSniffAgent * @see PopShowAgent */ diff --git a/src/jade/tools/sniffer/PopupAgent.java b/src/jade/tools/sniffer/PopupAgent.java index f59880a..cae8fd0 100644 --- a/src/jade/tools/sniffer/PopupAgent.java +++ b/src/jade/tools/sniffer/PopupAgent.java @@ -39,6 +39,7 @@ /** * This is the PopupMenu that will appear if the user click * on the canvas of agents. + * * @see PopupMessage */ @@ -50,8 +51,6 @@ public class PopupAgent extends ContextMenu #DOTNET_INCLUDE_END*/ { - //#DOTNET_EXCLUDE_BEGIN - private JMenuItem tmp; //#DOTNET_EXCLUDE_END /*#DOTNET_INCLUDE_BEGIN private MenuItem tmp; @@ -60,8 +59,9 @@ public class PopupAgent private final PopSniffAgent popSniffAg; private final PopNoSniffAgent popNoSniffAg; private final PopShowAgent popShowAg; - protected Agent agent; + //#DOTNET_EXCLUDE_BEGIN + private JMenuItem tmp; public PopupAgent(Sniffer mySniffer, MMCanvas canvAgent) { super(); diff --git a/src/jade/tools/sniffer/PopupMessage.java b/src/jade/tools/sniffer/PopupMessage.java index 2ac74f4..59f4dca 100644 --- a/src/jade/tools/sniffer/PopupMessage.java +++ b/src/jade/tools/sniffer/PopupMessage.java @@ -41,6 +41,7 @@ /** * This is the PopupMenu that will appear if the user click * on the canvas of messages. + * * @see PopupAgent */ @@ -55,12 +56,12 @@ public class PopupMessage //#DOTNET_EXCLUDE_BEGIN private final JMenuItem tmp; + private final ViewMessage viewMessage; //#DOTNET_EXCLUDE_END /*#DOTNET_INCLUDE_BEGIN private MenuItem tmp; #DOTNET_INCLUDE_END*/ private MainWindow mWnd; - private final ViewMessage viewMessage; public PopupMessage(MainWindow mWnd) { super(); diff --git a/src/jade/tools/sniffer/Sniffer.java b/src/jade/tools/sniffer/Sniffer.java index 876feb7..a16e967 100644 --- a/src/jade/tools/sniffer/Sniffer.java +++ b/src/jade/tools/sniffer/Sniffer.java @@ -126,134 +126,19 @@ public class Sniffer extends ToolAgent { public static final boolean SNIFF_ON = true; public static final boolean SNIFF_OFF = false; - + private final ArrayList agentsUnderSniff = new ArrayList<>(); + private final SequentialBehaviour AMSSubscribe = new SequentialBehaviour(); private Set allAgents = null; private Hashtable preload = null; private ExtendedProperties properties = null; - - private final ArrayList agentsUnderSniff = new ArrayList<>(); - - - // Sends requests to the AMS - private class AMSClientBehaviour extends SimpleAchieveREInitiator { - - private final String actionName; - - public AMSClientBehaviour(String an, ACLMessage request) { - super(Sniffer.this, request); - actionName = an; - } - - protected void handleNotUnderstood(ACLMessage reply) { - myGUI.showError("NOT-UNDERSTOOD received during " + actionName); - } - - protected void handleRefuse(ACLMessage reply) { - myGUI.showError("REFUSE received during " + actionName); - } - - protected void handleAgree(ACLMessage reply) { - if (logger.isLoggable(Logger.FINE)) - logger.log(Logger.FINE, "AGREE received"); - } - - protected void handleFailure(ACLMessage reply) { - myGUI.showError("FAILURE received during " + actionName); - } - - protected void handleInform(ACLMessage reply) { - if (logger.isLoggable(Logger.FINE)) - logger.log(Logger.FINE, "INFORM received"); - } - - } // End of AMSClientBehaviour class - - - private class SniffListenerBehaviour extends CyclicBehaviour { - - private final MessageTemplate listenSniffTemplate; - - SniffListenerBehaviour() { - listenSniffTemplate = MessageTemplate.MatchConversationId(getName() + "-event"); - } - - public void action() { - - ACLMessage current = receive(listenSniffTemplate); - if (current != null) { - - try { - Occurred o = (Occurred) getContentManager().extractContent(current); - EventRecord er = o.getWhat(); - Event ev = er.getWhat(); - String content = null; - Envelope env = null; - AID unicastReceiver = null; - if (ev instanceof SentMessage) { - content = ((SentMessage) ev).getMessage().getPayload(); - env = ((SentMessage) ev).getMessage().getEnvelope(); - unicastReceiver = ((SentMessage) ev).getReceiver(); - } else if (ev instanceof PostedMessage) { - content = ((PostedMessage) ev).getMessage().getPayload(); - env = ((PostedMessage) ev).getMessage().getEnvelope(); - unicastReceiver = ((PostedMessage) ev).getReceiver(); - AID sender = ((PostedMessage) ev).getSender(); - // If the sender is currently under sniff, then the message was already - // displayed when the 'sent-message' event occurred --> just skip this message. - if (agentsUnderSniff.contains(new Agent(sender))) { - return; - } - } else { - return; - } - - ACLCodec codec = new StringACLCodec(); - String charset = null; - if ((env == null) || ((charset = env.getPayloadEncoding()) == null)) { - charset = ACLCodec.DEFAULT_CHARSET; - } - ACLMessage tmp = codec.decode(content.getBytes(charset), charset); - tmp.setEnvelope(env); - Message msg = new Message(tmp, unicastReceiver); - - /* If this is a 'posted-message' event and the sender is - // currently under sniff, then the message was already - // displayed when the 'sent-message' event occurred. In that - // case, we simply skip this message. - if(ev instanceof PostedMessage) { - Agent a = new Agent(msg.getSender()); - if(agentsUnderSniff.contains(a)) - return; - }*/ - - - // If the message that we just got is one that should be filtered out - // then drop it. WARNING - this means that the log file - // that the sniffer might dump does not include the message!!!! - boolean[] filters; - String agentName = msg.getSender().getName(); - String key = preloadContains(agentName); - if (key != null) { - filters = preload.get(key); - if ((msg.getPerformative() >= 0) && filters[msg.getPerformative()]) { - myGUI.mainPanel.panelcan.canvMess.recMessage(msg); - } - } else { - myGUI.mainPanel.panelcan.canvMess.recMessage(msg); - } - } catch (Throwable e) { - //System.out.println("Serious problem Occurred"); - myGUI.showError("An error occurred parsing the incoming message.\n" + - " The message was lost."); - if (logger.isLoggable(Logger.WARNING)) - logger.log(Logger.WARNING, "The sniffer lost the following message because of a parsing error:" + current); - e.printStackTrace(); - } - } else - block(); - } - - } // End of SniffListenerBehaviour + /** + * @serial + */ + private MainWindow myGUI; + /** + * @serial + */ + private String myContainerName; // // @@ -306,95 +191,6 @@ protected boolean isMatch(String aMatchExpression, String aString) { return (expressionLength == aString.length()); } - private final SequentialBehaviour AMSSubscribe = new SequentialBehaviour(); - - /** - * @serial - */ - private MainWindow myGUI; - - /** - * @serial - */ - private String myContainerName; - - class SnifferAMSListenerBehaviour extends AMSListenerBehaviour { - - protected void installHandlers(Map handlersTable) { - - - // Fill the event handler table. - - handlersTable.put(IntrospectionVocabulary.META_RESETEVENTS, (EventHandler) ev -> { - ResetEvents re = (ResetEvents) ev; - myGUI.resetTree(); - allAgents.clear(); - }); - - handlersTable.put(IntrospectionVocabulary.ADDEDCONTAINER, (EventHandler) ev -> { - AddedContainer ac = (AddedContainer) ev; - ContainerID cid = ac.getContainer(); - String name = cid.getName(); - String address = cid.getAddress(); - try { - InetAddress addr = InetAddress.getByName(address); - myGUI.addContainer(name, addr); - } catch (UnknownHostException uhe) { - myGUI.addContainer(name, null); - } - }); - - handlersTable.put(IntrospectionVocabulary.REMOVEDCONTAINER, (EventHandler) ev -> { - RemovedContainer rc = (RemovedContainer) ev; - ContainerID cid = rc.getContainer(); - String name = cid.getName(); - myGUI.removeContainer(name); - }); - - handlersTable.put(IntrospectionVocabulary.BORNAGENT, (EventHandler) ev -> { - BornAgent ba = (BornAgent) ev; - ContainerID cid = ba.getWhere(); - String container = cid.getName(); - AID agent = ba.getAgent(); - myGUI.addAgent(container, agent); - allAgents.add(agent); - if (agent.equals(getAID())) - myContainerName = container; - // Here we check to see if the agent is one that we automatically will - // start sniffing. If so, we invoke DoSnifferAction's doSniff and start - // the sniffing process. - // Avoid sniffing myself to avoid infinite recursion - if (!agent.equals(getAID())) { - if (preloadContains(agent.getName()) != null) { - ActionProcessor ap = myGUI.actPro; - DoSnifferAction sa = (DoSnifferAction) ap.actions.get(ActionProcessor.DO_SNIFFER_ACTION); - sa.doSniff(agent.getName()); - } - } - }); - - handlersTable.put(IntrospectionVocabulary.DEADAGENT, (EventHandler) ev -> { - DeadAgent da = (DeadAgent) ev; - ContainerID cid = da.getWhere(); - String container = cid.getName(); - AID agent = da.getAgent(); - myGUI.removeAgent(container, agent); - allAgents.remove(agent); - - }); - - handlersTable.put(IntrospectionVocabulary.MOVEDAGENT, (EventHandler) ev -> { - MovedAgent ma = (MovedAgent) ev; - AID agent = ma.getAgent(); - ContainerID from = ma.getFrom(); - myGUI.removeAgent(from.getName(), agent); - ContainerID to = ma.getTo(); - myGUI.addAgent(to.getName(), agent); - }); - - } - } // END of inner class SnifferAMSListenerBehaviour - /** * ACLMessages for subscription and unsubscription as rma are created and * corresponding behaviours are set up. @@ -471,33 +267,6 @@ public void toolSetup() { #DOTNET_INCLUDE_END*/ } - /*#DOTNET_INCLUDE_BEGIN - private void createUI() - { - // Show Graphical User Interface - myGUI = new MainWindow(this, properties); - myGUI.ShowCorrect(); - System.Windows.Forms.Application.Run(); - } - - protected void startBehaviours() - { - // Send 'subscribe' message to the AMS - AMSSubscribe.addSubBehaviour(new SenderBehaviour(this, getSubscribe())); - - // Handle incoming 'inform' messages - AMSSubscribe.addSubBehaviour(new SnifferAMSListenerBehaviour()); - - // Handle incoming REQUEST to start/stop sniffing agents - addBehaviour(new RequestListenerBehaviour()); - - // Schedule Behaviours for execution - addBehaviour(AMSSubscribe); - addBehaviour(new SniffListenerBehaviour()); - } - #DOTNET_INCLUDE_END*/ - - private void addAgent(AID id) { ActionProcessor ap = myGUI.actPro; DoSnifferAction sa = (DoSnifferAction) ap.actions.get(ActionProcessor.DO_SNIFFER_ACTION); @@ -510,7 +279,6 @@ private void removeAgent(AID id) { nsa.doNotSniff(id.getName()); } - /** * Private function to read configuration file containing names of agents to be * preloaded. Also supports message filtering based on performatives. @@ -553,6 +321,32 @@ private void loadSnifferConfigurationFile(String aFileName, ExtendedProperties t } } + /*#DOTNET_INCLUDE_BEGIN + private void createUI() + { + // Show Graphical User Interface + myGUI = new MainWindow(this, properties); + myGUI.ShowCorrect(); + System.Windows.Forms.Application.Run(); + } + + protected void startBehaviours() + { + // Send 'subscribe' message to the AMS + AMSSubscribe.addSubBehaviour(new SenderBehaviour(this, getSubscribe())); + + // Handle incoming 'inform' messages + AMSSubscribe.addSubBehaviour(new SnifferAMSListenerBehaviour()); + + // Handle incoming REQUEST to start/stop sniffing agents + addBehaviour(new RequestListenerBehaviour()); + + // Schedule Behaviours for execution + addBehaviour(AMSSubscribe); + addBehaviour(new SniffListenerBehaviour()); + } + #DOTNET_INCLUDE_END*/ + private String locateFile(String aFileName) { try { String path = (new File(".")).getAbsolutePath(); @@ -579,7 +373,6 @@ private String locateFile(String aFileName) { return null; } - private void parsePreloadDescription(String aDescription) { StringTokenizer st = new StringTokenizer(aDescription); String name = st.nextToken(); @@ -722,6 +515,202 @@ public ACLMessage getSniffMsg(List agents, boolean onFlag) { return null; } + // Sends requests to the AMS + private class AMSClientBehaviour extends SimpleAchieveREInitiator { + + private final String actionName; + + public AMSClientBehaviour(String an, ACLMessage request) { + super(Sniffer.this, request); + actionName = an; + } + + protected void handleNotUnderstood(ACLMessage reply) { + myGUI.showError("NOT-UNDERSTOOD received during " + actionName); + } + + protected void handleRefuse(ACLMessage reply) { + myGUI.showError("REFUSE received during " + actionName); + } + + protected void handleAgree(ACLMessage reply) { + if (logger.isLoggable(Logger.FINE)) + logger.log(Logger.FINE, "AGREE received"); + } + + protected void handleFailure(ACLMessage reply) { + myGUI.showError("FAILURE received during " + actionName); + } + + protected void handleInform(ACLMessage reply) { + if (logger.isLoggable(Logger.FINE)) + logger.log(Logger.FINE, "INFORM received"); + } + + } // End of AMSClientBehaviour class + + private class SniffListenerBehaviour extends CyclicBehaviour { + + private final MessageTemplate listenSniffTemplate; + + SniffListenerBehaviour() { + listenSniffTemplate = MessageTemplate.MatchConversationId(getName() + "-event"); + } + + public void action() { + + ACLMessage current = receive(listenSniffTemplate); + if (current != null) { + + try { + Occurred o = (Occurred) getContentManager().extractContent(current); + EventRecord er = o.getWhat(); + Event ev = er.getWhat(); + String content = null; + Envelope env = null; + AID unicastReceiver = null; + if (ev instanceof SentMessage) { + content = ((SentMessage) ev).getMessage().getPayload(); + env = ((SentMessage) ev).getMessage().getEnvelope(); + unicastReceiver = ((SentMessage) ev).getReceiver(); + } else if (ev instanceof PostedMessage) { + content = ((PostedMessage) ev).getMessage().getPayload(); + env = ((PostedMessage) ev).getMessage().getEnvelope(); + unicastReceiver = ((PostedMessage) ev).getReceiver(); + AID sender = ((PostedMessage) ev).getSender(); + // If the sender is currently under sniff, then the message was already + // displayed when the 'sent-message' event occurred --> just skip this message. + if (agentsUnderSniff.contains(new Agent(sender))) { + return; + } + } else { + return; + } + + ACLCodec codec = new StringACLCodec(); + String charset = null; + if ((env == null) || ((charset = env.getPayloadEncoding()) == null)) { + charset = ACLCodec.DEFAULT_CHARSET; + } + ACLMessage tmp = codec.decode(content.getBytes(charset), charset); + tmp.setEnvelope(env); + Message msg = new Message(tmp, unicastReceiver); + + /* If this is a 'posted-message' event and the sender is + // currently under sniff, then the message was already + // displayed when the 'sent-message' event occurred. In that + // case, we simply skip this message. + if(ev instanceof PostedMessage) { + Agent a = new Agent(msg.getSender()); + if(agentsUnderSniff.contains(a)) + return; + }*/ + + + // If the message that we just got is one that should be filtered out + // then drop it. WARNING - this means that the log file + // that the sniffer might dump does not include the message!!!! + boolean[] filters; + String agentName = msg.getSender().getName(); + String key = preloadContains(agentName); + if (key != null) { + filters = preload.get(key); + if ((msg.getPerformative() >= 0) && filters[msg.getPerformative()]) { + myGUI.mainPanel.panelcan.canvMess.recMessage(msg); + } + } else { + myGUI.mainPanel.panelcan.canvMess.recMessage(msg); + } + } catch (Throwable e) { + //System.out.println("Serious problem Occurred"); + myGUI.showError("An error occurred parsing the incoming message.\n" + + " The message was lost."); + if (logger.isLoggable(Logger.WARNING)) + logger.log(Logger.WARNING, "The sniffer lost the following message because of a parsing error:" + current); + e.printStackTrace(); + } + } else + block(); + } + + } // End of SniffListenerBehaviour + + class SnifferAMSListenerBehaviour extends AMSListenerBehaviour { + + protected void installHandlers(Map handlersTable) { + + + // Fill the event handler table. + + handlersTable.put(IntrospectionVocabulary.META_RESETEVENTS, (EventHandler) ev -> { + ResetEvents re = (ResetEvents) ev; + myGUI.resetTree(); + allAgents.clear(); + }); + + handlersTable.put(IntrospectionVocabulary.ADDEDCONTAINER, (EventHandler) ev -> { + AddedContainer ac = (AddedContainer) ev; + ContainerID cid = ac.getContainer(); + String name = cid.getName(); + String address = cid.getAddress(); + try { + InetAddress addr = InetAddress.getByName(address); + myGUI.addContainer(name, addr); + } catch (UnknownHostException uhe) { + myGUI.addContainer(name, null); + } + }); + + handlersTable.put(IntrospectionVocabulary.REMOVEDCONTAINER, (EventHandler) ev -> { + RemovedContainer rc = (RemovedContainer) ev; + ContainerID cid = rc.getContainer(); + String name = cid.getName(); + myGUI.removeContainer(name); + }); + + handlersTable.put(IntrospectionVocabulary.BORNAGENT, (EventHandler) ev -> { + BornAgent ba = (BornAgent) ev; + ContainerID cid = ba.getWhere(); + String container = cid.getName(); + AID agent = ba.getAgent(); + myGUI.addAgent(container, agent); + allAgents.add(agent); + if (agent.equals(getAID())) + myContainerName = container; + // Here we check to see if the agent is one that we automatically will + // start sniffing. If so, we invoke DoSnifferAction's doSniff and start + // the sniffing process. + // Avoid sniffing myself to avoid infinite recursion + if (!agent.equals(getAID())) { + if (preloadContains(agent.getName()) != null) { + ActionProcessor ap = myGUI.actPro; + DoSnifferAction sa = (DoSnifferAction) ap.actions.get(ActionProcessor.DO_SNIFFER_ACTION); + sa.doSniff(agent.getName()); + } + } + }); + + handlersTable.put(IntrospectionVocabulary.DEADAGENT, (EventHandler) ev -> { + DeadAgent da = (DeadAgent) ev; + ContainerID cid = da.getWhere(); + String container = cid.getName(); + AID agent = da.getAgent(); + myGUI.removeAgent(container, agent); + allAgents.remove(agent); + + }); + + handlersTable.put(IntrospectionVocabulary.MOVEDAGENT, (EventHandler) ev -> { + MovedAgent ma = (MovedAgent) ev; + AID agent = ma.getAgent(); + ContainerID from = ma.getFrom(); + myGUI.removeAgent(from.getName(), agent); + ContainerID to = ma.getTo(); + myGUI.addAgent(to.getName(), agent); + }); + + } + } // END of inner class SnifferAMSListenerBehaviour /** * Inner class RequestListenerBehaviour. diff --git a/src/jade/tools/sniffer/SnifferAction.java b/src/jade/tools/sniffer/SnifferAction.java index f578bc2..15268aa 100644 --- a/src/jade/tools/sniffer/SnifferAction.java +++ b/src/jade/tools/sniffer/SnifferAction.java @@ -46,8 +46,8 @@ public abstract class SnifferAction extends AbstractAction { private final ActionProcessor actPro; - private Icon img; private final String ActionName; + private Icon img; public SnifferAction(String IconKey, String ActionName, ActionProcessor actPro) { //#DOTNET_EXCLUDE_BEGIN diff --git a/src/jade/tools/sniffer/WriteLogFileAction.java b/src/jade/tools/sniffer/WriteLogFileAction.java index 01ed0ca..9c43139 100644 --- a/src/jade/tools/sniffer/WriteLogFileAction.java +++ b/src/jade/tools/sniffer/WriteLogFileAction.java @@ -42,16 +42,17 @@ /** * Creates a serialized snapshot of the agents and sniffed messages in both canvases for * later recall. - * + *

* see FixedAction + * * @see AgentList * @see MessageList */ public class WriteLogFileAction extends FixedAction implements Serializable { - private final MainPanel mainPanel; private static final Logger logger = Logger.getMyLogger(WriteLogFileAction.class.getName()); + private final MainPanel mainPanel; public WriteLogFileAction(ActionProcessor actPro, MainPanel mainPanel) { super("WriteLogFileActionIcon", "Save Snapshot File", actPro); diff --git a/src/jade/tools/sniffer/WriteMessageListAction.java b/src/jade/tools/sniffer/WriteMessageListAction.java index 7c28092..70fc127 100644 --- a/src/jade/tools/sniffer/WriteMessageListAction.java +++ b/src/jade/tools/sniffer/WriteMessageListAction.java @@ -45,15 +45,16 @@ * Writes a text file with all sniffed messages showed on the Message Canvas. A dialog box * asks the user the name of the file. * see FixedAction + * * @see AgentList * @see MessageList */ public class WriteMessageListAction extends FixedAction implements Serializable { - private PrintWriter out; - private final MainPanel mainPanel; private static final Logger logger = Logger.getMyLogger(WriteMessageListAction.class.getName()); + private final MainPanel mainPanel; + private PrintWriter out; public WriteMessageListAction(ActionProcessor actPro, MainPanel mainPanel) { diff --git a/src/jade/tools/testagent/ReceiveCyclicBehaviour.java b/src/jade/tools/testagent/ReceiveCyclicBehaviour.java index df92713..ac52e01 100644 --- a/src/jade/tools/testagent/ReceiveCyclicBehaviour.java +++ b/src/jade/tools/testagent/ReceiveCyclicBehaviour.java @@ -34,6 +34,9 @@ * @created May 21, 2002 */ public class ReceiveCyclicBehaviour extends CyclicBehaviour { + private final TestAgent agent; + + /** * Constructor for the ReceiveCyclicBehaviour object * @@ -43,15 +46,11 @@ public ReceiveCyclicBehaviour(TestAgent agent) { this.agent = agent; } - /** * Description of the Method */ public void action() { agent.processIncomingMessage(agent.blockingReceive()); } - - - private final TestAgent agent; } // ***EOF*** diff --git a/src/jade/tools/testagent/TestAgent.java b/src/jade/tools/testagent/TestAgent.java index 7e84579..56bedea 100644 --- a/src/jade/tools/testagent/TestAgent.java +++ b/src/jade/tools/testagent/TestAgent.java @@ -53,6 +53,12 @@ public class TestAgent extends Agent { private static final Logger logger = Logger.getMyLogger(TestAgent.class.getName()); + boolean pingBehaviour = true; + ImageIcon dummyIcon = + new ImageIcon(this.getClass().getResource("images/dummy.gif")); + SplashScreen splash; + TestAgentFrame itsFrame; + /** * Constructor for the TestAgent @@ -61,7 +67,6 @@ public TestAgent() { super(); } - /** * The main program for the TestAgent class * @@ -73,7 +78,6 @@ public static void main(String[] args) { jade.Boot3.main(argsv); } - /** * Gets the PlatformRequest attribute of the TestAgent object * @@ -91,7 +95,6 @@ public ACLMessage getPlatformRequest() { return msg; } - /** * Description of the Method */ @@ -108,7 +111,6 @@ public void doRegisterAMS() { itsFrame.setItsMsg(msg); } - public void doRegisterDF() { ServiceDescription serviceDescr = new ServiceDescription(); @@ -129,7 +131,6 @@ public void doRegisterDF() { itsFrame.setItsMsg(msg); } - public void doDeregisterDF() { DFAgentDescription dFAgentDescription = new DFAgentDescription(); dFAgentDescription.setName(getAID()); @@ -140,7 +141,6 @@ public void doDeregisterDF() { itsFrame.setItsMsg(msg); } - public void doDeRegisterAMS() { AMSAgentDescription amsAgentDescription = new AMSAgentDescription(); @@ -152,7 +152,6 @@ public void doDeRegisterAMS() { itsFrame.setItsMsg(msg); } - public void doSearchAMS() { AMSAgentDescription amsAgentDescription = new AMSAgentDescription(); @@ -168,7 +167,6 @@ public void doSearchAMS() { itsFrame.setItsMsg(msg); } - public void doSearchDF() { DFAgentDescription dFAgentDescription = new DFAgentDescription(); @@ -185,7 +183,6 @@ public void doSearchDF() { itsFrame.setItsMsg(msg); } - public void doLausannePing() { ACLMessage msg = new ACLMessage(ACLMessage.QUERY_REF); msg.setSender(getAID()); @@ -201,7 +198,6 @@ public void doLausannePing() { itsFrame.setItsMsg(msg); } - public void doLocalPing() { ACLMessage msg = new ACLMessage(ACLMessage.QUERY_REF); msg.setSender(getAID()); @@ -213,7 +209,6 @@ public void doLocalPing() { itsFrame.setItsMsg(msg); } - /** * Description of the Method */ @@ -230,7 +225,6 @@ public void doHelloWorld() { itsFrame.setItsMsg(msg); } - /** * Description of the Method */ @@ -238,7 +232,6 @@ public void doSystemOut() { System.out.println(itsFrame.getItsMsg()); } - /** * exit method */ @@ -247,7 +240,6 @@ public void doExit() { System.exit(0); } - /** * Description of the Method */ @@ -257,7 +249,6 @@ public void doNewMessage() { itsFrame.setItsMsg(msg); } - /** * Description of the Method */ @@ -268,7 +259,6 @@ public void sendMessage() { doNewMessage(); } - /** * Description of the Method * @@ -295,7 +285,6 @@ public void processIncomingMessage(ACLMessage msg) { } } - public void doReply() { ACLMessage msg = itsFrame.aclTreePanel.getCurrentACL(); if (msg == null) { @@ -306,7 +295,6 @@ public void doReply() { itsFrame.aclPanel.setItsMsg(reply); } - /** * Description of the Method */ @@ -334,7 +322,6 @@ protected void setup() { splash.setVisible(false); } - ACLMessage createRequestMessage(Agent sender, AID receiver, AgentAction what) { ACLMessage request = new ACLMessage(ACLMessage.REQUEST); request.setSender(sender.getAID()); @@ -358,7 +345,6 @@ ACLMessage createRequestMessage(Agent sender, AID receiver, AgentAction what) { return request; } - /** * Description of the Class * @@ -366,6 +352,11 @@ ACLMessage createRequestMessage(Agent sender, AID receiver, AgentAction what) { * @created May 21, 2002 */ private class SplashScreen extends JWindow { + GridBagLayout gridBagLayout1 = new GridBagLayout(); + JPanel jPanel1 = new JPanel(); + GridBagLayout gridBagLayout2 = new GridBagLayout(); + JLabel jLabel1 = new JLabel(); + JProgressBar theProgressBar = new JProgressBar(); /** * Constructor for the SplashScreen object */ @@ -387,7 +378,6 @@ public SplashScreen() { } } - /** * Sets the Progress attribute of the SplashScreen object * @@ -397,7 +387,6 @@ public void setProgress(int p) { theProgressBar.setValue(p); } - void jbInit() { this.getContentPane().setLayout(gridBagLayout1); this.getContentPane().setBackground(Color.white); @@ -428,23 +417,6 @@ public void focusLost(FocusEvent e) { } - - GridBagLayout gridBagLayout1 = new GridBagLayout(); - JPanel jPanel1 = new JPanel(); - GridBagLayout gridBagLayout2 = new GridBagLayout(); - JLabel jLabel1 = new JLabel(); - JProgressBar theProgressBar = new JProgressBar(); - } - - - boolean pingBehaviour = true; - - ImageIcon dummyIcon = - new ImageIcon(this.getClass().getResource("images/dummy.gif")); - - SplashScreen splash; - - TestAgentFrame itsFrame; } // ***EOF*** diff --git a/src/jade/tools/testagent/TestAgentFrame.java b/src/jade/tools/testagent/TestAgentFrame.java index 008c50d..df6495c 100644 --- a/src/jade/tools/testagent/TestAgentFrame.java +++ b/src/jade/tools/testagent/TestAgentFrame.java @@ -47,6 +47,78 @@ public class TestAgentFrame extends JFrame { + GridBagLayout gridBagLayout1 = new GridBagLayout(); + JSplitPane mainSplitPane = new JSplitPane(); + JMenuBar itsMenuBar = new JMenuBar(); + JMenu fileMenu = new JMenu(); + JMenuItem exitMenuItem = new JMenuItem(); + JMenu messagesMenu = new JMenu(); + JMenuItem helloWorldMenuItem = new JMenuItem(); + JMenuItem amsRegMenuItem = new JMenuItem(); + JMenuItem amsDeregMenuItem = new JMenuItem(); + JMenuItem amsSearchMenuItem = new JMenuItem(); + JMenuItem pingLausanneMenuItem = new JMenuItem(); + JMenuItem dfSearchMenuItem = new JMenuItem(); + JMenuItem dfDeregMenuItem = new JMenuItem(); + JMenuItem dfRegMenuItem = new JMenuItem(); + JMenu helpMenu = new JMenu(); + JMenuItem aboutMenuItem = new JMenuItem(); + JPanel leftPanel = new JPanel(); + JPanel rightPanel = new JPanel(); + GridBagLayout gridBagLayout2 = new GridBagLayout(); + GridBagLayout gridBagLayout3 = new GridBagLayout(); + JToolBar aclTreeToolBar = new JToolBar(); + JButton writeQueueButton = new JButton(); + JButton readQueueButton = new JButton(); + JButton openButton = new JButton(); + JButton sendButton = new JButton(); + JButton newButton = new JButton(); + JButton saveButton = new JButton(); + JToolBar messageToolBar = new JToolBar(); + JButton currentButton = new JButton(); + JButton replyButton = new JButton(); + JButton viewButton = new JButton(); + JButton deleteButton = new JButton(); + JButton statisticsButton = new JButton(); + JButton quitButton = new JButton(); + JMenuItem newMenuItem = new JMenuItem(); + JMenuItem loadMenuItem = new JMenuItem(); + JMenuItem saveMenuItem = new JMenuItem(); + JMenuItem sendMenuItem = new JMenuItem(); + JMenuItem templatesMenuItem = new JMenuItem(); + JMenu traceMenu = new JMenu(); + JMenuItem claerQueueMenuItem = new JMenuItem(); + JMenuItem currentMenuItem = new JMenuItem(); + JMenuItem replyMenuItem = new JMenuItem(); + JMenuItem deleteMenuItem = new JMenuItem(); + JMenuItem statisticsMenuItem = new JMenuItem(); + JMenuItem loadMsgMenuItem = new JMenuItem(); + JMenuItem saveMsgMenuItem = new JMenuItem(); + JMenuItem loadQMenuItem = new JMenuItem(); + JMenuItem saveQMenuItem = new JMenuItem(); + JButton systemButton = new JButton(); + JMenuItem systemOutMenuItem = new JMenuItem(); + JMenuItem currentToOutMenuItem = new JMenuItem(); + JMenu behaviourMenu = new JMenu(); + JRadioButtonMenuItem pingRadioButtonMenuItem = new JRadioButtonMenuItem(); + JMenuItem localPingMenuItem = new JMenuItem(); + ImageIcon newIcon; + ImageIcon openIcon; + ImageIcon saveIcon; + ImageIcon sendIcon; + ImageIcon readQueueIcon; + ImageIcon saveQueueIcon; + ImageIcon currentIcon; + ImageIcon replyIcon; + ImageIcon viewIcon; + ImageIcon deleteIcon; + ImageIcon statisticsIcon; + ImageIcon quitIcon; + ImageIcon systemIcon; + ACLPanel aclPanel; + TestAgent agent; + ACLTracePanel aclTreePanel; + Border border1; /** * Constructor for the TestAgentFrame object * @@ -68,7 +140,6 @@ public TestAgentFrame(TestAgent agent) { } } - /** * Gets the ItsMsg attribute of the TestAgentFrame object * @@ -78,6 +149,14 @@ public ACLMessage getItsMsg() { return aclPanel.getItsMsg(); } + /** + * Sets the ItsMsg attribute of the TestAgentFrame object + * + * @param msg The new ItsMsg value + */ + public void setItsMsg(ACLMessage msg) { + aclPanel.setItsMsg(msg); + } public void getImages() { @@ -114,17 +193,6 @@ public void getImages() { } - - /** - * Sets the ItsMsg attribute of the TestAgentFrame object - * - * @param msg The new ItsMsg value - */ - public void setItsMsg(ACLMessage msg) { - aclPanel.setItsMsg(msg); - } - - /** * Sets the FrameIcon attribute of the TestAgentFrame object * @@ -135,7 +203,6 @@ public void setFrameIcon(String iconpath) { setIconImage(image.getImage()); } - /** * Adds a feature to the MessageNode attribute of the TestAgentFrame object * @@ -146,7 +213,6 @@ public void addMessageNode(String direction, ACLMessage msg) { aclTreePanel.addMessageNode(direction, msg); } - /** * Description of the Method * @@ -156,7 +222,6 @@ void helloWorldMenuItem_actionPerformed(ActionEvent e) { agent.doHelloWorld(); } - /** * Description of the Method * @@ -166,7 +231,6 @@ void amsRegMenuItem_actionPerformed(ActionEvent e) { agent.doRegisterAMS(); } - /** * Description of the Method * @@ -176,7 +240,6 @@ void systemMenuItem_actionPerformed(ActionEvent e) { agent.doSystemOut(); } - /** * Description of the Method * @@ -186,7 +249,6 @@ void exitMenuItem_actionPerformed(ActionEvent e) { agent.doExit(); } - /** * Description of the Method * @@ -196,7 +258,6 @@ void newButton_actionPerformed(ActionEvent e) { agent.doNewMessage(); } - /** * Description of the Method * @@ -206,7 +267,6 @@ void sendButton_actionPerformed(ActionEvent e) { agent.sendMessage(); } - /** * Description of the Method * @@ -216,7 +276,6 @@ void pingLausanneMenuItem_actionPerformed(ActionEvent e) { agent.doLausannePing(); } - /** * Description of the Method * @@ -226,7 +285,6 @@ void amsDeregMenuItem_actionPerformed(ActionEvent e) { agent.doDeRegisterAMS(); } - /** * Description of the Method * @@ -236,37 +294,30 @@ void amsSearchMenuItem_actionPerformed(ActionEvent e) { agent.doSearchAMS(); } - void dfRegMenuItem_actionPerformed(ActionEvent e) { agent.doRegisterDF(); } - void dfDeregMenuItem_actionPerformed(ActionEvent e) { agent.doDeregisterDF(); } - void dfSearchMenuItem_actionPerformed(ActionEvent e) { agent.doSearchDF(); } - void aboutMenuItem_actionPerformed(ActionEvent e) { new AboutFrame().setVisible(true); } - void readQueueButton_actionPerformed(ActionEvent e) { this.aclTreePanel.loadQueue(); } - void writeQueueButton_actionPerformed(ActionEvent e) { this.aclTreePanel.saveQueue(); } - void currentButton_actionPerformed(ActionEvent e) { ACLMessage currentACL = this.aclTreePanel.getCurrentACL(); @@ -275,73 +326,59 @@ void currentButton_actionPerformed(ActionEvent e) { } } - void viewButton_actionPerformed(ActionEvent e) { this.aclTreePanel.doShowCurrentACL(); } - void deleteButton_actionPerformed(ActionEvent e) { this.aclTreePanel.deleteCurrent(); } - void statisticsButton_actionPerformed(ActionEvent e) { this.aclTreePanel.showStastistics(); } - void quitButton_actionPerformed(ActionEvent e) { agent.doDelete(); System.exit(1); } - void replyButton_actionPerformed(ActionEvent e) { agent.doReply(); } - void newMenuItem_actionPerformed(ActionEvent e) { agent.doNewMessage(); } - void loadMenuItem_actionPerformed(ActionEvent e) { this.aclPanel.loadACL(); } - void saveMenuItem_actionPerformed(ActionEvent e) { this.aclPanel.saveACL(); } - void sendMenuItem_actionPerformed(ActionEvent e) { agent.sendMessage(); } - void saveButton_actionPerformed(ActionEvent e) { this.aclPanel.saveACL(); } - void openButton_actionPerformed(ActionEvent e) { this.aclPanel.loadACL(); } - void saveQueueMenuItem_actionPerformed(ActionEvent e) { this.aclTreePanel.saveQueue(); } - void claerQueueMenuItem_actionPerformed(ActionEvent e) { this.aclTreePanel.clearACLModel(); } - void currentMenuItem_actionPerformed(ActionEvent e) { ACLMessage currentACL = this.aclTreePanel.getCurrentACL(); if (currentACL != null) { @@ -350,67 +387,54 @@ void currentMenuItem_actionPerformed(ActionEvent e) { } - void replyMenuItem_actionPerformed(ActionEvent e) { agent.doReply(); } - void deleteMenuItem_actionPerformed(ActionEvent e) { this.aclTreePanel.deleteCurrent(); } - void statisticsMenuItem_actionPerformed(ActionEvent e) { this.aclTreePanel.showStastistics(); } - void loadMsgMenuItem_actionPerformed(ActionEvent e) { this.aclPanel.loadACL(); } - void saveMsgMenuItem_actionPerformed(ActionEvent e) { this.aclPanel.saveACL(); } - void loadQMenuItem_actionPerformed(ActionEvent e) { this.aclTreePanel.loadQueue(); } - void saveQMenuItem_actionPerformed(ActionEvent e) { this.aclTreePanel.saveQueue(); } - void systemButton_actionPerformed(ActionEvent e) { this.aclTreePanel.doSystemOut(); } - void systemOutMenuItem_actionPerformed(ActionEvent e) { this.aclPanel.doSystemOut(); } - void currentToOutMenuItem_actionPerformed(ActionEvent e) { this.aclTreePanel.doSystemOut(); } - void pingRadioButtonMenuItem_stateChanged(ChangeEvent e) { agent.pingBehaviour = (pingRadioButtonMenuItem.isSelected()); } - void localPingMenuItem_actionPerformed(ActionEvent e) { agent.doLocalPing(); } - /** * Description of the Method * @@ -779,9 +803,19 @@ private void jbInit() throws Exception { mainSplitPane.setDividerLocation(200); } - private class AboutFrame extends JWindow { + GridBagLayout gridBagLayout1 = new GridBagLayout(); + ImageIcon acklinIcon = + new ImageIcon(getClass().getResource("images/acklinabout.gif")); + JPanel contentPanel = new JPanel(); + GridBagLayout gridBagLayout2 = new GridBagLayout(); + JLabel logoLabel = new JLabel(); + JLabel jLabel1 = new JLabel(); + JLabel jLabel2 = new JLabel(); + Border border1; + + public AboutFrame() { try { jbInit(); @@ -795,77 +829,62 @@ public AboutFrame() { } } - void logoLabel_mouseClicked(MouseEvent e) { this.setVisible(false); } - void jLabel3_mousePressed(MouseEvent e) { this.setVisible(false); } - void jLabel2_mouseClicked(MouseEvent e) { this.setVisible(false); } - void jLabel3_mouseClicked(MouseEvent e) { this.setVisible(false); } - void logoLabel_mouseEntered(MouseEvent e) { this.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); } - void logoLabel_mouseExited(MouseEvent e) { this.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } - void jLabel3_mouseEntered(MouseEvent e) { this.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); } - void jLabel3_mouseExited(MouseEvent e) { this.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } - void jLabel2_mouseEntered(MouseEvent e) { this.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); } - void jLabel2_mouseExited(MouseEvent e) { this.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } - void logoLabel_mousePressed(MouseEvent e) { } - void logoLabel_mouseReleased(MouseEvent e) { } - void jLabel2_mousePressed(MouseEvent e) { } - void jLabel2_mouseReleased(MouseEvent e) { } - private void jbInit() throws Exception { // this.setClosable(true); //this.setOpaque(false); @@ -924,96 +943,7 @@ public void mouseExited(MouseEvent e) { , GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(5, 0, 5, 0), 0, 0)); } - - GridBagLayout gridBagLayout1 = new GridBagLayout(); - - ImageIcon acklinIcon = - new ImageIcon(getClass().getResource("images/acklinabout.gif")); - JPanel contentPanel = new JPanel(); - GridBagLayout gridBagLayout2 = new GridBagLayout(); - JLabel logoLabel = new JLabel(); - JLabel jLabel1 = new JLabel(); - JLabel jLabel2 = new JLabel(); - Border border1; - } - - GridBagLayout gridBagLayout1 = new GridBagLayout(); - JSplitPane mainSplitPane = new JSplitPane(); - JMenuBar itsMenuBar = new JMenuBar(); - JMenu fileMenu = new JMenu(); - JMenuItem exitMenuItem = new JMenuItem(); - JMenu messagesMenu = new JMenu(); - JMenuItem helloWorldMenuItem = new JMenuItem(); - JMenuItem amsRegMenuItem = new JMenuItem(); - JMenuItem amsDeregMenuItem = new JMenuItem(); - JMenuItem amsSearchMenuItem = new JMenuItem(); - JMenuItem pingLausanneMenuItem = new JMenuItem(); - JMenuItem dfSearchMenuItem = new JMenuItem(); - JMenuItem dfDeregMenuItem = new JMenuItem(); - JMenuItem dfRegMenuItem = new JMenuItem(); - - JMenu helpMenu = new JMenu(); - JMenuItem aboutMenuItem = new JMenuItem(); - JPanel leftPanel = new JPanel(); - JPanel rightPanel = new JPanel(); - GridBagLayout gridBagLayout2 = new GridBagLayout(); - GridBagLayout gridBagLayout3 = new GridBagLayout(); - JToolBar aclTreeToolBar = new JToolBar(); - JButton writeQueueButton = new JButton(); - JButton readQueueButton = new JButton(); - JButton openButton = new JButton(); - JButton sendButton = new JButton(); - JButton newButton = new JButton(); - JButton saveButton = new JButton(); - JToolBar messageToolBar = new JToolBar(); - JButton currentButton = new JButton(); - JButton replyButton = new JButton(); - JButton viewButton = new JButton(); - JButton deleteButton = new JButton(); - JButton statisticsButton = new JButton(); - JButton quitButton = new JButton(); - JMenuItem newMenuItem = new JMenuItem(); - JMenuItem loadMenuItem = new JMenuItem(); - JMenuItem saveMenuItem = new JMenuItem(); - JMenuItem sendMenuItem = new JMenuItem(); - JMenuItem templatesMenuItem = new JMenuItem(); - JMenu traceMenu = new JMenu(); - JMenuItem claerQueueMenuItem = new JMenuItem(); - JMenuItem currentMenuItem = new JMenuItem(); - JMenuItem replyMenuItem = new JMenuItem(); - JMenuItem deleteMenuItem = new JMenuItem(); - JMenuItem statisticsMenuItem = new JMenuItem(); - JMenuItem loadMsgMenuItem = new JMenuItem(); - JMenuItem saveMsgMenuItem = new JMenuItem(); - JMenuItem loadQMenuItem = new JMenuItem(); - JMenuItem saveQMenuItem = new JMenuItem(); - JButton systemButton = new JButton(); - JMenuItem systemOutMenuItem = new JMenuItem(); - JMenuItem currentToOutMenuItem = new JMenuItem(); - JMenu behaviourMenu = new JMenu(); - JRadioButtonMenuItem pingRadioButtonMenuItem = new JRadioButtonMenuItem(); - JMenuItem localPingMenuItem = new JMenuItem(); - - ImageIcon newIcon; - ImageIcon openIcon; - ImageIcon saveIcon; - ImageIcon sendIcon; - ImageIcon readQueueIcon; - ImageIcon saveQueueIcon; - ImageIcon currentIcon; - ImageIcon replyIcon; - ImageIcon viewIcon; - ImageIcon deleteIcon; - ImageIcon statisticsIcon; - ImageIcon quitIcon; - ImageIcon systemIcon; - ACLPanel aclPanel; - - TestAgent agent; - ACLTracePanel aclTreePanel; - Border border1; - } // ***EOF*** diff --git a/src/jade/util/AccessControlList.java b/src/jade/util/AccessControlList.java index e66ccdd..2d53c37 100644 --- a/src/jade/util/AccessControlList.java +++ b/src/jade/util/AccessControlList.java @@ -95,16 +95,17 @@ public class AccessControlList { private static final Logger logger = Logger.getMyLogger(AccessControlList.class.getName()); + // Set black and white list + private String blackFileName = null; + private String whiteFileName = null; + // internal representation (optimized for speed) + private InternalACL black_iacl; + private InternalACL white_iacl; // constructor public AccessControlList() { } // end constructor - - // Set black and white list - private String blackFileName = null; - private String whiteFileName = null; - public void setBlack(String blackFileName) { this.blackFileName = blackFileName; refresh_black(); @@ -115,11 +116,6 @@ public void setWhite(String whiteFileName) { refresh_white(); } - // internal representation (optimized for speed) - private InternalACL black_iacl; - private InternalACL white_iacl; - - /** * A specific client is allowed if: *

  • it is not present into the black list, AND
  • diff --git a/src/jade/util/ClassFinder.java b/src/jade/util/ClassFinder.java index 15ca3e6..affda91 100644 --- a/src/jade/util/ClassFinder.java +++ b/src/jade/util/ClassFinder.java @@ -44,6 +44,16 @@ * @author Daniel Le Berre, Elliott Wade, Paolo Cancedda */ public class ClassFinder { + private final static FileFilter DIRECTORIES_ONLY = f -> f.exists() && f.isDirectory(); + private final static FileFilter CLASSES_ONLY = f -> { + if (f.exists() && f.isFile() && f.canRead()) + return f.getName().endsWith(".class"); + else + return false; + }; + private final static Comparator URL_COMPARATOR = Comparator.comparing(String::valueOf); + private final static Comparator CLASS_COMPARATOR = Comparator.comparing(String::valueOf); + private final boolean useClassPathLocations; private Class searchClass = null; private Map locations = new HashMap<>(); private Map, URL> results = new HashMap<>(); @@ -51,11 +61,6 @@ public class ClassFinder { private boolean working = false; private ClassFinderListener listener; private ClassFinderFilter filter; - private final boolean useClassPathLocations; - - public boolean isWorking() { - return working; - } public ClassFinder() { useClassPathLocations = true; @@ -73,6 +78,25 @@ public ClassFinder(String[] jarNames) { } } + private static String packageNameFor(JarEntry entry) { + if (entry == null) + return ""; + String s = entry.getName(); + if (s == null) + return ""; + if (s.length() == 0) + return s; + if (s.startsWith("/")) + s = s.substring(1); + if (s.endsWith("/")) + s = s.substring(0, s.length() - 1); + return s.replace('/', '.'); + } + + public boolean isWorking() { + return working; + } + /** * Rescan the classpath, cacheing all possible file locations. */ @@ -170,19 +194,6 @@ public final Map getClasspathLocations() { return map; } - private final static FileFilter DIRECTORIES_ONLY = f -> f.exists() && f.isDirectory(); - - private final static FileFilter CLASSES_ONLY = f -> { - if (f.exists() && f.isFile() && f.canRead()) - return f.getName().endsWith(".class"); - else - return false; - }; - - private final static Comparator URL_COMPARATOR = (u1, u2) -> String.valueOf(u1).compareTo(String.valueOf(u2)); - - private final static Comparator CLASS_COMPARATOR = (c1, c2) -> String.valueOf(c1).compareTo(String.valueOf(c2)); - private void include(String name, File file, Map map) { if (!file.exists()) return; @@ -256,21 +267,6 @@ private void includeJar(File file, Map map) { } } - private static String packageNameFor(JarEntry entry) { - if (entry == null) - return ""; - String s = entry.getName(); - if (s == null) - return ""; - if (s.length() == 0) - return s; - if (s.startsWith("/")) - s = s.substring(1); - if (s.endsWith("/")) - s = s.substring(0, s.length() - 1); - return s.replace('/', '.'); - } - private Vector> findSubclasses(Class superClass, Map locations) { Set> setOfClasses = new TreeSet<>(CLASS_COMPARATOR); diff --git a/src/jade/util/Event.java b/src/jade/util/Event.java index 2ec6c5e..49b2197 100644 --- a/src/jade/util/Event.java +++ b/src/jade/util/Event.java @@ -31,16 +31,17 @@ /** * This class represents a generic event carrying some information - * (accessible in the form of Object parameters) and - * provides support for synchronous processing through the + * (accessible in the form of Object parameters) and + * provides support for synchronous processing through the * waitUntilProcessed() and notifyProcessed() * methods. - * This class can be effectively used in combination with the - * InputQueue class to support a synchronization between an + * This class can be effectively used in combination with the + * InputQueue class to support a synchronization between an * external therad (posting events in the InputQueue) * and the Agent thread (processing the events). + * + * @author Giovanni Caire - TILab * @see InputQueue - * @author Giovanni Caire - TILab */ public class Event //#MIDP_EXCLUDE_BEGIN @@ -53,7 +54,7 @@ public class Event #MIDP_INCLUDE_END*/ /** - The type of this event. + * The type of this event. */ protected int type; @@ -64,10 +65,11 @@ public class Event /** - Construct an Event of a given type produced by - the indicated source - @param type The type of the event - @param source The source that generated the event + * Construct an Event of a given type produced by + * the indicated source + * + * @param type The type of the event + * @param source The source that generated the event */ public Event(int type, Object source) { //#MIDP_EXCLUDE_BEGIN @@ -80,13 +82,14 @@ public Event(int type, Object source) { } /** - Construct an Event of a given type produced by - the indicated source and carrying a given information. - @param type The type of the event - @param source The source that generated the event - @param info The information associated to the event. This value - is handled as the first parameter of the event and can be - accessed using the getParameter(0) method + * Construct an Event of a given type produced by + * the indicated source and carrying a given information. + * + * @param type The type of the event + * @param source The source that generated the event + * @param info The information associated to the event. This value + * is handled as the first parameter of the event and can be + * accessed using the getParameter(0) method */ public Event(int type, Object source, Object info) { this(type, source); @@ -100,16 +103,18 @@ public Object getSource() { #MIDP_INCLUDE_END*/ /** - Retrieve the type of this event. - @return the type of this Event object + * Retrieve the type of this event. + * + * @return the type of this Event object */ public int getType() { return type; } /** - Add a parameter to this Event object - @param obj The parameter to be added + * Add a parameter to this Event object + * + * @param obj The parameter to be added */ public void addParameter(Object obj) { if (param == null) { @@ -119,10 +124,11 @@ public void addParameter(Object obj) { } /** - Retrieve an element of the event parameter list. - @param index The index of the parameter to retrieve. - @return the index-th parameter of this Event - object. + * Retrieve an element of the event parameter list. + * + * @param index The index of the parameter to retrieve. + * @return the index-th parameter of this Event + * object. */ public Object getParameter(int index) { if (param == null) { @@ -133,22 +139,24 @@ public Object getParameter(int index) { } /** - Blocks the calling thread until the notifyProcessed() - method is called. - @return the result of the processing of this Event - object as set by the notifyProcessed() method. + * Blocks the calling thread until the notifyProcessed() + * method is called. + * + * @return the result of the processing of this Event + * object as set by the notifyProcessed() method. */ public synchronized Object waitUntilProcessed() throws InterruptedException { return waitUntilProcessed(0); } /** - Blocks the calling thread until the notifyProcessed() - method is called. - @return the result of the processing of this Event - object as set by the notifyProcessed() method. - @throws InterruptedException if the timeout expires or the Thread - executing this method is interrupted. + * Blocks the calling thread until the notifyProcessed() + * method is called. + * + * @return the result of the processing of this Event + * object as set by the notifyProcessed() method. + * @throws InterruptedException if the timeout expires or the Thread + * executing this method is interrupted. */ public synchronized Object waitUntilProcessed(long timeout) throws InterruptedException { while (!processed) { @@ -162,11 +170,12 @@ public synchronized Object waitUntilProcessed(long timeout) throws InterruptedEx } /** - Wakes up threads waiting for the processing of this Event - object within the waitUntilProcessed() method. - @param result The result of the processing. This value is passed - to the waked threads as the result of the waitUntilProcessed() - method. + * Wakes up threads waiting for the processing of this Event + * object within the waitUntilProcessed() method. + * + * @param result The result of the processing. This value is passed + * to the waked threads as the result of the waitUntilProcessed() + * method. */ public synchronized void notifyProcessed(Object result) { if (!processed) { @@ -177,7 +186,7 @@ public synchronized void notifyProcessed(Object result) { } /** - Reset the status of this Event + * Reset the status of this Event */ public synchronized void reset() { processed = false; @@ -190,8 +199,9 @@ public synchronized void reset() { //#MIDP_EXCLUDE_BEGIN /** - Reset the status of this Event - @deprecated Use reset() instead + * Reset the status of this Event + * + * @deprecated Use reset() instead */ public void resetProcessed() { reset(); diff --git a/src/jade/util/ExtendedProperties.java b/src/jade/util/ExtendedProperties.java index 04048c1..6036a86 100644 --- a/src/jade/util/ExtendedProperties.java +++ b/src/jade/util/ExtendedProperties.java @@ -51,22 +51,11 @@ */ public class ExtendedProperties extends Properties { public static final String IMPORT_KEY = "import"; - + private final Logger logger = Logger.getMyLogger(getClass().getName()); boolean CRState = false; Hashtable keyNames = new Hashtable<>(); // for detecting circular definitions Vector sortVector = null; // only used by sortedKeys - private final Logger logger = Logger.getMyLogger(getClass().getName()); - - /** - * For testing. Simply pass command line arguments to constructor then display - * all key=value pairs using sorted enumeration. - */ - public static void main(String[] args) { - ExtendedProperties prop = new ExtendedProperties(args); - prop.list(System.out); - } - /** * Construct empty property collection. */ @@ -84,6 +73,15 @@ public ExtendedProperties(String[] propesStr) { addProperties(propesStr); } + /** + * For testing. Simply pass command line arguments to constructor then display + * all key=value pairs using sorted enumeration. + */ + public static void main(String[] args) { + ExtendedProperties prop = new ExtendedProperties(args); + prop.list(System.out); + } + /** * Add properties from a specified InputStream. Properties * will be added to any existing collection. @@ -276,28 +274,25 @@ public synchronized ExtendedProperties extractSubset(String prefix) { */ public Object get(Object aKey) { Object value = null; - if (aKey instanceof String) { - String strKey = (String) aKey; - String testKey = strKey; + if (aKey instanceof String strKey) { // Try WITHOUT the '!' for sure - value = super.get(testKey); + value = super.get(strKey); if (value == null) { // Not found --> Try WITH the '!' for sure - value = super.get(testKey + "!"); + value = super.get(strKey + "!"); } - if (value != null && value instanceof String) { - String strValue = (String) value; + if (value instanceof String strValue) { // This synchronized block prevents a "Circular argument substitution key" error in case two threads // search for the same key in parallel synchronized (keyNames) { - if (keyNames.put(testKey, "x") != null) { // value doesn't matter + if (keyNames.put(strKey, "x") != null) { // value doesn't matter throw new PropertiesException("Circular argument substitution with key: " + aKey); } if (strValue.length() >= 4) { // shortest possible value: ${x} strValue = doSubstitutions(strValue); } - keyNames.remove(testKey); + keyNames.remove(strKey); } strValue = valueFilter(strKey, strValue); value = strValue; @@ -322,9 +317,8 @@ public Object put(Object aKey, Object aValue) { String actualKey = doSubstitutions((String) aKey); // aKey may have the form kkk or kkk!. In both cases if a property with key = kkk! exists throws an exception - String testKey = actualKey; - if (super.containsKey(testKey + "!")) { - throw new PropertiesException("Attempt to alter read only property:" + testKey); + if (super.containsKey(actualKey + "!")) { + throw new PropertiesException("Attempt to alter read only property:" + actualKey); } // If the key to be inserted is the "import" key, do not insert it, but add all properties @@ -583,7 +577,7 @@ public String doSubstitutions(String anInputString, boolean allowUndefined) { if (anInputString == null) { return null; } - StringBuffer result = new StringBuffer(); + StringBuilder result = new StringBuilder(); int si = 0; // source index int oi = 0; // opening index int ci = 0; // closing index @@ -687,7 +681,7 @@ protected void addFromReader(Reader reader) throws IOException { * @throws IOException if anything goes wrong. */ protected String getOneLine(Reader reader) throws IOException { - StringBuffer sb = null; + StringBuilder sb = null; String line = null; boolean continued; @@ -711,7 +705,7 @@ protected String getOneLine(Reader reader) throws IOException { line = line.substring(0, line.length() - 1); } if (sb == null) { - sb = new StringBuffer(); + sb = new StringBuilder(); } sb.append(line); } @@ -732,7 +726,7 @@ protected String getOneLine(Reader reader) throws IOException { * @throws IOException if anything goes wrong. */ protected String readLine(Reader aReader) throws IOException { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); while (true) { int result = aReader.read(); diff --git a/src/jade/util/InputQueue.java b/src/jade/util/InputQueue.java index 7b73cf4..5d5cf47 100644 --- a/src/jade/util/InputQueue.java +++ b/src/jade/util/InputQueue.java @@ -30,34 +30,36 @@ /** * This class implements a FIFO queue of objects that can be put and got - * in a synchronized way. This is useful when an external thread, + * in a synchronized way. This is useful when an external thread, * e.g. a GUI, has to communicate with an agent: The external thread * puts objects in the queue and the agent gets and processes them. * The queue can be associated to a Behaviour. This - * Behaviour will be restarted each time an object is inserted in the - * queue. - * This class can be effectively used in combination with the - * Event class to support a synchronization between the + * Behaviour will be restarted each time an object is inserted in the + * queue. + * This class can be effectively used in combination with the + * Event class to support a synchronization between the * external therad (posting the event in the InputQueue) * and the Agent thread (processing the event). + * + * @author Giovanni Caire - TILab * @see Event - * @author Giovanni Caire - TILab */ public class InputQueue { private final Vector queue = new Vector<>(); private Behaviour myManager; /** - Default constructor. + * Default constructor. */ public InputQueue() { } /** - Associate this InputQueue object with the indicated - Behaviour so that it will be restarted each time - a new object is inserted. - @param b The Behaviour to associate. + * Associate this InputQueue object with the indicated + * Behaviour so that it will be restarted each time + * a new object is inserted. + * + * @param b The Behaviour to associate. */ public synchronized void associate(Behaviour b) { @@ -70,9 +72,10 @@ public synchronized void associate(Behaviour b) { } /** - Insert an object into the queue. If there is a Behaviour - associated to this InputQueue it will be restarted. - @param obj The object to insert. + * Insert an object into the queue. If there is a Behaviour + * associated to this InputQueue it will be restarted. + * + * @param obj The object to insert. */ public synchronized void put(Object obj) { queue.addElement(obj); @@ -85,9 +88,10 @@ public synchronized void put(Object obj) { } /** - Extract the first object in the queue (if any). - @return The first object in the queue or null if - the queue is empty. + * Extract the first object in the queue (if any). + * + * @return The first object in the queue or null if + * the queue is empty. */ public synchronized Object get() { Object obj = null; @@ -99,7 +103,7 @@ public synchronized Object get() { } /** - Remove all elements from this queue. + * Remove all elements from this queue. */ public synchronized void clear() { queue.removeAllElements(); diff --git a/src/jade/util/Logger.java b/src/jade/util/Logger.java index eab3c4c..2848e0c 100644 --- a/src/jade/util/Logger.java +++ b/src/jade/util/Logger.java @@ -40,10 +40,10 @@ /** * This class provides a uniform API to produce logs - * over a set of different and device-dependent logging mechanisms. + * over a set of different and device-dependent logging mechanisms. * Different implementations of this class are - * provided according to the target environment (Java Standard Edition, PersonalJava or CDC, MIDP and Android), - * but all of them offer the same API. + * provided according to the target environment (Java Standard Edition, PersonalJava or CDC, MIDP and Android), + * but all of them offer the same API. *
    * See also this * tutorial @@ -59,7 +59,7 @@ * FINE
    * FINER
    * FINEST (lowest value) - *

    In addition, there is a level OFF that can be used to turn off logging, + *

    In addition, there is a level OFF that can be used to turn off logging, * and a level ALL that can be used to enable logging of all messages. *

    * Notice that re-definition of logging levels was necessary in order to allow @@ -85,31 +85,31 @@ * java -Djava.util.logging.config.file=mylogging.properties jade.Boot ... * *

    PersonaJava
    - * In the PJava implementation of the Logger class calls to the + * In the PJava implementation of the Logger class calls to the * log() method result in calls to System.out.println(). - * Alternatively it is possible to redirect logging printouts to a text file - * by setting the -jade_util_Logger_logfile option. Note that, - * in order to face resource limitations, it is not possible to redirect + * Alternatively it is possible to redirect logging printouts to a text file + * by setting the -jade_util_Logger_logfile option. Note that, + * in order to face resource limitations, it is not possible to redirect * logging printouts produced by different Logger objects to different files. * *

    MIDP
    - * In the MIDP implementation of the Logger class logging printouts + * In the MIDP implementation of the Logger class logging printouts * are redirected to a MIDP RecordStore so that they can be later viewed * by means of the jade.util.leap.OutputViewer MIDlet included * in the LEAP add-on.
    * *

    Android
    - * In the Android implementation of the Logger class logging printouts + * In the Android implementation of the Logger class logging printouts * are redirected to the Android logging system implemented by the android.util.Log * class.
    * *

    - * The default level for logging is set to INFO, all messages of higher level + * The default level for logging is set to INFO, all messages of higher level * will be logged by default. - * In MIDP, PJava and Android environments, the logging level for a Logger object + * In MIDP, PJava and Android environments, the logging level for a Logger object * registered with name x.y.z can be configured by setting the configuration option * x_y_z_loglevel to one of severe, warning, info, config, - * fine, finer, finest, all. See the LEAP user guide for details about + * fine, finer, finest, all. See the LEAP user guide for details about * how to set JADE configuration options in MIDP and PJava. * * @author Rosalba Bochicchio - TILAB @@ -153,7 +153,7 @@ public class Logger **/ public static final Level FINEST = Level.FINEST; /** - *ALL indicates that all messages should be logged. + * ALL indicates that all messages should be logged. **/ public static final Level ALL = Level.ALL; /** @@ -164,45 +164,24 @@ public class Logger //#ANDROID_EXCLUDE_BEGIN private static final Map wrappers = new HashMap<>(); + private static final PrintStream logStream = System.out; + //#ANDROID_EXCLUDE_END /** * Private method to construct a logger for a named subsystem. - * @param name A name for the logger - * @param resourceBundleName Name of ResourceBundle to be used for localizing messages for this logger. May be null if none of the messages require localization. + * + * @param name A name for the logger + * @param resourceBundleName Name of ResourceBundle to be used for localizing messages for this logger. May be null if none of the messages require localization. */ private Logger(String name, String resourceBundleName) { super(name, resourceBundleName); } - //#ANDROID_EXCLUDE_END - - ////////////////////////////////////////////// - // This section is for serialization purposes - ////////////////////////////////////////////// - @Serial - private Object writeReplace() throws ObjectStreamException { - return new DummyLogger(getName()); - } - - private static class DummyLogger implements Serializable { - private final String name; - - public DummyLogger(String n) { - name = n; - } - - @Serial - private Object readResolve() throws ObjectStreamException { - return getJADELogger(name); - } - } - ////////////////////////////////////////////// - - //#ANDROID_EXCLUDE_BEGIN /** - Find or create a logger for a named subsystem. - @param name The name of the logger. - @return the instance of the Logger. + * Find or create a logger for a named subsystem. + * + * @param name The name of the logger. + * @return the instance of the Logger. */ public synchronized static Logger getJADELogger(String name) { java.util.logging.LogManager mng = java.util.logging.LogManager.getLogManager(); @@ -218,6 +197,9 @@ public synchronized static Logger getJADELogger(String name) { return (Logger) lg; } + ////////////////////////////////////////////// + + //#ANDROID_EXCLUDE_BEGIN private static Logger getWrapper(java.util.logging.Logger lg) { Logger jadeLogger = wrappers.get(lg.getName()); @@ -228,40 +210,19 @@ private static Logger getWrapper(java.util.logging.Logger lg) { return jadeLogger; } - - /** - * Inner class LoggerWrapper - */ - private static class LoggerWrapper extends Logger { - private final java.util.logging.Logger realLogger; - - private LoggerWrapper(java.util.logging.Logger lg) { - super(lg.getName(), null); - realLogger = lg; - } - - public void log(LogRecord r) { - realLogger.log(r); - } - } - /** - Initialize the logging mechanism. - This method makes sense only in a PJAVA or MIDP environment, - but is available in J2SE too (where it does nothing) to provide - a uniform interface over the different Java environments. + * Initialize the logging mechanism. + * This method makes sense only in a PJAVA or MIDP environment, + * but is available in J2SE too (where it does nothing) to provide + * a uniform interface over the different Java environments. */ public static void initialize(Properties pp) { } - //#ANDROID_EXCLUDE_END - //#J2ME_EXCLUDE_END public static Logger getMyLogger(String name) { return getJADELogger(name); } - private static final PrintStream logStream = System.out; - public static void println(String log) { logStream.println(log); /*#MIDP_INCLUDE_BEGIN @@ -278,13 +239,52 @@ public static void println(String log) { t.printStackTrace(); theRecordStore = null; } - } + } #MIDP_INCLUDE_END*/ - + /*#ANDROID_INCLUDE_BEGIN android.util.Log.i("", log); #ANDROID_INCLUDE_END*/ } + //#ANDROID_EXCLUDE_END + //#J2ME_EXCLUDE_END + + ////////////////////////////////////////////// + // This section is for serialization purposes + ////////////////////////////////////////////// + @Serial + private Object writeReplace() throws ObjectStreamException { + return new DummyLogger(getName()); + } + + private static class DummyLogger implements Serializable { + private final String name; + + public DummyLogger(String n) { + name = n; + } + + @Serial + private Object readResolve() throws ObjectStreamException { + return getJADELogger(name); + } + } + + /** + * Inner class LoggerWrapper + */ + private static class LoggerWrapper extends Logger { + private final java.util.logging.Logger realLogger; + + private LoggerWrapper(java.util.logging.Logger lg) { + super(lg.getName(), null); + realLogger = lg; + } + + public void log(LogRecord r) { + realLogger.log(r); + } + } /*#J2ME_INCLUDE_BEGIN diff --git a/src/jade/util/ObjectManager.java b/src/jade/util/ObjectManager.java index 40d6364..1146937 100644 --- a/src/jade/util/ObjectManager.java +++ b/src/jade/util/ObjectManager.java @@ -24,13 +24,6 @@ public class ObjectManager { private static final Map> loaders = new HashMap<>(); - /** - * The interface to be implemented by classes that can be registered to load objects of a given type - */ - public interface Loader { - Object load(String className, Properties pp) throws ClassNotFoundException, IllegalAccessException, InstantiationException; - } - /** * Convert a class-name, possibly with attached properties, into a Properties object * The actual class-name will be available as the value of the CLASS_NAME property @@ -66,11 +59,7 @@ private static Properties getClassProperties(String str) { * @param loader The Loader instance. */ public synchronized static void addLoader(String type, Loader loader) { - List l = loaders.get(type); - if (l == null) { - l = new ArrayList<>(); - loaders.put(type, l); - } + List l = loaders.computeIfAbsent(type, k -> new ArrayList<>()); l.add(loader); } @@ -107,4 +96,11 @@ public synchronized static Object load(String extendedClassName, String type) th } return null; } + + /** + * The interface to be implemented by classes that can be registered to load objects of a given type + */ + public interface Loader { + Object load(String className, Properties pp) throws ClassNotFoundException, IllegalAccessException, InstantiationException; + } } diff --git a/src/jade/util/PerDayFileLogger.java b/src/jade/util/PerDayFileLogger.java index 1fade74..2f5fec7 100644 --- a/src/jade/util/PerDayFileLogger.java +++ b/src/jade/util/PerDayFileLogger.java @@ -35,23 +35,24 @@ import java.util.Date; /** - This class is an OutputStream whose output is stored in - in different files according to the day it is produced. - Existing files, if any, are not rewritten as output is appended - at the end of the file. - @author Giovanni Caire - TILab + * This class is an OutputStream whose output is stored in + * in different files according to the day it is produced. + * Existing files, if any, are not rewritten as output is appended + * at the end of the file. + * + * @author Giovanni Caire - TILab */ public class PerDayFileLogger extends PrintStream { private final static long DAY = 24 * 60 * 60 * 1000; - + private static final DateFormat df = new SimpleDateFormat("yyyyMMdd"); private final String file; private long dayCnt; - private static final DateFormat df = new SimpleDateFormat("yyyyMMdd"); /** - Create a new day-based logger. - @param file The name of the file to write logs to. - @throws IOException If some filesystem operation fails. + * Create a new day-based logger. + * + * @param file The name of the file to write logs to. + * @throws IOException If some filesystem operation fails. */ public PerDayFileLogger(String file) throws IOException { super(new FileOutputStream(file + "." + df.format(new Date()), true), true); @@ -73,9 +74,10 @@ private void checkDate() { } /** - Print a Java object to the proper file, replacing the file - every new day. - @param obj The Java object to print. + * Print a Java object to the proper file, replacing the file + * every new day. + * + * @param obj The Java object to print. */ public void print(Object obj) { checkDate(); @@ -83,9 +85,10 @@ public void print(Object obj) { } /** - Print a string to the proper file, replacing the file every new - day. - @param str The string to print. + * Print a string to the proper file, replacing the file every new + * day. + * + * @param str The string to print. */ public void print(String str) { checkDate(); @@ -93,8 +96,8 @@ public void print(String str) { } /** - Print a new line to the proper file, replacing the file every - new day. + * Print a new line to the proper file, replacing the file every + * new day. */ public void println() { checkDate(); @@ -102,9 +105,10 @@ public void println() { } /** - Print a Java object and a newline to the proper file, replacing - the file every new day. - @param obj The Java object to print. + * Print a Java object and a newline to the proper file, replacing + * the file every new day. + * + * @param obj The Java object to print. */ public void println(Object obj) { checkDate(); @@ -112,9 +116,10 @@ public void println(Object obj) { } /** - Print a string and a new line to the proper file, replacing the - file every new day. - @param str THe string to print. + * Print a string and a new line to the proper file, replacing the + * file every new day. + * + * @param str THe string to print. */ public void println(String str) { checkDate(); diff --git a/src/jade/util/PrintStreamSplitter.java b/src/jade/util/PrintStreamSplitter.java index bb738d0..d8b57b5 100644 --- a/src/jade/util/PrintStreamSplitter.java +++ b/src/jade/util/PrintStreamSplitter.java @@ -32,20 +32,22 @@ import java.io.PrintStream; /** - This class is an OutputStream whose output is duplicated and - forwarded to two different output streams. - @author Giovanni Caire - TILab + * This class is an OutputStream whose output is duplicated and + * forwarded to two different output streams. + * + * @author Giovanni Caire - TILab */ public class PrintStreamSplitter extends PrintStream { private final PrintStream s1; private final PrintStream s2; /** - Create a new stream that feeds the output to the two given - streams. - @param s1 The first stream to write to. - @param s2 The second stream to write to. - @throws IOException If some stream operation fails. + * Create a new stream that feeds the output to the two given + * streams. + * + * @param s1 The first stream to write to. + * @param s2 The second stream to write to. + * @throws IOException If some stream operation fails. */ public PrintStreamSplitter(PrintStream s1, PrintStream s2) throws IOException { super(new OutputStream() { @@ -58,8 +60,9 @@ public void write(int b) throws IOException { } /** - Print a Java object to the two streams. - @param obj The Java object to print. + * Print a Java object to the two streams. + * + * @param obj The Java object to print. */ public void print(Object obj) { s1.print(obj); @@ -67,8 +70,9 @@ public void print(Object obj) { } /** - Print a string to the two streams. - @param str The string to print. + * Print a string to the two streams. + * + * @param str The string to print. */ public void print(String str) { s1.print(str); @@ -76,7 +80,7 @@ public void print(String str) { } /** - Print a new line to the two streams. + * Print a new line to the two streams. */ public void println() { s1.println(); @@ -84,8 +88,9 @@ public void println() { } /** - Print a Java object and a new line to the two streams. - @param obj The Java object to print. + * Print a Java object and a new line to the two streams. + * + * @param obj The Java object to print. */ public void println(Object obj) { s1.println(obj); @@ -93,8 +98,9 @@ public void println(Object obj) { } /** - Print a string and a new line to the two streams. - @param str The string to print. + * Print a string and a new line to the two streams. + * + * @param str The string to print. */ public void println(String str) { s1.println(str); diff --git a/src/jade/util/RWLock.java b/src/jade/util/RWLock.java index 22eb76e..9f0f03f 100644 --- a/src/jade/util/RWLock.java +++ b/src/jade/util/RWLock.java @@ -27,41 +27,39 @@ //#APIDOC_EXCLUDE_FILE /** - * This class provides support for - * synchronizing threads acting on a generic resource in such a way that - * - If a thread is writing the resource no other thread can act on it + * This class provides support for + * synchronizing threads acting on a generic resource in such a way that + * - If a thread is writing the resource no other thread can act on it * in any way * - Several threads can read the resource at the same time * - If one or more threads are reading the resource no thread can write it - * @author Giovanni Caire - TILab + * + * @author Giovanni Caire - TILab */ public class RWLock { + private final Logger logger = Logger.getMyLogger(this.getClass().getName()); // The counter of threads currently reading the resource private int readersCnt = 0; - // The Thread currently writing the resource (there can only be // one such a therad at a given time) private Thread currentWriter = null; - // writeLock()/unlock() can be nested. This indicates the current // depth private int writeLockDepth = 0; - private final Logger logger = Logger.getMyLogger(this.getClass().getName()); - /** - Default constructor. + * Default constructor. */ public RWLock() { } /** - Acquire the protected resource with writing privileges. Only - one writer at a time can access the protected resource, and no - readers can access it at the same time. The locking is - recursive (i.e. the same thread can acquire the lock multiple - times, but must unlock it a matching number of times to - actually free the protected resource). + * Acquire the protected resource with writing privileges. Only + * one writer at a time can access the protected resource, and no + * readers can access it at the same time. The locking is + * recursive (i.e. the same thread can acquire the lock multiple + * times, but must unlock it a matching number of times to + * actually free the protected resource). */ public synchronized void writeLock() { Thread me = Thread.currentThread(); @@ -84,8 +82,8 @@ public synchronized void writeLock() { } /** - Release the protected resource, previously acquired with - writing privileges. + * Release the protected resource, previously acquired with + * writing privileges. */ public synchronized void writeUnlock() { if (Thread.currentThread() == currentWriter) { @@ -100,12 +98,12 @@ public synchronized void writeUnlock() { } /** - Acquire the protected resource with reading privileges. Many - readers can access the protected resource at the same time, but - no writer can access it while at least one reader is - present. The locking is recursive (i.e. the same thread can - acquire the lock multiple times, but must unlock it a matching - number of times to actually free the protected resource). + * Acquire the protected resource with reading privileges. Many + * readers can access the protected resource at the same time, but + * no writer can access it while at least one reader is + * present. The locking is recursive (i.e. the same thread can + * acquire the lock multiple times, but must unlock it a matching + * number of times to actually free the protected resource). */ public synchronized void readLock() { while (currentWriter != null) { @@ -122,8 +120,8 @@ public synchronized void readLock() { /** - Release the protected resource, previously acquired with - reading privileges. + * Release the protected resource, previously acquired with + * reading privileges. */ public synchronized void readUnlock() { readersCnt--; @@ -135,23 +133,23 @@ public synchronized void readUnlock() { } /** - This placeholder method is called every time a thread actually - acquires the protected resource with writing privileges (this - means that, in case of multiple recursive locking by the same - thread, this method is called only the first time). Subclasses - can exploit this to transparently trigger a resource - acquisition prolog. + * This placeholder method is called every time a thread actually + * acquires the protected resource with writing privileges (this + * means that, in case of multiple recursive locking by the same + * thread, this method is called only the first time). Subclasses + * can exploit this to transparently trigger a resource + * acquisition prolog. */ protected void onWriteStart() { } /** - This placeholder method is called every time a thread actually - releases the protected resource with writing privileges (this - means that, in case of multiple recursive unlocking by the same - thread, this method is called only the last time). Subclasses - can exploit this to transparently trigger a resource release - epilog. + * This placeholder method is called every time a thread actually + * releases the protected resource with writing privileges (this + * means that, in case of multiple recursive unlocking by the same + * thread, this method is called only the last time). Subclasses + * can exploit this to transparently trigger a resource release + * epilog. */ protected void onWriteEnd() { } diff --git a/src/jade/util/ThreadDumpManager.java b/src/jade/util/ThreadDumpManager.java index 69d307b..762a47b 100644 --- a/src/jade/util/ThreadDumpManager.java +++ b/src/jade/util/ThreadDumpManager.java @@ -10,7 +10,7 @@ public class ThreadDumpManager { public static String dumpAllThreads() { ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); java.util.Map allStackTraces = Thread.getAllStackTraces(); Set threads = allStackTraces.keySet(); for (Thread thread : threads) { @@ -36,7 +36,7 @@ public static String dumpThread(String prefix, Thread t) { } public static String dumpThread(String prefix, Thread t, ThreadInfo threadInfo) { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); sb.append(prefix).append("\"").append(t.getName()).append("\""); if (t.isDaemon()) { sb.append(" daemon"); diff --git a/src/jade/util/Toolkit.java b/src/jade/util/Toolkit.java index dc449af..369ce60 100644 --- a/src/jade/util/Toolkit.java +++ b/src/jade/util/Toolkit.java @@ -50,7 +50,7 @@ public static String substituteParameters(String expression, Properties paramete } // Expression is != null and parameters is NOT empty --> Do the substitution - StringBuffer sbuf = new StringBuffer(); + StringBuilder sbuf = new StringBuilder(); int position = 0; while (true) { int paramStart = expression.indexOf(startDelim, position); diff --git a/src/jade/util/TransportAddressWrapper.java b/src/jade/util/TransportAddressWrapper.java index 0c75d03..d2a72b7 100644 --- a/src/jade/util/TransportAddressWrapper.java +++ b/src/jade/util/TransportAddressWrapper.java @@ -56,8 +56,7 @@ public boolean equals(Object obj) { } TransportAddress otherTA = null; - if (obj instanceof TransportAddressWrapper) { - TransportAddressWrapper taw = (TransportAddressWrapper) obj; + if (obj instanceof TransportAddressWrapper taw) { otherTA = taw.getAddress(); } else if (obj instanceof TransportAddress) { otherTA = (TransportAddress) obj; diff --git a/src/jade/util/leap/RoundList.java b/src/jade/util/leap/RoundList.java index 70af1fb..65d39e5 100644 --- a/src/jade/util/leap/RoundList.java +++ b/src/jade/util/leap/RoundList.java @@ -36,26 +36,59 @@ import java.util.NoSuchElementException; /** - * Implementation of a RoundList with get/insert methods relative + * Implementation of a RoundList with get/insert methods relative * to the current element - * @author Fabio Bellifemine - TILab + * + * @author Fabio Bellifemine - TILab * @version $Date: 2005-11-03 11:40:16 +0100 (gio, 03 nov 2005) $ $Revision: 5810 $ **/ public class RoundList implements Serializable { - private int cur = -1; private final LinkedList l = new LinkedList<>(); + private int cur = -1; /** - Default constructor. + * Default constructor. */ public RoundList() { } - /** Inserts the element before the current element. + /** + * Just for Debugging this implementation. + **/ + public static void main(String[] args) { + RoundList r = new RoundList(); + + while (true) { + try { + BufferedReader buff = new BufferedReader(new InputStreamReader(System.in)); + System.out.println("ENTER Operation add|get|remove"); + String op = buff.readLine(); + if (op.toLowerCase().startsWith("a")) { + System.out.println("ENTER Element to add"); + String el = buff.readLine(); + r.add(el); + } else if (op.toLowerCase().startsWith("g")) { + System.out.println("Got Element: " + r.get()); + } else if (op.toLowerCase().startsWith("r")) { + System.out.println("ENTER Element to remove"); + String el = buff.readLine(); + if (!r.remove(el)) + System.out.println("Element not found"); + } + System.out.println("The RoundList is now:" + r); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + + /** + * Inserts the element before the current element. * If the list was empty, the inserted element becomes also the current element. * Note that this implementation uses a LinkedList * and therefore it is not synchronized. + * * @param element the element to insert * @return true (as per the general contract of Collection.add). **/ @@ -72,13 +105,15 @@ public boolean add(Object element) { return true; } - /** Returns the current element in the list and updates the pointer + /** + * Returns the current element in the list and updates the pointer * such that the current becomes the * next element in the list. *
    Notice that if the list contains just 1 element each call to this method will return * the same element. *
    Take care in avoiding infinite loops in calling this method. It * must be called no more than size() times + * * @throws NoSuchElementException if the list is empty **/ public Object get() throws NoSuchElementException { @@ -91,13 +126,14 @@ public Object get() throws NoSuchElementException { return val; } - - /** Removes the first occurrence of the specified element in this list - * and updates the pointer to the current element. - * If the list does not contain the element, it is unchanged. - * More formally, removes the element with the lowest index i such that + /** + * Removes the first occurrence of the specified element in this list + * and updates the pointer to the current element. + * If the list does not contain the element, it is unchanged. + * More formally, removes the element with the lowest index i such that * (element==null ? get(i)==null : element.equals(get(i))) * (if such an element exists). + * * @param element the element to be removed from this list, if present. * @return true if the list contained the specified element. **/ @@ -120,10 +156,11 @@ public boolean remove(Object element) { return true; } - - /** Returns true if this list contains the specified element. + /** + * Returns true if this list contains the specified element. * More formally, returns true if and only if this list contains at least * one element e such that (element==null ? e==null : element.equals(e)). + * * @param element whose presence in this list is to be tested. * @return true if this list contains the specified element. **/ @@ -131,15 +168,18 @@ public boolean contains(Object element) { return l.contains(element); } - - /** Returns the number of elements in this list. + /** + * Returns the number of elements in this list. + * * @return the number of elements in this list. **/ public int size() { return l.size(); } - /** Returns an Iterator over the elements in this list. + /** + * Returns an Iterator over the elements in this list. + * * @return an Iterator over the elements in this list. **/ public Iterator iterator() { @@ -150,12 +190,17 @@ public Object[] toArray() { return l.toArray(); } - /** Returns a string representation of this collection. + + //#MIDP_EXCLUDE_BEGIN + + /** + * Returns a string representation of this collection. * The string representation consists of a list of the collection's elements * in the order they are returned by its get() method, * enclosed in square brackets ("[]"). * Adjacent elements are separated by the characters ", " (comma and space). * Elements are converted to strings as by String.valueOf(Object). + * * @return a String representation of this list **/ public String toString() { @@ -167,39 +212,6 @@ public String toString() { str.append("]"); return str.toString(); } - - - //#MIDP_EXCLUDE_BEGIN - - /** - * Just for Debugging this implementation. - **/ - public static void main(String[] args) { - RoundList r = new RoundList(); - - while (true) { - try { - BufferedReader buff = new BufferedReader(new InputStreamReader(System.in)); - System.out.println("ENTER Operation add|get|remove"); - String op = buff.readLine(); - if (op.toLowerCase().startsWith("a")) { - System.out.println("ENTER Element to add"); - String el = buff.readLine(); - r.add(el); - } else if (op.toLowerCase().startsWith("g")) { - System.out.println("Got Element: " + r.get()); - } else if (op.toLowerCase().startsWith("r")) { - System.out.println("ENTER Element to remove"); - String el = buff.readLine(); - if (!r.remove(el)) - System.out.println("Element not found"); - } - System.out.println("The RoundList is now:" + r); - } catch (Exception e) { - e.printStackTrace(); - } - } - } //#MIDP_EXCLUDE_END diff --git a/src/jade/wrapper/AgentState.java b/src/jade/wrapper/AgentState.java index 48036dd..488a77c 100644 --- a/src/jade/wrapper/AgentState.java +++ b/src/jade/wrapper/AgentState.java @@ -29,8 +29,14 @@ * @author David Bell, Dick Cowan: Hewlett-Packard */ public class AgentState extends StateBase { + public static final int cAGENT_STATE_INITIATED = 1; + public static final int cAGENT_STATE_ACTIVE = 2; + public static final int cAGENT_STATE_IDLE = 3; + public static final int cAGENT_STATE_SUSPENDED = 4; + public static final int cAGENT_STATE_WAITING = 5; + public static final int cAGENT_STATE_DELETED = 6; + public static final int cAGENT_STATE_TRANSIT = 7; static final int LOWEST_STATE = 1; - /** * An array of string names, one for each of the valid state this object * can represent. This array MUST be initialized before the other static @@ -45,15 +51,6 @@ public class AgentState extends StateBase { "Deleted", // 6 "Transit" // 7 }; - - public static final int cAGENT_STATE_INITIATED = 1; - public static final int cAGENT_STATE_ACTIVE = 2; - public static final int cAGENT_STATE_IDLE = 3; - public static final int cAGENT_STATE_SUSPENDED = 4; - public static final int cAGENT_STATE_WAITING = 5; - public static final int cAGENT_STATE_DELETED = 6; - public static final int cAGENT_STATE_TRANSIT = 7; - static final State AGENT_STATE_INITIATED = new AgentState(cAGENT_STATE_INITIATED); static final State AGENT_STATE_ACTIVE = new AgentState(cAGENT_STATE_ACTIVE); static final State AGENT_STATE_IDLE = new AgentState(cAGENT_STATE_IDLE); diff --git a/src/jade/wrapper/ContainerController.java b/src/jade/wrapper/ContainerController.java index 0593186..b14f66b 100644 --- a/src/jade/wrapper/ContainerController.java +++ b/src/jade/wrapper/ContainerController.java @@ -45,12 +45,11 @@ */ public class ContainerController { + protected PlatformController myPlatformController; private AgentContainer myImpl; private ContainerProxy myProxy; private String myPlatformName; - protected PlatformController myPlatformController; - /** * This constructor requires a concrete * implementation of a JADE agent container, which cannot be diff --git a/src/jade/wrapper/PlatformController.java b/src/jade/wrapper/PlatformController.java index 5982eab..297bf06 100644 --- a/src/jade/wrapper/PlatformController.java +++ b/src/jade/wrapper/PlatformController.java @@ -34,41 +34,6 @@ * @author David Bell, Dick Cowan: Hewlett-Packard */ public interface PlatformController { - /** - * Inner callback interface to receive platform events. - */ - interface Listener extends EventListener { - /** - * Called when an agent is born. EventObject source is AgentController. - */ - void bornAgent(PlatformEvent anEvent); - - /** - * Called when an agent dies. PlatformEvent source is AgentController. - */ - void deadAgent(PlatformEvent anEvent); - - /** - * Called when the platform is started. PlatformEvent source is PlatformController. - */ - void startedPlatform(PlatformEvent anEvent); - - /** - * Called when the platform is suspended. PlatformEvent source is PlatformController. - */ - void suspendedPlatform(PlatformEvent anEvent); - - /** - * Called when the platform is activated. PlatformEvent source is PlatformController. - */ - void resumedPlatform(PlatformEvent anEvent); - - /** - * Called when the platform is killed (destroyed). PlatformEvent source is PlatformController. - */ - void killedPlatform(PlatformEvent anEvent); - } - /** * Get the name of the platform. * @@ -149,5 +114,40 @@ AgentController createNewAgent(String nickName, String className, */ void removePlatformListener(Listener aListener) throws ControllerException; + /** + * Inner callback interface to receive platform events. + */ + interface Listener extends EventListener { + /** + * Called when an agent is born. EventObject source is AgentController. + */ + void bornAgent(PlatformEvent anEvent); + + /** + * Called when an agent dies. PlatformEvent source is AgentController. + */ + void deadAgent(PlatformEvent anEvent); + + /** + * Called when the platform is started. PlatformEvent source is PlatformController. + */ + void startedPlatform(PlatformEvent anEvent); + + /** + * Called when the platform is suspended. PlatformEvent source is PlatformController. + */ + void suspendedPlatform(PlatformEvent anEvent); + + /** + * Called when the platform is activated. PlatformEvent source is PlatformController. + */ + void resumedPlatform(PlatformEvent anEvent); + + /** + * Called when the platform is killed (destroyed). PlatformEvent source is PlatformController. + */ + void killedPlatform(PlatformEvent anEvent); + } + } diff --git a/src/jade/wrapper/PlatformState.java b/src/jade/wrapper/PlatformState.java index 8aa2fac..281c8f3 100644 --- a/src/jade/wrapper/PlatformState.java +++ b/src/jade/wrapper/PlatformState.java @@ -29,8 +29,17 @@ * @author David Bell, Dick Cowan: Hewlett-Packard */ public class PlatformState extends StateBase { + public static final int cPLATFORM_STATE_VOID = 0; + public static final int cPLATFORM_STATE_INITIALIZING = 1; + public static final int cPLATFORM_STATE_INITIALIZED = 2; + public static final int cPLATFORM_STATE_STARTING = 3; + public static final int cPLATFORM_STATE_READY = 4; + public static final int cPLATFORM_STATE_SUSPENDING = 5; + public static final int cPLATFORM_STATE_SUSPENDED = 6; + public static final int cPLATFORM_STATE_KILLING = 7; + public static final int cPLATFORM_STATE_KILLED = 8; + public static final int cPLATFORM_STATE_FAILED = 9; static final int LOWEST_STATE = 0; - /** * An array of string names, one for each of the valid state this object * can represent. This array MUST be initialized before the other static @@ -48,18 +57,6 @@ public class PlatformState extends StateBase { "Killed", // 8 "Failed" // 9 }; - - public static final int cPLATFORM_STATE_VOID = 0; - public static final int cPLATFORM_STATE_INITIALIZING = 1; - public static final int cPLATFORM_STATE_INITIALIZED = 2; - public static final int cPLATFORM_STATE_STARTING = 3; - public static final int cPLATFORM_STATE_READY = 4; - public static final int cPLATFORM_STATE_SUSPENDING = 5; - public static final int cPLATFORM_STATE_SUSPENDED = 6; - public static final int cPLATFORM_STATE_KILLING = 7; - public static final int cPLATFORM_STATE_KILLED = 8; - public static final int cPLATFORM_STATE_FAILED = 9; - static final State PLATFORM_STATE_VOID = new PlatformState(cPLATFORM_STATE_VOID); static final State PLATFORM_STATE_INITIALIZING = new PlatformState(cPLATFORM_STATE_INITIALIZING); static final State PLATFORM_STATE_INITIALIZED = new PlatformState(cPLATFORM_STATE_INITIALIZED); diff --git a/src/jade/wrapper/gateway/DynamicJadeGateway.java b/src/jade/wrapper/gateway/DynamicJadeGateway.java index 95aa404..e55bfdf 100644 --- a/src/jade/wrapper/gateway/DynamicJadeGateway.java +++ b/src/jade/wrapper/gateway/DynamicJadeGateway.java @@ -22,24 +22,20 @@ public class DynamicJadeGateway { static final int UNKNOWN = -1; static final int ACTIVE = 1; static final int NOT_ACTIVE = 2; - + private static final Logger myLogger = Logger.getMyLogger(DynamicJadeGateway.class.getName()); + //#DOTNET_EXCLUDE_BEGIN + private final List listeners = new ArrayList<>(); ContainerController myContainer = null; AgentController myAgent = null; String agentType = GatewayAgent.class.getName(); String agentName = null; // jade profile properties ProfileImpl profile; - private Properties jadeProps; Object[] agentArguments; - int gatewayAgentState = UNKNOWN; - //#DOTNET_EXCLUDE_BEGIN - private final List listeners = new ArrayList<>(); - private volatile GatewayListener[] listenersArray = new GatewayListener[0]; + private Properties jadeProps; //#DOTNET_EXCLUDE_END - - private static final Logger myLogger = Logger.getMyLogger(DynamicJadeGateway.class.getName()); - + private volatile GatewayListener[] listenersArray = new GatewayListener[0]; /** * Searches for the property with the specified key in the JADE Platform Profile. @@ -63,7 +59,7 @@ public final String getProfileProperty(String key, String defaultValue) { * is called by the executor agent) * * @throws StaleProxyException if the method was not able to execute the Command - * see AgentController#putO2AObject(Object, boolean) + * see AgentController#putO2AObject(Object, boolean) **/ public final void execute(Object command) throws ControllerException, InterruptedException { execute(command, 0); @@ -80,7 +76,7 @@ public final void execute(Object command) throws ControllerException, Interrupte * @throws InterruptedException if the timeout expires or the Thread * executing this method is interrupted. * @throws StaleProxyException if the method was not able to execute the Command - * see AgentController#putO2AObject(Object, boolean) + * see AgentController#putO2AObject(Object, boolean) **/ public final void execute(Object command, long timeout) throws ControllerException, InterruptedException { Event e = null; diff --git a/src/jade/wrapper/gateway/GatewayAgent.java b/src/jade/wrapper/gateway/GatewayAgent.java index ea38eae..9ef5ba7 100644 --- a/src/jade/wrapper/gateway/GatewayAgent.java +++ b/src/jade/wrapper/gateway/GatewayAgent.java @@ -24,9 +24,14 @@ **/ public class GatewayAgent extends Agent { + private final Logger myLogger = Logger.getMyLogger(this.getClass().getName()); private GatewayBehaviour myB = null; private GatewayListener listener; - private final Logger myLogger = Logger.getMyLogger(this.getClass().getName()); + + public GatewayAgent() { + // enable object2agent communication with queue of infinite length + setEnabledO2ACommunication(true, 0); + } /** * subclasses may implement this method. @@ -61,7 +66,6 @@ public void action() { } } - /** * notify that the command has been processed and remove the command from the queue * @@ -71,11 +75,6 @@ final public void releaseCommand(Object command) { myB.releaseCommand(command); } - public GatewayAgent() { - // enable object2agent communication with queue of infinite length - setEnabledO2ACommunication(true, 0); - } - /* * Those classes that extends this setup method of the GatewayAgent * MUST absolutely call super.setup() otherwise this diff --git a/src/jade/wrapper/gateway/JadeGateway.java b/src/jade/wrapper/gateway/JadeGateway.java index c47765a..c771903 100644 --- a/src/jade/wrapper/gateway/JadeGateway.java +++ b/src/jade/wrapper/gateway/JadeGateway.java @@ -54,6 +54,10 @@ public class JadeGateway { private static boolean splitContainer; //#DOTNET_EXCLUDE_END + // Private constructor to avoid creating instances of the JadeGateway class directly + private JadeGateway() { + } + private synchronized static DynamicJadeGateway getGateway() { if (jadeGateway == null) { //#DOTNET_EXCLUDE_BEGIN @@ -92,7 +96,7 @@ public final static String getProfileProperty(String key, String defaultValue) { * is called by the executor agent) * * @throws StaleProxyException if the method was not able to execute the Command - * see jade.wrapper.AgentController#putO2AObject(Object, boolean) + * see jade.wrapper.AgentController#putO2AObject(Object, boolean) **/ public final static void execute(Object command) throws ControllerException, InterruptedException { getGateway().execute(command); @@ -109,7 +113,7 @@ public final static void execute(Object command) throws ControllerException, Int * @throws InterruptedException if the timeout expires or the Thread * executing this method is interrupted. * @throws StaleProxyException if the method was not able to execute the Command - * see jade.wrapper.AgentController#putO2AObject(Object, boolean) + * see jade.wrapper.AgentController#putO2AObject(Object, boolean) **/ public final static void execute(Object command, long timeout) throws ControllerException, InterruptedException { getGateway().execute(command, timeout); @@ -177,18 +181,14 @@ public final static boolean isGatewayActive() { public static void addListener(GatewayListener l) { getGateway().addListener(l); } - - public void removeListener(GatewayListener l) { - getGateway().removeListener(l); - } //#DOTNET_EXCLUDE_END public static final DynamicJadeGateway getDefaultGateway() { return getGateway(); } - // Private constructor to avoid creating instances of the JadeGateway class directly - private JadeGateway() { + public void removeListener(GatewayListener l) { + getGateway().removeListener(l); } }