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.control;
 
 
 import java.util.Map;
 import java.util.Set;
 
 
 
 public class ExecutionControlGUI extends ExecutionControl {
 
     String currentAgState = "";
     String currentAgName  = "";
     int    agShownState   = 0;
     
     
     private int countCycles = 0; // cycles since last "Run"
     private int maxCycles = 0;   // cycles to run
     private boolean waitAllAgs     = false// run cycles in all agents
     private boolean waitSelectedAg = false// run cycles in selected agent
     private boolean breakpoint     = false;
 
     // xml components
     asl2xml  agTransformerXML  = new asl2xml();
     asl2tex  agTransformerTex  = new asl2tex("/xml/ag2tex.xsl");
     asl2html agTransformerHtml = new asl2html("/xml/agInspection.xsl");
     asl2xml  agTransformer     = null;
      
 
     public ExecutionControlGUI() {
          = ;
        setRunningCycle(false);
        initComponents();
    }
    @Override
    public void init(String[] args) {
        setListOfAgsFromInfra();
    }
    
    // Interface components
    JFrame     frame;
    JTextField jTfSteps = null;
    JComboBox  jCbWho = null;
    JButton    jBtRun = null;
    JComboBox  jCbViewAs = null;
    JSlider    jHistory = null;
    JTextPane  jTA = null;
    JList      jList = null;
    JPanel     spList;
    
    
    // what to show
    Document agState = null;
    // Which item is to be shown in HTML interface
    Map<String,Booleanshow = new HashMap<String,Boolean>();
    public static String title = "..:: Mind Inspector ::..";
    
    void initComponents() {
         = new JFrame();
         = new JTextField(3);
        .setText("1");
        .addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        startRun();
                    }
                });
            }
        });
        
         = new JComboBox();
        .addItem("all agents");
        .addItem("selected agent");
        
         = new JButton("Run"new ImageIcon(ExecutionControlGUI.class.getResource("/images/run.gif")));
        .setToolTipText("Run the MAS until some agent achieve a breakpoint. Breakpoints are annotations in plans' label");
        .setEnabled(true);
        .addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        startRun();
                    }
                });
            }
        });
         = new JComboBox();
        .addItem("html");
        .addItem("xml");
        .addItem("LaTeX");
        .addItemListener(new ItemListener() {
            public void itemStateChanged(ItemEvent ievt) {
                String mime = .getSelectedItem().toString();
                if (mime.equals("html")) {
                     = ;
                } else if (mime.equals("xml")) {
                     = ;
                } else if (mime.equals("LaTeX")) {
                    mime = "xml";
                     = ;
                }
                .setContentType("text/"+mime);
                 = "--";
                showAgState();
            }            
        });
        
        /*
        JButton jBtRefresh = new JButton("Show extra info");
        jBtRefresh.setEnabled(true);
        jBtRefresh.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                agsHistory.clear();
                showAgState();
                System.out.println("***"+RunCentralisedMAS.getRunner().sleepingAgs);
                for (CentralisedAgArch ar: RunCentralisedMAS.getRunner().sleepingAgs) {
                    System.out.println(ar+":"+ar.canSleep());
                }
            }
        });*/
        
         = new JTextPane();
        .setEditable(false);
        .setContentType("text/html");
        .setAutoscrolls(false);
            public void hyperlinkUpdate(HyperlinkEvent evt) {
                hyperLink(evt);
            }
        });
        .setText("<html><body>Select the agent to inspect.</body></html>");
        
        JPanel spTA = new JPanel(new BorderLayout());
        JScrollPane scpTA = new JScrollPane();
        //scpTA.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        spTA.add(.scpTA);
        spTA.setBorder(BorderFactory.createTitledBorder(BorderFactory
                .createEtchedBorder(), "Agent Inspection"..));
        JPanel pHistory = new JPanel(new BorderLayout());//new FlowLayout(FlowLayout.CENTER));
        pHistory.setBorder(BorderFactory.createTitledBorder(BorderFactory
                .createEtchedBorder(), "Agent History"..));
         = new JSlider();
        .setMaximum(1);
        .setMinimum(0);
        .setValue(0);
        .setPaintTicks(true);
        .setPaintLabels(true);
        .setMajorTickSpacing(10);
        .setMinorTickSpacing(1);
        setupSlider();
        .addChangeListener(new ChangeListener() {
            public void stateChanged(ChangeEvent e) {
                int c = (int).getValue();
                try {
                     = .get().get(c);
                    showAgState();
                } catch (Exception ex) { }
            }
        });
        pHistory.add(.);
        JPanel pAg = new JPanel(new BorderLayout());
        pAg.add(.spTA);
        pAg.add(.pHistory);
        
         = new DefaultListModel();
         = new JList();
         = new JPanel(new BorderLayout());
        .add(.new JScrollPane());
        .setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Agents"..));
            public void valueChanged(ListSelectionEvent e) {
                String ag = .getSelectedValue().toString();
                if (!ag.equals()) {
                     = ag;
                    SwingUtilities.invokeLater(new Runnable() {
                        public void run() {
                            inspectAgent();
                        }
                    });
                }
            }
        });
        
        JPanel pButtons = new JPanel(new FlowLayout(.));
        pButtons.add();
        pButtons.add();
        pButtons.add(new JLabel("cycle(s) for "));
        pButtons.add();
        pButtons.add(new JLabel("        view as:"));
        pButtons.add();
        //pButtons.add(jBtRefresh);
        JSplitPane splitPaneHor = new JSplitPane(.);
        splitPaneHor.setTopComponent();
        splitPaneHor.setDividerLocation(100);
        splitPaneHor.setBottomComponent(pAg);
        splitPaneHor.setOneTouchExpandable(true);
        //splitPane.setPreferredSize(new Dimension(600, 300));
        //JSplitPane splitPaneVer = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
        //splitPaneVer.setTopComponent(splitPaneHor);
        //splitPaneVer.setBottomComponent(spConsole);
        //splitPaneVer.setOneTouchExpandable(true);
        .getContentPane().add(.pButtons);
        .getContentPane().add(.splitPaneHor);//splitPaneVer);
        .pack();
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        int height = (int)(screenSize.height * 0.618);
        .setBounds(80, 30, (int)(height*1.618), height);
        //splitPaneVer.setDividerLocation((int)(splitPaneVer.getHeight()*0.618));
        //splitPaneVer.setDividerLocation(height - 200);
        
        .setVisible(true);
        .addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                //close();
            }
        });
        
        .put("bels"true);
        .put("rules"false);
        .put("evt"true);
        .put("mb"false);
        .put("int"false);
        .put("int-details"false);
        .put("plan"false);
        .put("plan-details"false);
        .put("annots", Config.get().getBoolean(.));        
    }
    void setListOfAgsFromInfra() {
        try {
            for (String agags) { //getExecutionControlInfraTier().getRuntimeServices().getAgentsNames()) {
                .addElement(ag);
            }
        } catch (Exception e) {
            ..println("Error getting list of agents from infrasructure. "+e);
        }
    }
    
    private void setupSlider() {
        int size = getCycleNumber();
        Hashtable<Integer,ComponentlabelTable = new Hashtable<Integer,Component>();
        labelTable.put( 0, new JLabel("Cycle 0") );
        labelTable.putsizenew JLabel("Cycle "+size) );
        .setLabelTablelabelTable );
        .setMaximum(size);
        .setValue(size);
    }
    
    public void stop() {
        super.stop();
        .dispose();
         = null;
    }
    
    private void inspectAgent(String agName) {
        if (agName == null) {
            return;
        }
        if (agName.length() == 0) {
            return;
        }
         = agName;
        
         = null;
        // try to get the state from the history
        try {
             = .get().get(getCycleNumber());
        } catch (Exception et) {}
        // if no state from history, ask the agent
        if ( == null) {
            try {
                // try to get from history
                 = .getAgState();
                storeAgHistory(getCycleNumber(), );
            } catch (Exception e) {
                .setText("Error getting the state of agent "+);
                .log(.,"Error:",e);
            }
        }
        
        showAgState();
        setupSlider();                
    }
    private String previousMind = "--";
    
    
show current agent state
    void showAgState() {
        if ( != null) {
            String sMind = null;
            try {
                // set parameters
                if (.getSelectedItem().toString().equals("html")) {
                    // as HTML
                    for (String p.keySet()) {
                        .getTransformer().setParameter("show-"+p.get(p)+"");
                    }
                }
                sMind = .transform();
                if (!sMind.equals()) {
                    .setText(sMind);
                }
                 = sMind;
            } catch (Exception e) {
                .setText("Error in XML transformation!" + e + "\nText="+sMind);
                e.printStackTrace();
            }
        }        
    }
    
    private void hyperLink(HyperlinkEvent evt) {
        if (evt.getEventType() == ..) {
            //System.out.println("*evt="+evt.getDescription());
            String uri = "show?";
            int pos = evt.getDescription().indexOf(uri);
            if (pos >= 0) {
                String par = evt.getDescription().substring(pos+uri.length());
                .put(par,true);
            } else {
                uri = "hide?";
                pos = evt.getDescription().indexOf(uri);
                if (pos >= 0) {
                    String par = evt.getDescription().substring(pos+uri.length());
                    .put(par,false);
                }
            }
            showAgState();
        }
    }
    
    
    protected void startRun() {
        .setEnabled(false);
         = 0;
         = Integer.parseInt(.getText());
         = false;
        if (.getSelectedIndex() == 0) {
                 = true
             = false;
        } else {
                 = false
             = true;
        }
        if (RunCentralisedMAS.getRunner() != null && RunCentralisedMAS.getRunner(). != null) {
            RunCentralisedMAS.getRunner()..setEnabled(true);
        }        
        startNewCycle();
        continueRun();
    }
    
    
stop the execution
    protected void stopRun() {
             = false
         = false;
        inspectAgent();
        .setEnabled(true);
        setRunningCycle(false);
    }
    private ExecutorService executor = Executors.newFixedThreadPool(2);
    
    protected void continueRun() {
        .execute(new Runnable() {
            public void run() {
                if () {
                    .informAllAgsToPerformCycle(getCycleNumber());            
                }
                if () {
                    .informAgToPerformCycle(getCycleNumber());
                }
            }
        });
    }
    
    
Called when the agent agName has finished its reasoning cycle. breakpoint is true in case the agent selected one plan with "breakpoint" annotation.
    public void receiveFinishedCycle(final String agNameboolean breakpointfinal int cycle) {
        if (!.contains(agName)) {
            .fine("New agent "+agName);
            .addElement(agName);
        }
        // get the state of this agent and add it in history
        try {
            storeAgHistory(agNamecycle.getAgState(agName));
        } catch (Exception e) {
            .setText("Error getting the state of agent "+agName);
            .log(.,"Error:",e);
        }
        this. = breakpoint;
        if () {
            ++;
            .info("Agent "+agName+" has finished cycle "+cycle);
            if (testStop()) {
                stopRun();
            } else {
                startNewCycle();
                continueRun();
            }
        } else {
            super.receiveFinishedCycle(agNamebreakpointcycle);    
        }
    }


    
called when all agents have finished the current cycle
    protected void allAgsFinished() {
        if () {
            .fine("All agents have finished cycle "+getCycleNumber());
            ++;
            if (testStop()) {
                stopRun();
            } else {
                startNewCycle();
                .setTitle( + " cycle "+getCycleNumber()+" ::");
                continueRun();
            }
        }
    }
    
    
test whether to stop running and show the agent state
    protected boolean testStop() {
        return  ||  >= 
    }
    protected void storeAgHistory(String agNameint cycleDocument doc) {
        if (doc == nullreturn;
        Map<Integer,Documentlag = .get(agName);
        if (lag == null) {
            lag = new HashMap<Integer,Document>();
            .put(agNamelag);
        }
        lag.put(cycle,doc);
    }
New to GrepCode? Check out our FAQ X