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

📄 introspector.java

📁 JADE(JAVA Agent开发框架)是一个完全由JAVA语言开发的软件,它简化了多Agent系统的实现。
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
	/**
	 Callback method for platform management <em>GUI</em>.
	 */
	public AgentTreeModel getModel() {
		return myGUI.getModel();
	}
	
	/*
	 Listens to introspective messages and dispatches them.
	 */
	private class IntrospectionListenerBehaviour extends CyclicBehaviour {
		
		private MessageTemplate template;
		private Map handlers = new TreeMap(String.CASE_INSENSITIVE_ORDER);
		
		IntrospectionListenerBehaviour() {
			template = MessageTemplate.and(MessageTemplate.MatchOntology(IntrospectionOntology.NAME),
					MessageTemplate.MatchConversationId(getName() + "-event"));
			
			// Fill handlers table ...
			handlers.put(IntrospectionVocabulary.CHANGEDAGENTSTATE, new EventHandler() {
				public void handle(Event ev) {
					
				}
				
			});
			
			handlers.put(IntrospectionVocabulary.ADDEDBEHAVIOUR, new EventHandler() {
				public void handle(Event ev) {
					AddedBehaviour ab = (AddedBehaviour)ev;
					AID agent = ab.getAgent();
					MainWindow wnd = (MainWindow)windowMap.get(agent);
					if(wnd != null)
						myGUI.behaviourAdded(wnd, ab);
				}
				
			});
			
			handlers.put(IntrospectionVocabulary.REMOVEDBEHAVIOUR, new EventHandler() {
				public void handle(Event ev) {
					RemovedBehaviour rb = (RemovedBehaviour)ev;
					AID agent = rb.getAgent();
					MainWindow wnd = (MainWindow)windowMap.get(agent);
					if(wnd != null)
						myGUI.behaviourRemoved(wnd, rb);
				}
				
			});
			
			handlers.put(IntrospectionVocabulary.CHANGEDBEHAVIOURSTATE, new EventHandler() {
				public void handle(Event ev) {
					ChangedBehaviourState cs = (ChangedBehaviourState)ev;
					AID agent = cs.getAgent();
					MainWindow wnd = (MainWindow)windowMap.get(agent);
					if(wnd != null) {
						myGUI.behaviourChangeState(wnd, cs);
					}
					if (stepByStepAgents.contains(agent)) {
						return;
					}
					if (slowAgents.contains(agent)) {
						try {
							Thread.sleep(500);
						}
						catch (InterruptedException ie) {
							// The introspector is probably being killed
						}
					}
					proceed(agent);
				}
				
			});
			
			handlers.put(IntrospectionVocabulary.SENTMESSAGE, new EventHandler() {
				public void handle(Event ev) {
					SentMessage sm = (SentMessage)ev;
					AID sender = sm.getSender();
					
					MainWindow wnd = (MainWindow)windowMap.get(sender);
					if(wnd != null)
						myGUI.messageSent(wnd, sm);
				}
				
			});
			
			handlers.put(IntrospectionVocabulary.RECEIVEDMESSAGE, new EventHandler() {
				public void handle(Event ev) {
					ReceivedMessage rm = (ReceivedMessage)ev;
					AID receiver = rm.getReceiver();
					
					MainWindow wnd = (MainWindow)windowMap.get(receiver);
					if(wnd != null)
						myGUI.messageReceived(wnd, rm);
				}
				
			});
			
			handlers.put(IntrospectionVocabulary.POSTEDMESSAGE, new EventHandler() {
				public void handle(Event ev) {
					PostedMessage pm = (PostedMessage)ev;
					AID receiver = pm.getReceiver();
					
					MainWindow wnd = (MainWindow)windowMap.get(receiver);
					if(wnd != null)
						myGUI.messagePosted(wnd, pm);
				}
				
			});
			
			handlers.put(IntrospectionVocabulary.CHANGEDAGENTSTATE, new EventHandler() {
				public void handle(Event ev) {
					ChangedAgentState cas = (ChangedAgentState)ev;
					AID agent = cas.getAgent();
					
					MainWindow wnd = (MainWindow)windowMap.get(agent);
					if(wnd != null)
						myGUI.changedAgentState(wnd, cas);
				}
				
			});
			
		}
		
		public void action() {
			
			ACLMessage message = receive(template);
			if(message != null) {
				AID name = message.getSender();
				try{
					Occurred o = (Occurred)getContentManager().extractContent(message);
					EventRecord er = o.getWhat();
					Event ev = er.getWhat();
					// DEBUG
					if(logger.isLoggable(Logger.FINEST))
						logger.log(Logger.FINEST,"Received event "+ev);
					if (message.getReplyWith() != null) {
						// A reply is expected --> put relevant information into the
						// pendingReplies Map
						ChangedBehaviourState cs = (ChangedBehaviourState)ev;
						pendingReplies.put(cs.getAgent(), message.getReplyWith());
					}
					String eventName = ev.getName();
					EventHandler h = (EventHandler)handlers.get(eventName);
					if(h != null)
						h.handle(ev);
				}
				catch(Exception fe) {
					fe.printStackTrace();
				}
			}
			else
				block();
		}
		
	} // End of inner class IntrospectionListenerBehaviour
	
	
	/**
	 Inner class ControlListenerBehaviour.
	 This is a behaviour that listen for messages from ToolNotifiers
	 informing that they have started notifying events about a given
	 agent. These information are used to keep the map between observed
	 agents and ToolNotifiers up to date.
	 */
	private class ControlListenerBehaviour extends CyclicBehaviour {
		private MessageTemplate template;
		
		ControlListenerBehaviour(Agent a) {
			super(a);
			template = MessageTemplate.and(
					MessageTemplate.MatchOntology(IntrospectionOntology.NAME),
					MessageTemplate.MatchConversationId(getName() + "-control"));
		}
		
		public void action() {
			ACLMessage message = receive(template);
			if(message != null) {
				try{
					Done d = (Done)getContentManager().extractContent(message);
					Action a = (Action)d.getAction();
					AID tn = a.getActor();
					StartNotify sn = (StartNotify) a.getAction();
					AID observed = sn.getObserved();
					notifiers.put(observed, tn);
				}
				catch(Exception fe) {
					fe.printStackTrace();
				}
			}
			else {
				block();
			}
		}
		
	} // End of inner class ControlListenerBehaviour
	
	private void proceed(AID id) {
		String pendingReplyWith = (String) pendingReplies.remove(id);
		AID tn = (AID) 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 = (MainWindow)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 = (String)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:
	 * <ol>
	 * <li> If we encounter a '*' in the expression token they match.
	 * <li> If there aren't any more characters in the subject string token they don't match.
	 * <li> If we encounter a '?' in the expression token we ignore the subject string's
	 * character and move on to the next iteration.
	 * <li> If the character in the expression token isn't equal to the character in
	 * the subject string they don't match.
	 * </ol>
	 * 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() ? 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);
	}
	
	/**
	 Inner class RequestListenerBehaviour.
	 This behaviour serves requests to start debugging agents.
	 If an agent does not exist it is put into the 
	 preload table so that it will be debugged 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(Introspector.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 DebugOn || aa instanceof DebugOff) {
					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 DebugOn) { 
				// DEBUG ON
				DebugOn requestDebugOn = (DebugOn) aa;
				// Start debugging existing agents.
				// Put non existing agents in the preload map. We will start
				// debug them as soon as they start. 
				List agentsToDebug = requestDebugOn.getCloneOfDebuggedAgents();											
				for (int i=0;i<agentsToDebug.size();i++) {
					AID aid = (AID)agentsToDebug.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 {
				// DEBUG OFF
				DebugOff requestDebugOff = (DebugOff) aa;
				List agentsToDebug = requestDebugOff.getCloneOfDebuggedAgents();											
				for (int i=0;i<agentsToDebug.size();i++) {
					AID aid = (AID)agentsToDebug.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 + -