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

📄 localagletref.java

📁 aglet的部分源码
💻 JAVA
📖 第 1 页 / 共 4 页
字号:
		checkMessagePermission(msg);		checkMessageProtection(msg);	}	private void checkMessagePermissionAndProtection(String actions) {		checkMessagePermission(actions);		checkMessageProtection(actions);	}	private void checkMessageProtection(MessageImpl msg) {		Certificate cert = AgletRuntime.getCurrentCertificate();		// ??????What if cert is null????(HT)		if (cert != null) {			// System.out.println("checkProtection(msg.getProtection("+id.getName()+"))");			Permission p = 				msg.getProtection(AgletRuntime.getCertificateAlias(cert));			// System.out.println("checkProtection("+p.toString()+")");			checkProtection(p);		} 	}	private void checkMessageProtection(String actions) {		Certificate cert = AgletRuntime.getCurrentCertificate();		// ??????What if cert is null????(HT)		if (cert != null) {			// System.out.println("checkProtection(new MessageProtection("+id.getName()+", "+actions+"))");			checkProtection(new MessageProtection(AgletRuntime				.getCertificateAlias(cert), actions));		} 	}	/*	 * check permission/protection	 */	private void checkPermission(Permission p) {		if (_context != null) {			_context.checkPermission(p);		} 	}	private void checkProtection(Permission p) {		if (!_secure) {			return;		} 		logCategory.debug("protections="+String.valueOf(protections));		logCategory.debug("permission="+String.valueOf(p));		if (protections != null && protections.implies(p) == false) {			SecurityException ex = new SecurityException(p.toString());			ex.printStackTrace();			throw ex;		} 	}	/*	 * Checks if the aglet ref is valid.	 */	public void checkValidation() throws InvalidAgletException {		if (!isValid()) {			throw new InvalidAgletException("Aglet is not valid");		} 	}	// #     /*	// #      *	// #      */	// #     public void resetAllowance() {	// # 	CodeSource cs = new CodeSource(info.getCodeBase(), null);	// # 	Policy pol = null;	// # 	try {	// # 	    AccessController.beginPrivileged();	// # 	    pol = Policy.getPolicy();	// # 	} finally {	// # 	    AccessController.endPrivileged();	// # 	}	// # 	pol = (Policy)AccessController.doPrivileged(new PrivilegedAction() {	// # 	    public Object run() {	// # 		return Policy.getPolicy();	// # 	    }	// # 	});	// # 	Permissions permissions = null;	// # 	if(pol instanceof PolicyImpl) {	// # 	    PolicyImpl policy = (PolicyImpl)pol;	// # 	    permissions = policy.getPermissions(cs, null);	// # 	}	// # 	if(permissions!=null) {	// # 	    Enumeration perms = permissions.elements();	// # 	    while(allowance==null && perms.hasMoreElements()) {	// # 		Object obj = perms.nextElement();	// # 		if(obj instanceof ActivityPermission) {	// # 		    ActivityPermission perm = (ActivityPermission)obj;	// # 		    if(perm.isMatched("name")) {	// # 			if(allowance==null) {	// # 			    allowance = perm.getAllowance();	// # //+			} else {	// # //+			    allow.limit(perm.getAllowance());	// # 			}	// # 		    }	// # 		}	// # 	    }	// # 	}	// #	// # 	if(allowance==null) {	// # 	    allowance = new Allowance(Room.INFINITE, Room.INFINITE, Lifetime.UNLIMITED);	// # 	}	// #     }	/**	 * Clones the aglet ref. Note that the cloned aglet will get activated.	 * If you like to get cloned aglet which is not activated, throw	 * ThreadDeath exception in the onClone method.	 * 	 * @return  the new aglet ref what holds cloned aglet.	 * @exception CloneNotSupportedException if the cloning fails.	 * @exception InvalidAgletException if the aglet is invalid.	 */	protected Object clone() throws CloneNotSupportedException {		/*		 * TO AVOID SELF CKECKING : M.O		 * checkPermission(new AgletPermission("this", ACTION_CLONE));		 * checkProtection(new AgletProtection("this", ACTION_CLONE));		 */		checkAgletPermissionAndProtection(ACTION_CLONE);		return _clone();	}	private MessageImpl cloneMessageAndCheck(Message msg, int type) {		MessageImpl clone;		if (msg instanceof SystemMessage) {			clone = (MessageImpl)msg;		} else {	// normal or delegate			clone = new MessageImpl(msg, null, type, 									System.currentTimeMillis());		} 		checkMessagePermissionAndProtection(clone);		return clone;	}	/**	 * 	 */	private static Protections cloneProtections(Protections protections) {		// because java.security.Permissions and java.security.Permission		// are not Cloneable.		if (protections == null) {			return null;		} 		Enumeration prots = protections.elements();		Protections ps = new Protections();		while (prots.hasMoreElements()) {			Object obj = prots.nextElement();			if (obj instanceof AgletProtection) {				AgletProtection ap = (AgletProtection)obj;				String name = ap.getName();				String actions = ap.getActions();				AgletProtection nap = new AgletProtection(name, actions);				ps.add(nap);			} else if (obj instanceof MessageProtection) {				MessageProtection mp = (MessageProtection)obj;				String name = mp.getName();				String actions = mp.getActions();				MessageProtection nmp = new MessageProtection(name, actions);				ps.add(mp);			} 		} 		return ps;	}	/*	 * 	 */	ResourceManager createResourceManager(ClassName[] table) {		resourceManager = _context.createResourceManager(info.getCodeBase(), 				_owner, table);		if (resourceManager == null) {			logCategory.error("invalid codebase:" + info.getCodeBase());		} 		return resourceManager;	}	/**	 * Deactivate aglet till the specified date. The deactivated aglet are	 * stored in the aglet spool.	 * @param duration the duration to sleep in milliseconds.	 * @exception AgletEception if can not deactivate the aglet.	 */	protected void deactivate(long duration) throws IOException {		try {			checkActive();			/*			 * TO AVOID SELF CKECKING : M.O			 * checkPermission(new AgletPermission("this", ACTION_DEACTIVATE));			 * checkProtection(new AgletProtection("this", ACTION_DEACTIVATE));			 */			checkAgletPermissionAndProtection(ACTION_DEACTIVATE);			deactivate(AgletThread.getCurrentMessage(), duration);		} catch (InvalidAgletException excpt) {			throw new AgletsSecurityException(ACTION_DEACTIVATE + " : " 											  + excpt);		} catch (RequestRefusedException excpt) {			throw new AgletsSecurityException(ACTION_DEACTIVATE + " : " 											  + excpt);		} 	}	/*	 * 	 */	void deactivate(MessageImpl msg, long duaration) 			throws IOException, InvalidAgletException, 				   RequestRefusedException {		synchronized (lock) {			checkValidation();			if (duaration < 0) {				throw new IllegalArgumentException("minutes must be positive");			} 			Persistence persistence = _context.getPersistence();			if (persistence == null) {				_context					.log("Deactivation", 						 "Deactivation not implemneted in this environment");				return;			} 			try {				dispatchEvent(new PersistencyEvent(PersistencyEvent					.DEACTIVATING, proxy, duaration));			} catch (SecurityException ex) {				throw ex;			} catch (Exception ex) {				ex.printStackTrace();			} 			ObjectOutputStream out = null;			// 			// Suspend all threads except for the current thread			// 			suspendMessageManager();			// start			boolean success = false;			String key = getPersistenceKey();			try {				long wakeupTime = duaration == 0 ? 0 								  : System.currentTimeMillis() + duaration;				PersistentEntry entry = persistence.createEntryWith(key);				out = new ObjectOutputStream(entry.getOutputStream());				DeactivationInfo dinfo = new DeactivationInfo(_name, 						wakeupTime, key, DeactivationInfo.DEACTIVATED);				writeDeactivatedAglet(out, dinfo);				_context._timer.add(dinfo);				success = true;			} 			finally {				if (success == false) {					try {						persistence.removeEntry(key);					} catch (ThreadDeath t) {						throw t;					} catch (Throwable ee) {						// ignore					} 					resumeMessageManager();					_context.log("Deactivate", 								 "Fail to save aglet [" + key + "]");				} 				if (out != null) {					try {						out.flush();						out.close();					} catch (IOException ex) {}				} 			} 			_state = INACTIVE;			_mode = DeactivationInfo.DEACTIVATED;			if (msg != null && msg.future != null) {				msg.future.sendReplyIfNeeded(null);			} 			// message manager is persistent and will be restored later			messageManager.deactivate();			terminateThreads();			_hasSnapshot = false;			aglet = null;			try {				_context.log("Deactivate", key);				_context					.postEvent(new ContextEvent(ContextEvent						.DEACTIVATED, _context, proxy), true);			} 			finally {				resourceManager.disposeAllResources();				resourceManager.stopThreadGroup();			} 		} 	}	/**	 * Delegates a message to the ref.	 * @param msg a message to delegate	 * @exception InvalidAgletException if the aglet is not valid any longer.	 */	public void delegateMessage(Message msg) throws InvalidAgletException {        logCategory.debug("delegateMessage()++");		synchronized (msg) {			if (msg instanceof MessageImpl == false 					|| ((MessageImpl)msg).isDelegatable() == false) {				throw new IllegalArgumentException("The message cannot be delegated " 												   + msg);			} 			MessageManagerImpl mng = messageManager;			checkValidation();			MessageImpl origin = (MessageImpl)msg;			MessageImpl clone = (MessageImpl)origin.clone();			checkMessagePermissionAndProtection(clone);			if (mng != null) {				origin.disable();		// disable the message				mng.postMessage(clone);			} else {				origin.cancel("Message Manager not found " 							  + (_state == INACTIVE ? "[inactive]" : ""));			} 		} 	}	void destroyMessageManager() {		// Debug.check();		messageManager.destroy();		// Debug.check();	}	// trip with Ticket	protected void dispatch(Ticket ticket) 			throws IOException, RequestRefusedException {		try {			checkActive();			/*			 * TO AVOID SELF CKECKING : M.O			 * checkPermission(new AgletPermission("this", ACTION_DISPATCH));			 * checkProtection(new AgletProtection("this", ACTION_DISPATCH));			 */			checkAgletPermissionAndProtection(ACTION_DISPATCH);			dispatch(AgletThread.getCurrentMessage(), ticket);		} catch (InvalidAgletException ex) {			throw new AgletsSecurityException(ACTION_DISPATCH + " : " + ex);		} 	}	// trip with Ticket	void dispatch(MessageImpl msg, Ticket ticket) 			throws IOException, RequestRefusedException, 				   InvalidAgletException {		URL dest = ticket.getDestination();		synchronized (lock) {			checkValidation();			// 			// Converts URL to the destination ticket.			// 			if (dest.getRef() != null &&!"".equals(dest.getRef())) {				throw new MalformedURLException("MalformedURL in dispatchAglet:" 												+ ticket);			} 			try {				dispatchEvent(new MobilityEvent(MobilityEvent.DISPATCHING, 												proxy, ticket));			} catch (SecurityException ex) {				throw ex;			} catch (Exception ex) {				ex.printStackTrace();			} 			suspendMessageManager();			boolean success = false;			try {				MAFAgentSystem _maf = 					MAFAgentSystem.getMAFAgentSystem(ticket);				if (_maf == null) {					throw new ServerNotFoundException(ticket.toString());				} 				// # 		// consume a room of hops.				// # 		// When the aglet has no available rooms of hops,				// # 		// raise an ExhaustedException.				// # 		allowance.consumeRoomHops();				// 				// clean up the reference. REMIND: needs to be improved.				// 				removeAgletRef(_name, this);				AgletWriter writer = new AgletWriter();				writer.writeInfo(this);				writer.writeAglet(this);				// Name        name       = getName(); // ??				byte[] agent = writer.getBytes();				String place = dest.getFile();				if (place.startsWith("/")) {					place = place.substring(1);				} 				ClassName[] classnames = writer.getClassNames();				String codebase = info.getCodeBase().toString();				MAFAgentSystem local = 					MAFAgentSystem.getLocalMAFAgentSystem();				_maf.receive_agent(_name, _agent_profile, agent, place, 								   classnames, codebase, local);				success = true;				// # 	    } catch (ExhaustedException ex) {				// # 		ex.printStackTrace();				// # 		throw new RequestRefusedException("Available room of hops was exhausted : " + ex.getMessage());			} catch (ClassUnknown ex) {				ex.printStackTrace();				throw new RequestRefusedException(ticket + " " 												  + info.getAgletClassName());			} catch (DeserializationFailed ex) {				throw new RequestRefusedException(ticket + " " 												  + info.getAgletClassName());				/*				 * } catch (RequestRefused ex) {				 * throw new RequestRefusedException(ticket + " " +				 * info.getAgletClassName());				 */			} catch (MAFExtendedException ex) {				ex.printStackTrace();				throw new RequestRefusedException(ticket + " " 												  + info.getAgletClassName());			} 			finally {				if (success == false) {					resumeMessageManager();					addAgletRef(_name, this);					_context.log("Dispatch", 								 "Fail to dispatch " 								 + info.getAgletClassName() + " to " 								 + ticket);				} 			} 			invalidateReference();			RemoteAgletRef r_ref = RemoteAgletRef.getAgletRef(ticket, _name);			r_ref.setAgletInfo(info);			AgletProxy new_proxy = new AgletProxyImpl(r_ref);			if (msg != null && msg.future != null) {				msg.future.sendReplyIfNeeded(new_proxy);			} 			removeSnapshot();			terminateThreads();			destroyMessageManager();			try {				_context.log("Dispatch", 							 info.getAgletClassName() + " to " 							 + ticket.getDestination());				_context					.postEvent(new ContextEvent(ContextEvent						.DISPATCHED, _context, new_proxy, ticket							.getDestination()), true);			} 			finally {				releaseResource();			} 		} 	}

⌨️ 快捷键说明

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