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

📄 agentcontainerimpl.java

📁 java实现的P2P多agent中间件
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
		ServiceDescriptor[] descriptors = new ServiceDescriptor[services.size()];
		for (int i = 0; i < descriptors.length; ++i) {
			descriptors[i] = (ServiceDescriptor) services.get(i);
		}
		// This call performs the real connection to the platform and can modify the 
		// name of this container
		myServiceManager.addNode(myNodeDescriptor, descriptors);
		creationTime = System.currentTimeMillis();

		//#MIDP_EXCLUDE_BEGIN
		// If we are the master main container --> initialize the AMS and DF. Do that before booting all services 
		// since during service boot some messages may be directed to the AMS or DF
		boolean isMaster = !myProfile.getBooleanProperty(Profile.LOCAL_SERVICE_MANAGER, false);
		if(myMainContainer != null && isMaster) {
			myMainContainer.initSystemAgents(this, false);
		}
		//#MIDP_EXCLUDE_END

		// Boot all services
		for (int i = 0; i < descriptors.length; ++i) {	
			ServiceDescriptor currentServDesc = descriptors[i];
			try {
				currentServDesc.getService().boot(myProfile);
			} 
			catch(Throwable t) {
				if ( currentServDesc.isMandatory() ) {
					throw new ServiceException("An error occurred during service booting", t);
				}
				else {
					myLogger.log(Logger.WARNING,"Exception booting service " + currentServDesc.getName() + " : " + t.toString());
					t.printStackTrace();
				}
			}
		}

		//#MIDP_EXCLUDE_BEGIN
		// If we are the master main container --> start the AMS and DF.
		if(myMainContainer != null && isMaster) {
			myMainContainer.startSystemAgents(this, null);
		}
		//#MIDP_EXCLUDE_END
	}

	boolean joinPlatform() {
		//#J2ME_EXCLUDE_BEGIN
		// Redirect output if the -output option is specified
		String output = myProfile.getParameter("output", null);
		if (output != null) {
			try {
				jade.util.PerDayFileLogger fl = new jade.util.PerDayFileLogger(output);
				jade.util.PrintStreamSplitter pss = new jade.util.PrintStreamSplitter(System.out, fl);
				System.setOut(pss);
				System.setErr(pss);
			}
			catch (Exception e) {
				e.printStackTrace();
			}
		}
		//#J2ME_EXCLUDE_END

		try {
			// Perform the initial setup from the profile
			init();

			// Connect the local node to the platform and activate all the services
			startNode();
		}
		catch (IMTPException imtpe) {
			myLogger.log(Logger.SEVERE,"Communication failure while joining agent platform: " + imtpe.getMessage());
			imtpe.printStackTrace();
			endContainer();
			cleanIMTPManager();
			return false;
		}
		catch (JADESecurityException ae) {
			myLogger.log(Logger.SEVERE,"Authentication or authorization failure while joining agent platform.");
			ae.printStackTrace();
			endContainer();
			cleanIMTPManager();
			return false;
		}
		catch (Exception e) {
			myLogger.log(Logger.SEVERE,"Some problem occurred while joining agent platform.");
			e.printStackTrace();
			endContainer();
			cleanIMTPManager();
			return false;
		}

		// Create and activate agents that must be launched at bootstrap
		startBootstrapAgents();

		myLogger.log(Logger.INFO, "--------------------------------------\nAgent container " + myID + " is ready.\n--------------------------------------------");
		return true;
	}

	private void cleanIMTPManager() {
		// In case container startup failed, we clean IMTPManager resources. 
		// This is important when the JVM is not killed on JADE termination.
		if (myIMTPManager != null) {
			myIMTPManager.shutDown();
		}
	}

	private void startBootstrapAgents() {
		try {
			List l = myProfile.getSpecifiers(Profile.AGENTS);
			Iterator agentSpecifiers = l.iterator();
			while(agentSpecifiers.hasNext()) {
				Specifier s = (Specifier) agentSpecifiers.next();
				if (s.getName() != null) {
					AID agentID = new AID(s.getName(), AID.ISLOCALNAME);

					try {
						//#MIDP_EXCLUDE_BEGING
						getContainerProxy(myNodeDescriptor.getOwnerPrincipal(), myNodeDescriptor.getOwnerCredentials()).createAgent(agentID, s.getClassName(), s.getArgs());
						//#MIDP_EXCLUDE_END
						/*#MIDP_INCLUDE_BEGIN
						 String serviceName = jade.core.management.AgentManagementSlice.NAME;
						 Service svc = myServiceFinder.findService(serviceName);
						 jade.core.management.AgentManagementSlice target = (jade.core.management.AgentManagementSlice) myIMTPManager.createSliceProxy(serviceName, svc.getHorizontalInterface(), myIMTPManager.getLocalNode());
						 GenericCommand dummyCmd = new GenericCommand(null, null, null);
						 dummyCmd.setPrincipal(myNodeDescriptor.getOwnerPrincipal());
						 dummyCmd.setCredentials(myNodeDescriptor.getOwnerCredentials());
						 target.createAgent(agentID, s.getClassName(), s.getArgs(), myNodeDescriptor.getOwnerPrincipal(), null, target.CREATE_ONLY, dummyCmd);
						 #MIDP_INCLUDE_END*/
					}
					catch (Throwable t) {
						myLogger.log(Logger.SEVERE,"Cannot create agent "+s.getName()+": "+t.getMessage());
					}
				}
				else {
					myLogger.log(Logger.WARNING,"Cannot create an agent with no name. Class was "+s.getClassName());
				}              	
			}

			// Now activate all agents (this call starts their embedded threads)
			AID[] allLocalNames = localAgents.keys();
			for (int i = 0; i < allLocalNames.length; i++) {
				AID id = allLocalNames[i];

				if(!id.equals(theAMS) && !id.equals(theDefaultDF)) {
					try {
						powerUpLocalAgent(id);
					}
					catch (NotFoundException nfe) {
						// Should never happen
						nfe.printStackTrace();
					}
				}
			}

			//#J2ME_EXCLUDE_BEGIN
			// If the Misc add-on is in the classpath and the -jade_core_AgentContainerImpl_enablemonitor option is not explicitly set to false, activate a ContainerMonitorAgent
			if (myProfile.getBooleanProperty(ENABLE_MONITOR, true)) {
				AID monitorId = new AID(MONITOR_AGENT_NAME, AID.ISLOCALNAME);
				try {
					getContainerProxy(myNodeDescriptor.getOwnerPrincipal(), myNodeDescriptor.getOwnerCredentials()).createAgent(monitorId, MONITOR_AGENT_CLASS, new Object[]{this, localAgents});
					powerUpLocalAgent(monitorId);
					myLogger.log(Logger.INFO, "Container-Monitor agent activated");
				}
				catch (Throwable t) {
					// The Misc add-on is not in the classpath --> Just do nothing
				}
			}
			//#J2ME_EXCLUDE_END
		}
		catch (ProfileException pe) {
			myLogger.log(Logger.WARNING, "Error reading initial agents. "+pe);
			pe.printStackTrace();
		}
	}

	public void shutDown() {
		checkCreationTime();

		// Remove all non-system agents
		Agent[] allLocalAgents = localAgents.values();

		for(int i = 0; i < allLocalAgents.length; i++) {
			// Kill agent and wait for its termination
			Agent a = allLocalAgents[i];

			// Skip the Default DF and the AMS
			AID id = a.getAID();
			if(id.equals(getAMS()) || id.equals(getDefaultDF()))
				continue;

			//System.out.println("Killing agent "+a.getLocalName());
			//System.out.flush();
			a.doDelete();
			//System.out.println("Done. Waiting for its termination...");
			//System.out.flush();
			a.join();
			//System.out.println("Agent "+a.getLocalName()+" terminated");
			//System.out.flush();
			a.resetToolkit();
		}

		try {
			myServiceManager.removeNode(myNodeDescriptor);
			//#J2ME_EXCLUDE_BEGIN
			MainDetectionManager.unexport();
			//#J2ME_EXCLUDE_END
			myIMTPManager.shutDown();
		}
		catch(IMTPException imtpe) {
			imtpe.printStackTrace();
		}
		catch(ServiceException se) {
			se.printStackTrace();
		}

		// Release Thread resources
		myResourceManager.releaseResources();

		// Notify the JADE Runtime that the container has terminated execution
		endContainer();
	}

	private void checkCreationTime() {
		long time = System.currentTimeMillis();
		if ((time - creationTime) < 3000) {
			try {Thread.sleep(3000 - (time - creationTime));} catch (Exception e) {}
		}
	}

	// Call Runtime.instance().endContainer()
	// with the security priviledges of AgentContainerImpl
	// no matter priviledges of who originaltely triggered this action
	private void endContainer() {
		try {
			Runtime.instance().endContainer();
		} catch(Exception e) {
			e.printStackTrace();
		}
	}


	////////////////////////////////////////////
	// AgentToolkit interface implementation
	////////////////////////////////////////////

	public Location here() {
		return myID;
	}

	/**
	 Issue a SEND_MESSAGE VerticalCommand for each receiver
	 */
	public void handleSend(ACLMessage msg, AID sender, boolean needClone) {
		Iterator it = msg.getAllIntendedReceiver();
		// If there are multiple receivers the message must always be cloned
		// since the MessageManager will modify it. If there is a single 
		// receiver we clone it or not depending on the needClone parameter
		boolean isFirst = true;
		while (it.hasNext()) {
			AID receiver = (AID)it.next();
			if (isFirst) {
				needClone = needClone || it.hasNext();
				isFirst = false;
			}
			GenericCommand cmd = new GenericCommand(jade.core.messaging.MessagingSlice.SEND_MESSAGE, jade.core.messaging.MessagingSlice.NAME, null);
			cmd.addParam(sender);
			ACLMessage toBeSent = null;
			if (needClone) {
				toBeSent = (ACLMessage) msg.clone();
			}
			else {
				toBeSent = msg;
			}
			isFirst = false;
			GenericMessage gmsg = new GenericMessage(toBeSent);
			cmd.addParam(gmsg);
			cmd.addParam(receiver);
			// Set the credentials of the sender
			initCredentials(cmd, sender);
			Object ret = myCommandProcessor.processOutgoing(cmd);
			if (ret != null) {
				if (ret instanceof Throwable) {
					// The SEND_MESSAGE VerticalCommand was blocked by some Filter 
					// before reaching the Messaging Souce Sink --> Issue
					// a NOTIFY_FAILURE VerticalCommand to notify the sender
					cmd = new GenericCommand(jade.core.messaging.MessagingSlice.NOTIFY_FAILURE, jade.core.messaging.MessagingSlice.NAME, null);
					cmd.addParam(gmsg);
					cmd.addParam(receiver);
					cmd.addParam(new InternalError("Message blocked: "+ret));
					ret = myCommandProcessor.processOutgoing(cmd);
					if (ret != null) {
						if (ret instanceof Throwable) {
							((Throwable) ret).printStackTrace();
						}
					}
				}
			}
		}

	}

	//#MIDP_EXCLUDE_BEGIN
	// FIXME: to be removed
	public void handlePosted(AID agentID, ACLMessage msg) {
		GenericCommand cmd = new GenericCommand(jade.core.event.NotificationSlice.NOTIFY_POSTED, jade.core.event.NotificationSlice.NAME, null);
		cmd.addParam(msg);
		cmd.addParam(agentID);

		Object ret = myCommandProcessor.processOutgoing(cmd);
		if (ret != null) {
			if (ret instanceof Throwable) {
				((Throwable) ret).printStackTrace();
			}
		}
	}
	//#MIDP_EXCLUDE_END

	//#MIDP_EXCLUDE_BEGIN
	/**
	 Issue a NOTIFY_RECEIVED VerticalCommand
	 */
	public void handleReceived(AID agentID, ACLMessage msg) {
		GenericCommand cmd = new GenericCommand(jade.core.event.NotificationSlice.NOTIFY_RECEIVED, jade.core.event.NotificationSlice.NAME, null);
		cmd.addParam(msg);
		cmd.addParam(agentID);
		// No security check is meaningful on this action --> don't even set the Credentials

		Object ret = myCommandProcessor.processOutgoing(cmd);
		if (ret != null) {
			if (ret instanceof Throwable) {
				((Throwable) ret).printStackTrace();
			}
		}

	}
	//#MIDP_EXCLUDE_END

	//#MIDP_EXCLUDE_BEGIN
	public void handleBehaviourAdded(AID agentID, Behaviour b) {
		GenericCommand cmd = new GenericCommand(jade.core.event.NotificationSlice.NOTIFY_BEHAVIOUR_ADDED, jade.core.event.NotificationSlice.NAME, null);
		cmd.addParam(agentID);
		cmd.addParam(b);
		// No security check is meaningful on this action --> don't even set the Credentials

		Object ret = myCommandProcessor.processOutgoing(cmd);
		if (ret != null) {
			if (ret instanceof Throwable) {
				((Throwable) ret).printStackTrace();
			}
		}
	}
	//#MIDP_EXCLUDE_END

	//#MIDP_EXCLUDE_BEGIN
	public void handleBehaviourRemoved(AID agentID, Behaviour b) {
		GenericCommand cmd = new GenericCommand(jade.core.event.NotificationSlice.NOTIFY_BEHAVIOUR_REMOVED, jade.core.event.NotificationSlice.NAME, null);
		cmd.addParam(agentID);
		cmd.addParam(b);
		// No security check is meaningful on this action --> don't even set the Credentials

		Object ret = myCommandProcessor.processOutgoing(cmd);
		if (ret != null) {
			if (ret instanceof Throwable) {
				((Throwable) ret).printStackTrace();
			}
		}
	}
	//#MIDP_EXCLUDE_END

	//#MIDP_EXCLUDE_BEGIN
	public void handleChangeBehaviourState(AID agentID, Behaviour b, String from, String to) {
		GenericCommand cmd = new GenericCommand(jade.core.event.NotificationSlice.NOTIFY_CHANGED_BEHAVIOUR_STATE, jade.core.event.NotificationSlice.NAME, null);
		cmd.addParam(agentID);
		cmd.addParam(b);
		cmd.addParam(from);
		cmd.addParam(to);
		// No security check is meaningful on this action --> don't even set the Credentials

		Object ret = myCommandProcessor.processOutgoing(cmd);
		if (ret != null) {
			if (ret instanceof Throwable) {
				((Throwable) ret).printStackTrace();
			}
		}
	}
	//#MIDP_EXCLUDE_END

	//#MIDP_EXCLUDE_BEGIN
	// FIXME: to be removed
	public void handleChangedAgentPrincipal(AID agentID, JADEPrincipal oldPrincipal, Credentials creds) {

		/***

		 myNotificationManager.fireEvent(NotificationManager.CHANGED_AGENT_PRINCIPAL,
		 new Object[]{agentID, oldPrincipal, (AgentPrincipal)certs.getIdentityCertificate().getSubject()});
		 try {
		 myPlatform.changedAgentPrincipal(agentID, certs);
		 }
		 catch (IMTPException re) {
		 re.printStackTrace();
		 }
		 catch (NotFoundException nfe) {
		 nfe.printStackTrace();
		 }

		 ***/
	}
	//#MIDP_EXCLUDE_END


	public void handleChangedAgentState(AID agentID, int oldState, int newState) {

⌨️ 快捷键说明

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