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

📄 df.java

📁 java实现的P2P多agent中间件
💻 JAVA
📖 第 1 页 / 共 5 页
字号:
			try {
				p.load((String) args[0]);
				sAutocleanup = p.getProperty(AUTOCLEANUP, sAutocleanup);
				sPoolsize = p.getProperty(POOLSIZE, sPoolsize);
				sMaxLeaseTime = p.getProperty(MAX_LEASE_TIME, sMaxLeaseTime);
				sMaxResults = p.getProperty(MAX_RESULTS, sMaxResults);
				sDisableValidation = p.getProperty(DISABLE_VALIDATION, sDisableValidation);
				dbUrl = p.getProperty(DB_URL, dbUrl);
				dbDriver = p.getProperty(DB_DRIVER, dbDriver);
				dbUsername = p.getProperty(DB_USERNAME, dbUsername);
				dbPassword = p.getProperty(DB_PASSWORD, dbPassword);
				kbFactClass = p.getProperty(KB_FACTORY, kbFactClass);
				sDBDefault = p.getProperty(DB_DEFAULT, sDBDefault);
				sCleanTables = p.getProperty(DB_CLEANTABLES, sCleanTables);
				sDBAbortOnError = p.getProperty(DB_ABORTONERROR, sDBAbortOnError);
			}
			catch (Exception e) {
				logger.log(Logger.SEVERE,"Error loading configuration from file "+args[0]+" ["+e+"].");
			}
		}
		
		// ---------- Max lease time ----------
		try {
			maxLeaseTime = new Date(Long.parseLong(sMaxLeaseTime));
		}
		catch (Exception e) {
			// Keep default
		}
		logger.log(Logger.CONFIG, "DF Max lease time = "+(maxLeaseTime != null ? ISO8601.toRelativeTimeString(maxLeaseTime.getTime()) : "infinite"));
		
		// ---------- Max search results ----------
		try {
			maxResultLimit = Integer.parseInt(sMaxResults);
			if(maxResultLimit < 0){
				maxResultLimit = Integer.parseInt(DEFAULT_MAX_RESULTS);
				logger.log(Logger.WARNING,"The maxResult parameter of the DF Search Constraints can't be a negative value. It has been set to the default value: " + DEFAULT_MAX_RESULTS);
			}else if(maxResultLimit > Integer.parseInt(DEFAULT_MAX_RESULTS)){
				logger.log(Logger.WARNING,"Setting the maxResult of the DF Search Constraint to large values can cause low performance or system crash !!");
			}
		}
		catch (Exception e) {
			// Keep default
		}
		logger.log(Logger.CONFIG, "DF Max search result = "+maxResultLimit);
				
		// ---------- Knowledge Base ----------
		StringBuffer sb = new StringBuffer("DF KB configuration:\n");
		
		// ---------- KB Factory ----------
		DFKBFactory kbFactory = new DFKBFactory(); // Default factory
		if (kbFactClass != null) {
			try {
				Object o = Class.forName(kbFactClass).newInstance();
				if (o instanceof DFKBFactory) {
					kbFactory = (DFKBFactory)o;
					sb.append("- Factory class = " + kbFactClass);
					sb.append('\n');					
				} 
				else {
					logger.log(Logger.SEVERE,"The class " + kbFactClass + " is not a valid KB factory for the DF.");
				}
			} 
			catch (Exception e) {
				logger.log(Logger.SEVERE, "Error loading class " + kbFactClass + ". "+e);
			}		
		}
		
		// ---------- Persistent KB ----------
		boolean cleanTables = getBooleanProperty(sCleanTables, DB_CLEANTABLES);
		if (isRestarting()) {
			// Avoid cleaing tables if we are restarting
			cleanTables = false;
		}
		boolean dbDefault = getBooleanProperty(sDBDefault, DB_DEFAULT);
		boolean dbAbortOnError = getBooleanProperty(sDBAbortOnError, DB_ABORTONERROR);
		
		if (dbDefault) {
			sb.append("- Type = persistent using internal HSQL database\n");
			try {
				agentDescriptions = kbFactory.getDFDBKB(maxResultLimit, null, null, null, null, cleanTables);
			}
			catch (Exception e) {
				logger.log(Logger.SEVERE,"Error creating persistent KB based on internal HSQLDB database", e);
				if (dbAbortOnError) {
					doDelete();
					return;
				}
				else {
					logger.log(Logger.WARNING, "DF using volatile (in-memory) KB");
					sb = new StringBuffer("DF KB configuration:\n");
				}
			}
		}
		
		if (agentDescriptions == null && dbUrl != null) {
			if(logger.isLoggable(Logger.CONFIG)){
				sb.append("- Type = persistent\n");
				sb.append("- DB url = "+dbUrl);
				sb.append('\n');
				sb.append("- DB driver = "+dbDriver);
				sb.append('\n');
				sb.append("- DB username = "+dbUsername);
				sb.append('\n');
				sb.append("- DB password = "+dbPassword);
				sb.append('\n');
			}
			try {
				agentDescriptions = kbFactory.getDFDBKB(maxResultLimit, dbDriver, dbUrl, dbUsername, dbPassword, cleanTables);
			}
			catch (Exception e) {
				logger.log(Logger.SEVERE,"Error creating persistent KB (+url = "+getValue(dbUrl)+", driver = "+getValue(dbDriver)+", username = "+getValue(dbUsername)+", password = "+getValue(dbPassword)+")", e);
				if (dbAbortOnError) {
					doDelete();
					return;
				}
				else {
					logger.log(Logger.WARNING, "DF using volatile (in-memory) KB");
					sb = new StringBuffer("DF KB configuration:\n");
				}
			}
		}

		// ---------- Volatile (in-memory) KB ----------
		if (agentDescriptions == null){
			sb.append("- Type = volatile\n");
			agentDescriptions = kbFactory.getDFMemKB(maxResultLimit);
			if (sPoolsize != null) {
				logger.log(Logger.WARNING, "Ignoring pool-size indication ("+sPoolsize+"). Parameter not supported when using volatile KB");
				sPoolsize = null;
			}
		}
		
		logger.log(Logger.CONFIG, sb.toString());	
		//#PJAVA_EXCLUDE_END
		
		/*#PJAVA_INCLUDE_BEGIN
		 agentDescriptions = new DFMemKB(Integer.parseInt(getProperty(MAX_RESULTS, DEFAULT_MAX_RESULTS)));
		 #PJAVA_INCLUDE_END*/
		
		// Initiate the SubscriptionManager used by the DF 
		subManager = new KBSubscriptionManager(agentDescriptions);	
		subManager.setContentManager(getContentManager());
		
		// Register languages and ontologies
		getContentManager().registerLanguage(codec, FIPANames.ContentLanguage.FIPA_SL0);	
		getContentManager().registerLanguage(codec, FIPANames.ContentLanguage.FIPA_SL1);	
		getContentManager().registerLanguage(codec, FIPANames.ContentLanguage.FIPA_SL2);	
		getContentManager().registerLanguage(codec, FIPANames.ContentLanguage.FIPA_SL);	
		getContentManager().registerOntology(FIPAManagementOntology.getInstance());
		getContentManager().registerOntology(JADEManagementOntology.getInstance());
		getContentManager().registerOntology(DFAppletOntology.getInstance());
		
		boolean disableValidation = getBooleanProperty(sDisableValidation, DISABLE_VALIDATION);
		if (disableValidation) {
			getContentManager().setValidationMode(false);
		}
		
		// Create and add behaviours
		MessageTemplate mt = MessageTemplate.MatchPerformative(ACLMessage.REQUEST);
		MessageTemplate mt1 = null;
		
		// Behaviour dealing with FIPA management actions
		mt1 = MessageTemplate.and(mt, MessageTemplate.MatchOntology(FIPAManagementOntology.getInstance().getName()));
		mt1 = MessageTemplate.and(mt1, MessageTemplate.not(MessageTemplate.MatchProtocol(FIPANames.InteractionProtocol.ITERATED_FIPA_REQUEST)));
		//#PJAVA_EXCLUDE_BEGIN
		int poolSize = getIntegerProperty(sPoolsize, POOLSIZE);
		if (poolSize == 0) {
			DFFipaAgentManagementBehaviour fipaRequestResponder = new DFFipaAgentManagementBehaviour(this, mt1);
			addBehaviour(fipaRequestResponder);
		}
		else {
			logger.log(Logger.INFO, "DF FIPA request pool-size = "+poolSize);
			tbf = new ThreadedBehaviourFactory();
			for (int i = 0; i < poolSize; ++i) {
				DFFipaAgentManagementBehaviour fipaRequestResponder = new DFFipaAgentManagementBehaviour(this, mt1);
				fipaRequestResponder.setBehaviourName(getLocalName()+"#FIPAManagementResponder-"+i);
				addBehaviour(tbf.wrap(fipaRequestResponder));
			}
		}
		//#PJAVA_EXCLUDE_END
		/*#PJAVA_INCLUDE_BEGIN
		DFFipaAgentManagementBehaviour fipaRequestResponder = new DFFipaAgentManagementBehaviour(this, mt1);
		addBehaviour(fipaRequestResponder);
		#PJAVA_INCLUDE_END*/
		
		
		// Behaviour dealing with iterated searches according to the iterated-fipa-request protocol
		mt1 = MessageTemplate.and(mt, MessageTemplate.MatchOntology(FIPAManagementOntology.getInstance().getName()));
		mt1 = MessageTemplate.and(mt1, MessageTemplate.MatchProtocol(FIPANames.InteractionProtocol.ITERATED_FIPA_REQUEST));
		DFIteratedSearchManagementBehaviour iteratedSearchResponder = new DFIteratedSearchManagementBehaviour(this, mt1);
		addBehaviour(iteratedSearchResponder);
		
		// Behaviour dealing with JADE management actions
		mt1 = MessageTemplate.and(mt, MessageTemplate.MatchOntology(JADEManagementOntology.getInstance().getName()));
		DFJadeAgentManagementBehaviour jadeRequestResponder = new DFJadeAgentManagementBehaviour(this, mt1);
		addBehaviour(jadeRequestResponder);
		
		// Behaviour dealing with DFApplet management actions
		mt1 = MessageTemplate.and(mt, MessageTemplate.MatchOntology(DFAppletOntology.getInstance().getName()));
		DFAppletManagementBehaviour appletRequestResponder = new DFAppletManagementBehaviour(this, mt1);
		addBehaviour(appletRequestResponder);

		// Behaviour dealing with subscriptions
		mt1 = MessageTemplate.and(
				MessageTemplate.MatchOntology(FIPAManagementOntology.getInstance().getName()),
				MessageTemplate.or(MessageTemplate.MatchPerformative(ACLMessage.SUBSCRIBE), MessageTemplate.MatchPerformative(ACLMessage.CANCEL)));
		dfSubscriptionResponder = new SubscriptionResponder(this, mt1, subManager) {
			// If the CANCEL message has a meaningful content, use it. 
			// Otherwise deregister the Subscription with the same convID (default)
			protected ACLMessage handleCancel(ACLMessage cancel) throws FailureException {
				try {
					Action act = (Action) myAgent.getContentManager().extractContent(cancel);
					ACLMessage subsMsg = (ACLMessage)act.getAction();
					Subscription s = getSubscription(subsMsg);
					if (s != null) {
						mySubscriptionManager.deregister(s);
						s.close();
					}
				}
				catch(Exception e) {
					if(logger.isLoggable(Logger.CONFIG))
						logger.log(Logger.CONFIG,"Unknown CANCEL content. Use default handler");
					super.handleCancel(cancel);
				}
				return null;
			}
		};
		addBehaviour(dfSubscriptionResponder);
		
		// Set the DFDescription of thie DF
		setDescriptionOfThisDF(getDefaultDescription());
		
		// Set lease policy and subscription responder to the knowledge base  
		agentDescriptions.setSubscriptionResponder(dfSubscriptionResponder);
		agentDescriptions.setLeaseManager(new LeaseManager() {
			public Date getLeaseTime(Object item){
				return ((DFAgentDescription) item).getLeaseTime();
			}
			
			public void setLeaseTime(Object item, Date lease){
				((DFAgentDescription) item).setLeaseTime(lease);
			}
			
			/**
			 * Grant a lease to this request according to the
			 * policy of the DF: if the requested lease is
			 * greater than the max lease policy of this DF, then
			 * the granted lease is set to the max of the DF.
			 **/
			public Object grantLeaseTime(Object item){
				if (maxLeaseTime != null) {
					Date lease = getLeaseTime(item);
					long current = System.currentTimeMillis();
					if ( (lease != null && lease.getTime() > (current+maxLeaseTime.getTime())) ||
							( (lease == null) && (maxLeaseTime != null))) {
						// the first condition of this if considers the case when the agent requestes a leasetime greater than the policy of this DF. The second condition, instead, considers the case when the agent requests an infinite leasetime and the policy of this DF does not allow infinite leases. 
						setLeaseTime(item, new Date(current+maxLeaseTime.getTime()));
					} 
				}
				return item;
			}
			
			public boolean isExpired(Date lease){
				return (lease != null && (lease.getTime() <= System.currentTimeMillis()));
			}
		} );
		
		// Prepare the default description of this DF (used for federations) 
		myDescription = getDefaultDescription();
		
		//#PJAVA_EXCLUDE_BEGIN
		boolean autocleanup = getBooleanProperty(sAutocleanup, AUTOCLEANUP);
		if (autocleanup) {
			logger.log(Logger.CONFIG,"Autocleanup activated");
			// Finally add the behaviour that listens for AMS notifications 
			// about dead agents.
			amsSubscriber = new AMSSubscriber() {
				protected void installHandlers(java.util.Map handlersTable) {
					handlersTable.put(IntrospectionVocabulary.DEADAGENT, new EventHandler() {
						public void handle(Event ev) {
							DeadAgent da = (DeadAgent)ev;
							AID id = da.getAgent();
							// Deregister the dead agent in case it was registered
							try {
								DFAgentDescription dfd = new DFAgentDescription();
								dfd.setName(id);
								DFDeregister(dfd);
							}
							catch (Exception e) {
								// Just do nothing
							}
							// Unsubscribe the dead agent in case it was subscribed
							unsubscribeDeadAgent(id);
						}
					});
					
				}
			};
			addBehaviour(amsSubscriber);
		}
		//#PJAVA_EXCLUDE_END
		
		// In case some subscription is already present in the KB (e.g. because the DF is using a DB-based KB and 
		// it has just restarted) reinitialize the SubscriptionResponder protocol.
		// NOTE that this must be done after all components taking part in the subscription mechanism have been properly initialized
		Enumeration ss = agentDescriptions.getSubscriptions();
		while (ss.hasMoreElements()) {
			SubscriptionResponder.Subscription s = (SubscriptionResponder.Subscription) ss.nextElement();
			dfSubscriptionResponder.createSubscription(s.getMessage());
		}
	}  // End of method setup()

	private void unsubscribeDeadAgent(AID id) {
		Vector ss = dfSubscriptionResponder.getSubscriptions(id);
		for (int i = 0; i < ss.size(); i++) {
			try {
				subManager.deregister((SubscriptionResponder.Subscription) ss.elementAt(i));
			}
			catch (Exception e) {
				logger.log(Logger.WARNING, "Error deregistering subscription of dead agent "+id.getName(), e);
			}
		}
	}

	private boolean getBooleanProperty(String sValue, String name) {
		boolean b = false;
		if (sValue != null) {
			try {
				b = Boolean.valueOf(sValue).booleanValue();
			} catch (Exception e) {
				logger.log(Logger.WARNING, "\""+sValue+"\" is not a valid value for boolean parameter" + name, e);
			}
		}
		return b;
	}
	
	private int getIntegerProperty(String sValue, String name) {
		int n = 0;
		if (sValue != null) {

⌨️ 快捷键说明

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