Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package jason.infra.jade;
  
  import  jade.core.AID;
  import  jade.core.behaviours.Behaviour;
  import  jade.core.behaviours.CyclicBehaviour;
  import  jade.domain.DFService;
  import  jade.domain.FIPAException;
  import  jade.domain.FIPAAgentManagement.DFAgentDescription;
  import  jade.domain.FIPAAgentManagement.ServiceDescription;
 import  jade.lang.acl.ACLMessage;
 import  jade.lang.acl.MessageTemplate;
 
 import java.io.File;
 
 
 import  c4jason.CartagoEnvironment;


Implementation of the Jade Architecture to run Jason agents

Author(s):
Jomi
 
 public class JadeAgArch extends JadeAg {

    
name of the "jason agent" service in DF
 
     public  static String dfName = "j_agent";
     
     private static final long serialVersionUID = 1L;
    
     protected JasonBridgeArch jasonBridgeAgArch;
 
     private boolean enterInSleepMode = false;
 
     AID controllerAID  = new AID(., AID.ISLOCALNAME);
 
     Behaviour tsBehaviour;
     
     // 
     // Jade Methods
     // ------------
     //
 
     @SuppressWarnings("serial")
     @Override
     protected void setup() {
         RunCentralisedMAS.setupLogger();
          = jade.util.Logger.getMyLogger(this.getClass().getName() + "." + getLocalName());
         .info("starting "+getLocalName());
         try {
     
             AgentParameters ap = parseParameters();
             if (ap != null) {
                  = new JasonBridgeArch(this);
                 .init(ap);
                 
                 if (.getTS().getSettings().verbose() >= 0)
                     .setLevel(.getTS().getSettings().logLevel());
         
                 registerAgInDF();
             
                  = new JasonTSReasoner();
                 addBehaviour();
                 
                 .fine("Created from source "+ap.asSource);
             }
         } catch (Exception e) {
             .log(.,"Error creating JADE architecture.",e);
         }
     }
 
     /*
     @Override
     protected void afterMove() {
         super.afterMove();
     }
     */
     
     void enterInSleepMode() {
          = true;        
     }
     void wakeUp() {
         .restart();
     }
     
     protected AgentParameters parseParameters() throws ParseExceptionIOException {
        Object[] args = getArguments();
        if (args == null || args.length == 0) {
            .info("No AgentSpeak source informed!");
            return null;
        }
        // read arguments
        // if [0] is an instance of AgentParameters
        //    read parameters from [0] 
        // else if [0] is j-project 
        //    read all parameters form [1] (including aslSource and directives)
        //    create the agent indicated by [2]              
        // else
        //    [0] is the file with AS source for the agent
        //    arch <arch class>
        //    ag <agent class>
        //    bb < belief base class >
        //    option < options >
        if (args[0] instanceof AgentParameters) {
            return (AgentParameters)args[0];
        } else if (args[0].toString().equals("j-project")) { // load parameters from .mas2j
            if (args.length != 3) {
                .log(."To start agents from .mas2j file, you have to provide as parameters: (j-project <file.mas2j> <nameofagent in mas2j>)");
                return null;
            }
            jason.mas2j.parser.mas2j parser = new jason.mas2j.parser.mas2j(new FileReader(args[1].toString())); 
            MAS2JProject project = parser.mas();
            project.setupDefault();
            project.registerDirectives();
            ((Include)DirectiveProcessor.getDirective("include")).setSourcePath(project.getSourcePaths());
            
            AgentParameters ap = project.getAg(args[2].toString());
            if (ap == null) {
                .log(."There is no agent '"+args[2]+"' in project '"+args[1]+"'.");
            } else {    
                ap.fixSrc(project.getSourcePaths(), null);
                //if (ap.qty > 1)
                //    logger.warning("Ignoring quantity of agents from mas2j, jade arch creates only ONE agent.");
            }
            
            // The case CARTAGO+JADE
            if (isCartagoJadeCase(project)) {
                startCartagoNode(project.getEnvClass().getParametersArray());           
            }
            return ap;
            
        } else { // load parameters from shell
            AgentParameters ap = new AgentParameters();
            ap.asSource = new File(args[0].toString());
        
            int i=1;
            while (i < args.length) {                
                if (args[i].toString().equals("arch")) {
                    i++;
                    ap.addArchClass(args[i].toString());
                } else if (args[i].toString().equals("ag")) {
                    i++;
                    ap.agClass = new ClassParameters(args[i].toString());
                }
                i++;
            }
            return ap;
        }
    }
    
    public static boolean isCartagoJadeCase(MAS2JProject project) {
        return 
            project.getEnvClass() != null && 
            project.getEnvClass().getClassName().equals(CartagoEnvironment.class.getName()) && 
            project.isJade();
    }
    
    private static boolean cartagoStarted = false;
    public static synchronized void startCartagoNode(String[] args) {
        if (!) {
            ..print("Starting cartago node....");
            CartagoEnvironment env = new CartagoEnvironment();
            env.init(args);
            ..println("ok.");
        }
         = true;
    }
    
    private void registerAgInDF() {
        // DF register
        DFAgentDescription dfa = new DFAgentDescription();
        dfa.setName(getAID());
        ServiceDescription vc = new ServiceDescription();
        vc.setType("jason");
        vc.setName();
        dfa.addServices(vc);
        try {
            DFService.register(this,dfa);
        } catch (FIPAException e) {
            try {
                DFService.deregister(this);
                DFService.register(this,dfa);
            } catch (Exception ex) {
                .log(."Error registering agent in DF"e);
                .log(."Error unregistering agent in DF"ex);
            }
        }
    }
    class JasonTSReasoner extends CyclicBehaviour {
        public void action() {
            if (.getSettings().isSync()) {
                if (processExecutionControlOntologyMsg()) {
                    // execute a cycle in sync mode
                    .reasoningCycle();
                    boolean isBreakPoint = false;
                    try {
                        isBreakPoint = .getC().getSelectedOption().getPlan().hasBreakpoint();
                        if (.isLoggable(.)) .fine("Informing controller that I finished a reasoning cycle "+.getCycleNumber()+". Breakpoint is " + isBreakPoint);
                    } catch (NullPointerException e) {
                        // no problem, there is no sel opt, no plan ....
                    }
                    informCycleFinished(isBreakPoint.getCycleNumber());
                } else {
                    block(1000);
                }
            } else {
                if () {
                    block(1000);
                     = false;
                } else {
                    .reasoningCycle();
                }
            }
        }
    }
    
    @Override
    public void doDelete() {
        try {
             = false;
            if ( != null) {
                .getFirstAgArch().stop();
            }
        } catch (Exception e) {
            .log(.,"Error in doDelete.",e);
        } finally {
            super.doDelete();
        }
    }
    
    @Override
    protected void takeDown() {
        .info("Finished!");
    }
    
    
    private MessageTemplate ts = MessageTemplate.and(
            MessageTemplate.MatchContent("agState"),
            MessageTemplate.MatchOntology(.));
    private MessageTemplate tc = MessageTemplate.and(
            MessageTemplate.MatchContent("performCycle"),
            MessageTemplate.MatchOntology(.));
        ACLMessage m = receive();
        if (m != null) {
            // send the agent state
            ACLMessage r = m.createReply();
            r.setPerformative(ACLMessage.INFORM);
            try {
                Document agStateDoc = .getTS().getAg().getAgState();
                r.setContentObject((Serializable)agStateDoc);
                send(r);
            } catch (Exception e) {
                .log(."Error sending message " + re);
            }            
        }
        
        m = receive();
        if (m != null) {
            int cycle = Integer.parseInt(m.getUserDefinedParameter("cycle"));
            .fine("new cycle: "+cycle);
            .setCycleNumber(cycle);
            return true;
        }
        return false;
    }
    
    /*
    boolean isPerceptionOntology(ACLMessage m) {
        return m.getOntology() != null && m.getOntology().equals(JadeEnvironment.perceptionOntology);
    }
    */


    
Informs the infrastructure tier controller that the agent has finished its reasoning cycle (used in sync mode).

breakpoint is true in case the agent selected one plan with the "breakpoint" annotation.

 
    public void informCycleFinished(boolean breakpointint cycle) {
        try {
            ACLMessage m = new ACLMessage(ACLMessage.INFORM);
            m.addReceiver();
            m.setOntology(.);
            m.setContent(breakpoint+","+cycle);
            send(m);
        } catch (Exception e) {
            .log(."Error sending cycle finished."e);
        }
    }
New to GrepCode? Check out our FAQ X