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

📄 ams.java

📁 java实现的P2P多agent中间件
💻 JAVA
📖 第 1 页 / 共 4 页
字号:
					sendFailureNotification(kc, cid, new InternalError("Container unreachable. " + ue.getMessage()));
				} catch (Throwable t) {
					// Send failure notification to the requester if any
					sendFailureNotification(kc, cid, new InternalError(t.getMessage()));
				}
			}
		};

		auxThread.start();
	}

	// SHUTDOWN PLATFORM
	void shutdownPlatformAction(ShutdownPlatform sp, final AID requester, final JADEPrincipal requesterPrincipal, final Credentials requesterCredentials) throws FIPAException {
		if (logger.isLoggable(Logger.FINE))
			logger.log(Logger.FINE, "Agent " + requester + " requesting Shutdown-platform ");

		// Notify a SHUTDOWN_PLATFORM_REQUESTED introspection event to all tools
		ShutdownPlatformRequested spr = new ShutdownPlatformRequested();
		EventRecord er = new EventRecord(spr, here());
		er.setWhen(new Date());
		try {
			notifyTools(er);
		} catch (Exception e) {
			// Should never happen 
			e.printStackTrace();
		}
		
		Thread auxThread = new Thread() {
			public void run() {
				try {
					myPlatform.shutdownPlatform(requesterPrincipal, requesterCredentials);
				} catch (JADESecurityException ae) {
					if (logger.isLoggable(Logger.SEVERE))
						logger.log(Logger.SEVERE, "Agent " + requester.getName() + " does not have permission to perform action Shutdown-Platform: " + ae);
				}
			}
		};

		auxThread.start();
	}

	// INSTALL MTP
	MTPDescriptor installMTPAction(InstallMTP im, AID requester) throws FIPAException {
		if (logger.isLoggable(Logger.FINE))
			logger.log(Logger.FINE, "Agent " + requester + " requesting Install-MTP");
		// FIXME: Permissions for this action are not yet defined
		try {
			return myPlatform.installMTP(im.getAddress(), im.getContainer(), im.getClassName());
		} catch (NotFoundException nfe) {
			throw new InternalError("Container not found. " + nfe.getMessage());
		} catch (UnreachableException ue) {
			throw new InternalError("Container unreachable. " + ue.getMessage());
		} catch (MTPException mtpe) {
			throw new InternalError("Error in MTP installation. " + mtpe.getMessage());
		}
	}

	// UNINSTALL MTP
	void uninstallMTPAction(UninstallMTP um, AID requester) throws FIPAException {
		if (logger.isLoggable(Logger.FINE))
			logger.log(Logger.FINE, "Agent " + requester + " requesting Uninstall-MTP");
		// FIXME: Permissions for this action are not yet defined
		try {
			myPlatform.uninstallMTP(um.getAddress(), um.getContainer());
		} catch (NotFoundException nfe) {
			throw new InternalError("Container not found. " + nfe.getMessage());
		} catch (UnreachableException ue) {
			throw new InternalError("Container unreachable. " + ue.getMessage());
		} catch (MTPException mtpe) {
			throw new InternalError("Error in MTP de-installation. " + mtpe.getMessage());
		}
	}

	// SNIFF ON
	void sniffOnAction(SniffOn so, AID requester) throws FIPAException {
		if (logger.isLoggable(Logger.FINE))
			logger.log(Logger.FINE, "Agent " + requester + " requesting Sniff-on");
		// FIXME: Permissions for this action are not yet defined
		try {
			myPlatform.sniffOn(so.getSniffer(), so.getCloneOfSniffedAgents());
		} catch (NotFoundException nfe) {
			throw new InternalError("Agent not found. " + nfe.getMessage());
		} catch (UnreachableException ue) {
			throw new InternalError("Container unreachable. " + ue.getMessage());
		}
	}

	// SNIFF OFF
	void sniffOffAction(SniffOff so, AID requester) throws FIPAException {
		if (logger.isLoggable(Logger.FINE))
			logger.log(Logger.FINE, "Agent " + requester + " requesting Sniff-off");
		// FIXME: Permissions for this action are not yet defined
		try {
			myPlatform.sniffOff(so.getSniffer(), so.getCloneOfSniffedAgents());
		} catch (NotFoundException nfe) {
			throw new InternalError("Agent not found. " + nfe.getMessage());
		} catch (UnreachableException ue) {
			throw new InternalError("Container unreachable. " + ue.getMessage());
		}
	}

	// DEBUG ON
	void debugOnAction(DebugOn don, AID requester) throws FIPAException {
		if (logger.isLoggable(Logger.FINE))
			logger.log(Logger.FINE, "Agent " + requester + " requesting Debug-on");
		// FIXME: Permissions for this action are not yet defined
		try {
			myPlatform.debugOn(don.getDebugger(), don.getCloneOfDebuggedAgents());
		} catch (NotFoundException nfe) {
			throw new InternalError("Agent not found. " + nfe.getMessage());
		} catch (UnreachableException ue) {
			throw new InternalError("Container unreachable. " + ue.getMessage());
		}
	}

	// DEBUG OFF
	void debugOffAction(DebugOff doff, AID requester) throws FIPAException {
		if (logger.isLoggable(Logger.FINE))
			logger.log(Logger.FINE, "Agent " + requester + " requesting Debug-off");
		// FIXME: Permissions for this action are not yet defined
		try {
			myPlatform.debugOff(doff.getDebugger(), doff.getCloneOfDebuggedAgents());
		} catch (NotFoundException nfe) {
			throw new InternalError("Agent not found. " + nfe.getMessage());
		} catch (UnreachableException ue) {
			throw new InternalError("Container unreachable. " + ue.getMessage());
		}
	}

	// WHERE IS AGENT
	Location whereIsAgentAction(WhereIsAgentAction wia, AID requester) throws FIPAException {
		if (logger.isLoggable(Logger.FINE))
			logger.log(Logger.FINE, "Agent " + requester + " requesting Where-is-agent");
		// FIXME: Permissions for this action are not yet defined
		try {
			return myPlatform.getContainerID(wia.getAgentIdentifier());
		} catch (NotFoundException nfe) {
			throw new InternalError("Agent not found. " + nfe.getMessage());
		}
	}

	// QUERY PLATFORM LOCATIONS
	List queryPlatformLocationsAction(QueryPlatformLocationsAction qpl, AID requester) throws FIPAException {
		if (logger.isLoggable(Logger.FINE))
			logger.log(Logger.FINE, "Agent " + requester + " requesting Query-platform-locations");
		// FIXME: Permissions for this action are not yet defined
		ContainerID[] ids = myPlatform.containerIDs();
		List l = new ArrayList();
		for (int i = 0; i < ids.length; ++i) {
			l.add(ids[i]);
		}
		return l;
	}

	// QUERY AGENTS ON LOCATION
	List queryAgentsOnLocationAction(QueryAgentsOnLocation qaol, AID requester) throws FIPAException {
		if (logger.isLoggable(Logger.FINE))
			logger.log(Logger.FINE, "Agent " + requester + " requesting Query-agents-on-location");
		// FIXME: Permissions for this action are not yet defined
		try {
			return myPlatform.containerAgents((ContainerID) qaol.getLocation());
		} catch (NotFoundException nfe) {
			throw new InternalError("Location not found. " + nfe.getMessage());
		}
	}

	//////////////////////////////////////////////////////////////////
	// Methods implementing the actions of the FIPAManagementOntology.
	// All these methods
	// - extract the necessary information from the requested Action
	//   object and check whether mandatory slots are present.
	// - Call the corresponding method of the AgentManager using the
	//   permissions of the requester agent.
	// - Convert eventual JADE-internal Exceptions into proper FIPAException.
	// These methods are package-scoped as they are called by the
	// AMSFipaAgentManagementBehaviour.
	//////////////////////////////////////////////////////////////////

	// REGISTER
	void registerAction(Register r, AID requester) throws FIPAException {
		final AMSAgentDescription amsd = (AMSAgentDescription) r.getDescription();
		// Check mandatory slots
		AID id = amsd.getName();
		if (logger.isLoggable(Logger.FINE))
			logger.log(Logger.FINE, "Agent " + requester + " requesting AMS-registration for " + id);
		if (id == null || id.getName() == null || id.getName().length() == 0) {
			throw new MissingParameter(FIPAManagementVocabulary.AMSAGENTDESCRIPTION, FIPAManagementVocabulary.DFAGENTDESCRIPTION_NAME);
		}

		try {
			myPlatform.amsRegister(amsd);
		} catch (AlreadyRegistered ar) {
			throw ar;
		} catch (JADESecurityException ae) {
			if (logger.isLoggable(Logger.SEVERE))
				logger.log(Logger.SEVERE, "Agent " + requester.getName() + " does not have permission to perform action Register");
			throw new Unauthorised();
		} catch (Exception e) {
			e.printStackTrace();
			throw new InternalError("Unexpected exception. " + e.getMessage());
		}
	}

	// DEREGISTER
	void deregisterAction(Deregister d, AID requester) throws FIPAException {
		final AMSAgentDescription amsd = (AMSAgentDescription) d.getDescription();
		// Check mandatory slots
		AID id = amsd.getName();
		if (logger.isLoggable(Logger.FINE))
			logger.log(Logger.FINE, "Agent " + requester + " requesting AMS-deregistration for " + id);
		if (id == null || id.getName() == null || id.getName().length() == 0) {
			throw new MissingParameter(FIPAManagementVocabulary.AMSAGENTDESCRIPTION, FIPAManagementVocabulary.DFAGENTDESCRIPTION_NAME);
		}

		try {
			myPlatform.amsDeregister(amsd);
		} catch (NotRegistered nr) {
			throw nr;
		} catch (JADESecurityException ae) {
			if (logger.isLoggable(Logger.SEVERE))
				logger.log(Logger.SEVERE, "Agent " + requester.getName() + " does not have permission to perform action Deregister");
			throw new Unauthorised();
		} catch (Exception e) {
			e.printStackTrace();
			throw new InternalError("Unexpected exception. " + e.getMessage());
		}
	}

	// MODIFY
	void modifyAction(Modify m, AID requester) throws FIPAException {
		final AMSAgentDescription amsd = (AMSAgentDescription) m.getDescription();
		// Check mandatory slots
		AID id = amsd.getName();
		if (logger.isLoggable(Logger.FINE)) {
			logger.log(Logger.FINE, "Agent " + requester + " requesting AMS-modification for " + id);
			logger.log(Logger.FINE, "New state is " + amsd.getState() + ". New ownership is " + amsd.getOwnership());
		}
		if (id == null || id.getName() == null || id.getName().length() == 0) {
			throw new MissingParameter(FIPAManagementVocabulary.AMSAGENTDESCRIPTION, FIPAManagementVocabulary.DFAGENTDESCRIPTION_NAME);
		}

		try {
			myPlatform.amsModify(amsd);
		} catch (NotRegistered nr) {
			throw nr;
		} catch (UnreachableException ue) {
			throw new InternalError("Container not reachable. " + ue.getMessage());
		} catch (NotFoundException nfe) {
			throw new InternalError("Agent not found. " + nfe.getMessage());
		} catch (JADESecurityException ae) {
			if (logger.isLoggable(Logger.SEVERE))
				logger.log(Logger.SEVERE, "Agent " + requester.getName() + " does not have permission to perform action Modify");
			throw new Unauthorised();
		} catch (Exception e) {
			e.printStackTrace();
			throw new InternalError("Unexpected exception. " + e.getMessage());
		}
	}

	// SEARCH
	List searchAction(Search s, AID requester) {
		if (logger.isLoggable(Logger.FINE))
			logger.log(Logger.FINE, "Agent " + requester + " requesting AMS-search");
		return myPlatform.amsSearch((AMSAgentDescription) s.getDescription(), getActualMaxResults(s.getConstraints()));
	}

	/**
	 * @return
	 * <ul>
	 * <li> 1 if constraints.maxResults == null (according to FIPA specs)
	 * <li> The AMS internal max result limit if constraints.maxResults < 0 (the FIPA specs requires it to be
	 * infinite, but for practical reason we prefer to limit it)
	 * <li> constraints.maxResults otherwise
	 * </ul>
	 **/
	private long getActualMaxResults(SearchConstraints constraints) {
		long maxResult = (constraints.getMaxResults() == null ? 1 : constraints.getMaxResults().longValue());
		maxResult = (maxResult < 0 ? amsMaxResults : maxResult); // limit the max num of results
		return maxResult;
	}

	// GET_DESCRIPTION
	APDescription getDescriptionAction(AID requester) {
		if (requester != null) {
			if (logger.isLoggable(Logger.FINE))
				logger.log(Logger.FINE, "Agent " + requester + " requesting AMS-get-description");
		}
		theProfile.clearAllAPServices(); // clear all the services and recreate the new APDescription
		MTPDescriptor dr;
		for (Iterator mtps = platformMTPs().iterator(); mtps.hasNext();) {
			dr = (MTPDescriptor) mtps.next();
			// convert from an internal MTPDescriptor to a FIPA APService
			theProfile.addAPServices(new APService(dr.getName(), dr.getAddresses()));
		}
		return theProfile;
	}

	//////////////////////////////////////////////////////////////////
	// TOOLS REGISTRATION and NOTIFICATION
	//////////////////////////////////////////////////////////////////
	/**
	 Inner calss RegisterToolBehaviour.
	 This behaviour handles subscriptions of tools i.e. agents
	 to be notified about platform events.
	 */
	private class RegisterToolBehaviour extends CyclicBehaviour {

		private MessageTemplate subscriptionTemplate;

		RegisterToolBehaviour() {

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

			mt1 = MessageTemplate.MatchReplyWith("tool-subscription");
			mt2 = MessageTemplate.MatchPerformative(ACLMessage.SUBSCRIBE);
			subscriptionTemplate = MessageTemplate.and(mt1, mt2);
			subscriptionTemplate = MessageTemplate.and(subscriptionTemplate, mt12);

		}

		public void action() {

			// Receive 'subscribe' ACL messages.
			ACLMessage current = receive(subscriptionTemplate);
			if (current != null) {

				// FIXME: Should parse 'iota ?x ...'

				// Get new tool name from subscription message
				AID newTool = current.getSender();
				toolNotification.clearAllReceiver();
				toolNotification.addReceiver(newTool);

				try {
					// Send a 'Reset' meta-event
					ResetEvents re = new ResetEvents();
					EventRecord er = new EventRecord(re, here());
					Occurred o = new Occurred();
					o.setWhat(er);

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

					// 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());
						o = new Occurred();
						o.setWhat(er);

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

⌨️ 快捷键说明

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