Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  //----------------------------------------------------------------------------
  // Copyright (C) 2003  Rafael H. Bordini, Jomi F. Hubner, et al.
  // 
  // This library is free software; you can redistribute it and/or
  // modify it under the terms of the GNU Lesser General Public
  // License as published by the Free Software Foundation; either
  // version 2.1 of the License, or (at your option) any later version.
  // 
  // This library is distributed in the hope that it will be useful,
 // but WITHOUT ANY WARRANTY; without even the implied warranty of
 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 // Lesser General Public License for more details.
 // 
 // You should have received a copy of the GNU Lesser General Public
 // License along with this library; if not, write to the Free Software
 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 // 
 // To contact the authors:
 // http://www.inf.ufrgs.br/~bordini
 // http://www.das.ufsc.br/~jomi
 //
 //----------------------------------------------------------------------------
 
 
 package jason.environment;
 
 
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
It is a base class for Environment, it is overridden by the user application to define the environment "behaviour".

Execution sequence:

  • setEnvironmentInfraTier,
  • init,
  • (getPercept|executeAction)*,
  • stop.
 
 public class Environment { 
 
     private static Logger logger = Logger.getLogger(Environment.class.getName());
 
     private List<Literalpercepts = Collections.synchronizedList(new ArrayList<Literal>());
     private Map<String,List<Literal>>  agPercepts = new ConcurrentHashMap<StringList<Literal>>();
 
     private boolean isRunning = true;
    
    
the infrastructure tier for environment (Centralised, Saci, ...)
 
     private EnvironmentInfraTier environmentInfraTier = null;
 
     // set of agents that already received the last version of perception
     private Set<StringuptodateAgs = Collections.synchronizedSet(new HashSet<String>());
 
     protected ExecutorService executor// the thread pool used to execute actions
 
    
creates an environment class with n threads to execute actions required by the agents
 
     public Environment(int n) {
         // creates a thread pool with n threads
          = Executors.newFixedThreadPool(n);
 
         // creates and executor with 1 core thread
         // where no more than 3 tasks will wait for a thread
         // The max number of thread is 1000 (so the 1001 task will be rejected) 
         // Threads idle for 10 sec. will be removed from the pool
         //executor= new ThreadPoolExecutor(1,1000,10,TimeUnit.SECONDS,new ArrayBlockingQueue<Runnable>(3));
     }

    
creates an environment class with the default number of threads in the pool
 
     public Environment() {
         this(4);
     }

    
Called before the MAS execution with the args informed in .mas2j project, the user environment could override it.
 
     public void init(String[] args) {
     }
    
    
Called just before the end of MAS execution, the user environment could override it.
    public void stop() {
         = false;
        .shutdownNow();
    }
    
    public boolean isRunning() {
        return ;
    }
    
    
Sets the infrastructure tier of the environment (saci, jade, centralised, ...)
    public void setEnvironmentInfraTier(EnvironmentInfraTier je) {
         = je;
    }
        return ;
    }
    public Logger getLogger() {
        return ;
    }
    
    

Deprecated:
use version with String... parameter
    public void informAgsEnvironmentChanged(Collection<Stringagents) {
        if ( != null) {
            .informAgsEnvironmentChanged(agents);
        }
    }
    public void informAgsEnvironmentChanged(String... agents) {
        if ( != null) {
            .informAgsEnvironmentChanged(agents);
        }
    }

    
Returns percepts for an agent. A full copy of both common and agent's percepts lists is returned. It returns null if the agent's perception doesn't changed since last call. This method is to be called by TS and should not be called by other objects.
    public List<LiteralgetPercepts(String agName) { // TODO in a future release, call this method doPerception, and get simply returns the list
        
        // check whether this agent needs the current version of perception
        if (.contains(agName)) {
            return null;
        }
        // add agName in the set of updated agents
        .add(agName);
        
        int size = .size();
        List<Literalagl = .get(agName);
        if (agl != null) {
            size += agl.size();
        }
        List<Literalp = new ArrayList<Literal>(size);
        
        if (! .isEmpty()) { // has global perception?
            synchronized () {
                // make a local copy of the environment percepts
                // Note: a deep copy will be done by BB.add
                p.addAll();
            }
        }
        if (agl != null) { // add agent personal perception
            synchronized (agl) {
                p.addAll(agl);
            }
        }
        
        return p;
    }
    
    
Returns a copy of the perception for an agent. It is the same list returned by getPercepts, but doesn't consider the last call of the method.
    public List<LiteralconsultPercepts(String agName) {
        int size = .size();
        List<Literalagl = .get(agName);
        if (agl != null) {
            size += agl.size();
        }
        List<Literalp = new ArrayList<Literal>(size);
        
        if (! .isEmpty()) { // has global perception?
            synchronized () {
                // make a local copy of the environment percepts
                // Note: a deep copy will be done by BB.add
                p.addAll();
            }
        }
        if (agl != null) { // add agent personal perception
            synchronized (agl) {
                p.addAll(agl);
            }
        }    
        return p;
    }
    
    
Adds a perception for all agents
    public void addPercept(Literal per) {
        if (per != null) {
            if (! .contains(per)) {
                .add(per);
                .clear();
            }
        }
    }

    
Removes a perception from the common perception list
    public boolean removePercept(Literal per) {
        if (per != null) {
            .clear();
            return .remove(per);
        } 
        return false;
    }
    
    
Removes all percepts from the common perception list that unifies with per. Example: removePerceptsByUnif(Literal.parseLiteral("position(_)")) will remove all percepts that unifies "position(_)".

Returns:
the number of removed percepts.
    public int removePerceptsByUnif(Literal per) {
        int c = 0;
        if (! .isEmpty()) { // has global perception?
            synchronized () {
                Iterator<Literali = .iterator();
                while (i.hasNext()) {
                    Literal l = i.next();
                    if (new Unifier().unifies(l,per)) {
                        i.remove();
                        c++;
                    }
                }
            }
            if (c>0) .clear();
        }
        return c;
    }
    
    
    
Clears the list of global percepts
    public void clearPercepts() {
        if (!.isEmpty()) {
            .clear();
            .clear();
        }
    }
    
    
Returns true if the list of common percepts contains the perception per.
    public boolean containsPercept(Literal per) {
        if (per != null) {
            return .contains(per);
        } 
        return false;
    }
    
    
Adds a perception for a specific agent
    public void addPercept(String agNameLiteral... per) {
        if (per != null && agName != null) {
            List<Literalagl = .get(agName);
            if (agl == null) {
                agl = Collections.synchronizedList(new ArrayList<Literal>());
                .putagNameagl);
            } 
            for (Literal pper) {
                if (! agl.contains(p)) {
                    .remove(agName);
                    agl.add(p);
                }                
            }
        }
    }
    
    
Removes a perception for an agent
    public boolean removePercept(String agNameLiteral per) {
        if (per != null && agName != null) {
            List<Literalagl = .get(agName);
            if (agl != null) {
                .remove(agName);
                return agl.remove(per);
            }
        }
        return false;
    }

    
Removes from an agent perception all percepts that unifies with per.

Returns:
the number of removed percepts.
    public int removePerceptsByUnif(String agNameLiteral per) {
        int c = 0;
        if (per != null && agName != null) {
            List<Literalagl = .get(agName);
            if (agl != null) {
                synchronized (agl) {
                    Iterator<Literali = agl.iterator();
                    while (i.hasNext()) {
                        Literal l = i.next();
                        if (new Unifier().unifies(l,per)) {
                            i.remove();
                            c++;
                        }
                    }
                }
                if (c>0) .remove(agName);
            }
        }
        return c;
    }
    
    public boolean containsPercept(String agNameLiteral per) {
        if (per != null && agName != null) {
            @SuppressWarnings("rawtypes")
            List agl = (List).get(agName);
            if (agl != null) {
                return agl.contains(per);
            }
        }
        return false;
    }

    
Clears the list of percepts of a specific agent
    public void clearPercepts(String agName) {
        if (agName != null) {
            List<Literalagl = .get(agName);
            if (agl != null) {
                .remove(agName);
                agl.clear();
            }
        }
    }
    
    
Clears all perception (from common list and individual perceptions)
    public void clearAllPercepts() {
        clearPercepts();
        for (String ag.keySet()) 
            clearPercepts(ag);
    }
    
    
Called by the agent infrastructure to schedule an action to be executed on the environment
    public void scheduleAction(final String agNamefinal Structure actionfinal Object infraData) {
        .execute(new Runnable() {
            public void run() {
                try {
                    boolean success = executeAction(agNameaction);
                    .actionExecuted(agNameactionsuccessinfraData); // send the result of the execution to the agent
                } catch (Exception ie) {
                    if (!(ie instanceof InterruptedException)) {
                        .log(."act error!",ie);
                    }
                }
            }
        });
    }
    
    
Executes an action on the environment. This method is probably overridden in the user environment class.
    public boolean executeAction(String agNameStructure act) {
        .info("The action "+act+" done by "+agName+" is not implemented in the default environment.");
        return false;
    }
New to GrepCode? Check out our FAQ X