⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 sniffer.java

📁 java实现的P2P多agent中间件
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
   */
  public void toolSetup() {

    properties = new ExpandedProperties();

    /*
     * preload agents from argument array if arguments present, otherwise load
     * sniffer.properties file.
     */
    Object[] arguments = getArguments();
    if ( (arguments != null) && ( arguments.length > 0 ))
    {
        String  s = "";
        for( int i=0; i < arguments.length; ++i ) {
            s += arguments[i].toString()+' ';
        }
        properties.setProperty("preload", s );
        
    } else {
        String fileName = locateFile("sniffer.properties");
        if (fileName != null) {
            try {
                properties.addFromFile(fileName);
            } catch (IOException ioe) {
                // ignore - Properties not processed
            }
        } else {
            // This is only being done for backward compatability.
            fileName = locateFile("sniffer.inf");
            if (fileName != null) {
                loadSnifferConfigurationFile(fileName, properties);
            }
        }
    }

    allAgents = new HashSet();
    preload = new Hashtable();
    
    String preloadDescriptions = properties.getProperty("preload", null);
    
    if (preloadDescriptions != null) {
        StringTokenizer parser = new StringTokenizer(preloadDescriptions, ";");
        while (parser.hasMoreElements()) {
            parsePreloadDescription(parser.nextToken());
        }
    }

    //#DOTNET_EXCLUDE_BEGIN
    // 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());

    // Show Graphical User Interface
    myGUI = new MainWindow(this, properties);
    myGUI.ShowCorrect();
    //#DOTNET_EXCLUDE_END

    /*#DOTNET_INCLUDE_BEGIN
    //Create GUI
	System.Threading.ThreadStart tStart = new System.Threading.ThreadStart( createUI );
	System.Threading.Thread t = new System.Threading.Thread( tStart );
	t.Start();
	#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(ap.DO_SNIFFER_ACTION);
    sa.doSniff(id.getName());
  }
  
  private void removeAgent(AID id) {
    ActionProcessor ap = myGUI.actPro;
    DoNotSnifferAction nsa = (DoNotSnifferAction)ap.actions.get(ap.DO_NOT_SNIFFER_ACTION);
    nsa.doNotSniff(id.getName());
  }
  

    /**
     * Private function to read configuration file containing names of agents to be
     * preloaded. Also supports message filtering based on performatives.
     * Each line of the file lists an agent, optionally followed
     * by a set of messages to sniff.  If there are no tokens, then we assume
     * that means to sniff all.  The tokens are the name of the performative type
     * such as INFORM, QUERY, etc.
     * @deprecated Use sniffer.properties file instead.
     */
    private void loadSnifferConfigurationFile (String aFileName, ExpandedProperties theProperties) {
        StringBuffer sb = new StringBuffer();
        BufferedReader in = null;
        try {
            in = new BufferedReader(new FileReader(aFileName));
            boolean eof = false;
            while (!eof) {
                String line = in.readLine();
                eof = (line == null);
                if (!eof) {
                    line = line.trim();
                    if (line.length() > 0) {
                        sb.append(line);
                        sb.append(";");
                    }
                }
            }
        } catch(Exception e) {
            // ignore
        }
        if (in != null) {
            try {
                in.close();
            } catch (IOException ee) {
                // ignore
            }
        }
        if (sb.length() > 0) {
            theProperties.setProperty("preload", sb.toString());
        }
    }

    private String locateFile(String aFileName) {
        try {
            String path = (new File(".")).getAbsolutePath();
            while (path != null) {
                path = path.replace('\\','/');
                if (path.endsWith(".")) {
                    path = path.substring(0, path.length() - 1);    // drop dot
                }

                if (path.endsWith("/")) {
                    path = path.substring(0, path.length() - 1);    // drop last separator
                }
                File dir = new File(path);
                File theFile = new File(dir, aFileName);
                if (theFile.exists()) {
                    return theFile.getCanonicalPath();
                } else {
                    path = dir.getParent();    // reduce the path by one
                }
            }
        } catch (Exception any) {
            // ignore
        }
        return null;
    }


    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() ? false : true);
        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);
    }

/**
   * Cleanup during agent shutdown. This method cleans things up when
   * <em>Sniffer</em> agent is destroyed, disconnecting from <em>AMS</em>
   * agent and closing down the Sniffer administration <em>GUI</em>.
   * Currently sniffed agents are also unsniffed to avoid errors.
   */
  protected void toolTakeDown() {

    List l = (List)(agentsUnderSniff.clone());
    ACLMessage request = getSniffMsg(l, SNIFF_OFF);

    // Start a FIPARequestProtocol to sniffOff all the agents since
    // the sniffer is shutting down
    try {
      if(request != null)
	FIPAService.doFipaRequestClient(this,request);
    }
    catch(jade.domain.FIPAException e) {
    	// When the AMS replies the tool notifier is no longer registered.
    	// But we don't care as we are exiting
      //System.out.println(e.getMessage());
    }

    myGUI.mainPanel.panelcan.canvMess.ml.removeAllMessages();

    // Now we unsubscribe from the rma list
    send(getCancel());
    // myGUI.setVisible(false); Not needed. Can cause thread deadlock.
    myGUI.disposeAsync();

  }

/**
 * This method adds an AMSClientBehaviour that performs a request to the AMS for sniffing/unsniffing list of agents.
 **/
 public void sniffMsg(List agents, boolean onFlag) {
      ACLMessage request = getSniffMsg(agents,onFlag);
      if (request != null)
        addBehaviour(new AMSClientBehaviour((onFlag?"SniffAgentOn":"SniffAgentOff"),request));

 }
  /**
   * Creates the ACLMessage to be sent to the <em>Ams</em> with the list of the
   * agents to be sniffed/unsniffed. The internal list of sniffed agents is also
   * updated.
   *
   * @param agentVect vector containing TreeData item representing the agents
   * @param onFlag can be:<ul>
   *			  <li> Sniffer.SNIFF_ON  to activate sniffer on an agent/group
   *			  <li> Sniffer.SNIFF_OFF to deactivate sniffer on an agent/group
   *		         </ul>
   */
  public ACLMessage getSniffMsg(List agents, boolean onFlag) {

    Iterator it = agents.iterator();

    if(onFlag) {
      SniffOn so = new SniffOn();
      so.setSniffer(getAID());
      boolean empty = true;
      while(it.hasNext()) {
	Agent a = (Agent)it.next();
	AID agentID = new AID();
	agentID.setName(a.agentName + '@' + getHap());
	if(!agentsUnderSniff.contains(a)) {
	  agentsUnderSniff.add(a);
	  so.addSniffedAgents(agentID);
	  empty = false;
	}
      }
      if(!empty) {
	try {
	  Action a = new Action();
	  a.setActor(getAMS());
	  a.setAction(so);

	  ACLMessage requestMsg = getRequest();
	  requestMsg.setOntology(JADEManagementOntology.NAME);
	  getContentManager().fillContent(requestMsg, a);
       return requestMsg;
	}
	catch(Exception fe) {
	  fe.printStackTrace();
	}
      }
    }

    else {
      SniffOff so = new SniffOff();
      so.setSniffer(getAID());
      boolean empty = true;
      while(it.hasNext()) {
		Agent a = (Agent)it.next();
		AID agentID = new AID();
		agentID.setName(a.agentName + '@' + getHap());
		if(agentsUnderSniff.contains(a)) {
	  		agentsUnderSniff.remove(a);
	  		so.addSniffedAgents(agentID);
	  		empty = false;
		}
      }
      if(!empty) {
		try {
	  		Action a = new Action();
	  		a.setActor(getAMS());
	  		a.setAction(so);

	  		ACLMessage requestMsg = getRequest();
	  		requestMsg.setOntology(JADEManagementOntology.NAME);
	  		getContentManager().fillContent(requestMsg, a);
          	requestMsg.setReplyWith(getName()+ (new Date().getTime()));
          	return requestMsg;
	}
	catch(Exception fe) {
	  fe.printStackTrace();
	}
      }
    }
    return null;
  }

  
  /**
     Inner class RequestListenerBehaviour.
     This behaviour serves requests to start sniffing agents.
     If an agent does not exist it is put into the 
     preload table so that it will be sniffed as soon as it starts.
   */
  private class RequestListenerBehaviour extends SimpleAchieveREResponder {  	
		private Action requestAction;
		private AgentAction aa;
		
		RequestListenerBehaviour() {
			// We serve REQUEST messages refering to the JADE Management Ontology
 			super(Sniffer.this, MessageTemplate.and(MessageTemplate.MatchPerformative(ACLMessage.REQUEST),MessageTemplate.MatchOntology(JADEManagementOntology.NAME)));
		}
	
		protected ACLMessage prepareResponse (ACLMessage request) {
			ACLMessage response = request.createReply();
			try {			
				requestAction = (Action) getContentManager().extractContent(request);
				aa = (AgentAction) requestAction.getAction();
				if (aa instanceof SniffOn || aa instanceof SniffOff) {
					if (getAID().equals(requestAction.getActor())) {
						response.setPerformative(ACLMessage.AGREE);
						response.setContent(request.getContent());
					}
					else {
						response.setPerformative(ACLMessage.REFUSE);
						response.setContent("((unrecognised-parameter-value actor "+requestAction.getActor()+"))");
					}
				}
				else {
					response.setPerformative(ACLMessage.REFUSE);	
					response.setContent("((unsupported-act "+aa.getClass().getName()+"))");
				}
			} 
			catch (Exception e) {
				e.printStackTrace();
				response.setPerformative(ACLMessage.NOT_UNDERSTOOD);	
			}
			return response;					    		    		 	
		}
	
		protected ACLMessage prepareResultNotification(ACLMessage request, ACLMessage response) {	
			if (aa instanceof SniffOn) { 
				// SNIFF ON
				SniffOn requestSniffOn = (SniffOn) aa;
				// Start sniffing existing agents.
				// Put non existing agents in the preload map. We will start
				// sniffing them as soon as they start. 
				List agentsToSniff = requestSniffOn.getCloneOfSniffedAgents();											
				for (int i=0;i<agentsToSniff.size();i++) {
					AID aid = (AID)agentsToSniff.get(i); 
					if (allAgents.contains(aid)) {
						addAgent(aid);
					} 
					else {
						//not alive -> put it into preload
						int performativeCount = ACLMessage.getAllPerformativeNames().length;
						boolean[] filter = new boolean[performativeCount];
						for (int j=0; j<performativeCount;j++) {
							filter[j] = true;
						}
						preload.put(aid.getName(), filter);									
					}
				}																		
			}
			else {
				// SNIFF OFF
				SniffOff requestSniffOff = (SniffOff) aa;
				List agentsToSniff = requestSniffOff.getCloneOfSniffedAgents();											
				for (int i=0;i<agentsToSniff.size();i++) {
					AID aid = (AID)agentsToSniff.get(i); 
					removeAgent(aid);
				}
			}
			
			// Send back the notification
			ACLMessage result = request.createReply();
			result.setPerformative(ACLMessage.INFORM);
			Done d = new Done(requestAction);
			try {
				myAgent.getContentManager().fillContent(result, d);
			}
			catch (Exception e) {
				// Should never happen
				e.printStackTrace();
			}
			return result;
		}		
  }  // END of inner class RequestListenerBehaviour 
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -