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

📄 ams.java

📁 java实现的P2P多agent中间件
💻 JAVA
📖 第 1 页 / 共 4 页
字号:

						// Send the list of the MTPs installed on this container
						Iterator mtps = myPlatform.containerMTPs(cid).iterator();
						while (mtps.hasNext()) {
							AddedMTP amtp = new AddedMTP();
							amtp.setAddress(((MTPDescriptor) mtps.next()).getAddresses()[0]);
							amtp.setWhere(cid);

							er = new EventRecord(amtp, here());
							o = new Occurred();
							o.setWhat(er);

							try {
								getContentManager().fillContent(toolNotification, o);
								send(toolNotification);
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					}

					// Send all agent names, along with their container name.
					AID[] agents = myPlatform.agentNames();
					for (int i = 0; i < agents.length; i++) {

						AID agentName = agents[i];
						ContainerID cid = myPlatform.getContainerID(agentName);
						AMSAgentDescription amsd = myPlatform.getAMSDescription(agentName);

						BornAgent ba = new BornAgent();
						// Note that "agentName" may not include agent addresses
						AID id = agentName;
						if (amsd != null) {
							if (amsd.getName() != null) {
								id = amsd.getName();
							}
							ba.setState(amsd.getState());
							ba.setOwnership(amsd.getOwnership());
							ba.setClassName(id.getAllUserDefinedSlot().getProperty(AID.AGENT_CLASSNAME));
						}
						ba.setAgent(id);
						ba.setWhere(cid);

						er = new EventRecord(ba, here());
						o = new Occurred();
						o.setWhat(er);

						try {
							getContentManager().fillContent(toolNotification, o);
							send(toolNotification);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}

					// Notification of the APDescription
					PlatformDescription ap = new PlatformDescription();
					ap.setPlatform(getDescriptionAction(null));

					er = new EventRecord(ap, here());
					o = new Occurred();
					o.setWhat(er);

					try {
						getContentManager().fillContent(toolNotification, o);
						send(toolNotification);
					} catch (Exception e) {
						e.printStackTrace();
					}

					myPlatform.addTool(newTool);

				} catch (NotFoundException nfe) {
					nfe.printStackTrace();
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else
				block();

		}

	} // End of RegisterToolBehaviour inner class

	/**
	 Inner calss DeregisterToolBehaviour.
	 This behaviour handles tools un-subscriptions.
	 */
	private class DeregisterToolBehaviour extends CyclicBehaviour {

		private MessageTemplate cancellationTemplate;

		DeregisterToolBehaviour() {

			MessageTemplate mt1 = MessageTemplate.MatchLanguage(FIPANames.ContentLanguage.FIPA_SL0);
			MessageTemplate mt2 = MessageTemplate.MatchOntology(IntrospectionOntology.NAME);
			MessageTemplate mt12 = MessageTemplate.and(mt1, mt2);

			mt1 = MessageTemplate.MatchReplyWith("tool-cancellation");
			mt2 = MessageTemplate.MatchPerformative(ACLMessage.CANCEL);
			cancellationTemplate = MessageTemplate.and(mt1, mt2);
			cancellationTemplate = MessageTemplate.and(cancellationTemplate, mt12);

		}

		public void action() {

			// Receive 'cancel' ACL messages.
			ACLMessage current = receive(cancellationTemplate);
			if (current != null) {
				// FIXME: Should parse the content

				// Remove this tool from tools agent group.
				myPlatform.removeTool(current.getSender());

			} else
				block();

		}

	} // End of DeregisterToolBehaviour inner class

	/**
	 Inner interface Handler.
	 Perform additional operations related to a given platform event
	 */
	private interface Handler {
		void handle(Event ev);
	} // END of Handler inner interface

	/**
	 Inner class EventManager.
	 This behaviour notifies
	 - all registered tools about all platform events
	 - the agent that had requested the AMS to perform an action
	 about the platform event forced by that action. Note that
	 this is done only for actions that produce an "asynchronous
	 event".
	 */
	private class EventManager extends CyclicBehaviour {

		private Map handlers = new HashMap();

		public EventManager() {
			handlers.put(RemovedContainer.NAME, new Handler() {
				public void handle(Event ev) {
					// If this event was forced by an action requested by
					// an agent --> notify him.
					RemovedContainer rc = (RemovedContainer) ev;
					ContainerID cid = rc.getContainer();
					ACLMessage notification = (ACLMessage) pendingRemovedContainers.remove(cid);
					if (notification != null) {
						send(notification);
					}
				}
			});
			handlers.put(DeadAgent.NAME, new Handler() {
				public void handle(Event ev) {
					// If this event was forced by an action requested by
					// an agent --> notify him.
					DeadAgent da = (DeadAgent) ev;
					AID agentID = da.getAgent();
					ACLMessage notification = (ACLMessage) pendingDeadAgents.remove(agentID);
					if (notification != null) {
						send(notification);
					}
				}
			});
			handlers.put(MovedAgent.NAME, new Handler() {
				public void handle(Event ev) {
					// If this event was forced by an action requested by
					// an agent --> notify him.
					MovedAgent ma = (MovedAgent) ev;
					AID agentID = ma.getAgent();
					ACLMessage notification = (ACLMessage) pendingMovedAgents.remove(agentID);
					if (notification != null) {
						send(notification);
					}
				}
			});
			handlers.put(BornAgent.NAME, new Handler() {
				public void handle(Event ev) {
					// If this event was forced by an action requested by
					// an agent --> notify him.
					BornAgent ba = (BornAgent) ev;
					AID agentID = ba.getAgent();
					// The requested action could be a CreateAgent or a CloneAgent
					ACLMessage notification = (ACLMessage) pendingNewAgents.remove(agentID);
					if (notification == null) {
						notification = (ACLMessage) pendingClonedAgents.remove(agentID);
					}
					if (notification != null) {
						send(notification);
					}
				}
			});
			handlers.put(PlatformDescription.NAME, new Handler() {
				public void handle(Event ev) {
					// Update the PlatformDescription txt file.
					writeAPDescription(((PlatformDescription) ev).getPlatform());
				}
			});
		}

		public void action() {
			try {
				EventRecord er = (EventRecord) eventQueue.get();
				if (er != null) {
					// Perform event-specific actions (if any)
					Event ev = er.getWhat();
					if (logger.isLoggable(Logger.FINE))
						logger.log(Logger.FINE, "EventManager serving event " + ev.getName());
					Handler handler = (Handler) handlers.get(ev.getName());
					if (handler != null) {
						handler.handle(ev);
					}

					// Notify all tools about the event
					notifyTools(er);
				} else {
					block();
				}
			} catch (Throwable t) {
				// Should never happen
				t.printStackTrace();
			}
		}
	} // END of EventManager inner class

	private void notifyTools(EventRecord er) throws Exception {
		toolNotification.clearAllReceiver();
		AID[] allTools = myPlatform.agentTools();
		for (int i = 0; i < allTools.length; i++) {
			AID tool = allTools[i];
			toolNotification.addReceiver(tool);
		}
		Occurred o = new Occurred();
		o.setWhat(er);
		getContentManager().fillContent(toolNotification, o);
		send(toolNotification);
	}

	//////////////////////////////////////////////////////////////////
	// Platform events input methods.
	// The following methods are called when a platform event is notified
	// to the Main and are executed outside the AMS thread.
	// They result in preparing a proper IntrospectionOntology event (i.e. a
	// description of the event that has just happened) and inserting it in
	// AMS event queue. The EventManager behaviour will handle them within
	// the AMS thread.
	//////////////////////////////////////////////////////////////////

	public void resetEvents(boolean sendSnapshot) {
		// FIXME: in this method here() does not work since the agent toolkit is
		// not yet initialized.

		// GC-ADD-18022007-START
		queueFeeder = new AMSEventQueueFeeder(eventQueue, here());
		myPlatform.addListener(queueFeeder);
		// GC-ADD-18022007-END
		
		// Put the initial event in the event queue
		eventQueue.clear();
		ResetEvents re = new ResetEvents();
		EventRecord er = new EventRecord(re, here());
		eventQueue.put(er);

		if (sendSnapshot) {

			try {
				// Send back the whole container list.
				ContainerID[] ids = myPlatform.containerIDs();
				for (int i = 0; i < ids.length; i++) {
					ContainerID cid = ids[i];

					AddedContainer ac = new AddedContainer();
					ac.setContainer(cid);
					ac.setOwnership(getContainerOwnership(cid));

					er = new EventRecord(ac, here());
					eventQueue.put(er);

					// Send the list of the MTPs installed on this container
					Iterator mtps = myPlatform.containerMTPs(cid).iterator();
					while (mtps.hasNext()) {
						AddedMTP amtp = new AddedMTP();
						amtp.setAddress(((MTPDescriptor) mtps.next()).getAddresses()[0]);
						amtp.setWhere(cid);

						er = new EventRecord(amtp, here());
						eventQueue.put(er);
					}
				}

				// The PlatformDescription has changed --> Generate a suitable event
				PlatformDescription ap = new PlatformDescription();
				ap.setPlatform(getDescriptionAction(null));
				er = new EventRecord(ap, here());
				eventQueue.put(er);

				// Send all agent names, along with their container name.
				AID[] agents = myPlatform.agentNames();
				for (int j = 0; j < agents.length; j++) {
					AID agentName = agents[j];
					// FIXME: Check if we have to lock the AgentDescriptor
					AMSAgentDescription amsd = myPlatform.getAMSDescription(agentName);
					if (! amsd.getState().equals(AMSAgentDescription.LATENT)) {

						ContainerID c = myPlatform.getContainerID(agentName);
	
						BornAgent ba = new BornAgent();
						// Note that "agentName" may not include agent addresses
						AID id = agentName;
						if (amsd != null) {
							if (amsd.getName() != null) {
								id = amsd.getName();
							}
							ba.setState(amsd.getState());
							ba.setOwnership(amsd.getOwnership());
						}
						ba.setAgent(id);
						ba.setWhere(c);
	
						er = new EventRecord(ba, here());
						eventQueue.put(er);
					}
				}
			} catch (NotFoundException nfe) {
				// It should never happen
				nfe.printStackTrace();
			}
		}
	}

	// GC-ADD-18022007-START
	public void setQueueFeeder(AMSEventQueueFeeder feeder) {
		queueFeeder = feeder;
		queueFeeder.setAms(this);
		eventQueue = queueFeeder.getQueue();
	}
	
	public AMSEventQueueFeeder getQueueFeeder() {
		return queueFeeder;
	}
	// GC-ADD-18022007-START
	
	/**
	 Put a BornAgent event in the AMS event queue
	 *
	public void bornAgent(PlatformEvent ev) {
		if (logger.isLoggable(Logger.CONFIG))
			logger.log(Logger.CONFIG, ev.toString());
		ContainerID cid = ev.getContainer();
		AID agentID = ev.getAgent();
		String ownership = ev.getNewOwnership();

		BornAgent ba = new BornAgent();
		ba.setAgent(agentID);
		ba.setWhere(cid);
		ba.setState(AMSAgentDescription.ACTIVE);
		ba.setOwnership(ownership);
		ba.setClassName((String) agentID.getAllUserDefinedSlot().get(AID.AGENT_CLASSNAME));

		EventRecord er = new EventRecord(ba, here());
		er.setWhen(ev.getTime());
		eventQueue.put(er);
	}*/

⌨️ 快捷键说明

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