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

📄 nodeimpl.java

📁 p2p仿真器。开发者可以工作在覆盖层中进行创造和测试逻辑算法或者创建和测试新的服务。PlanetSim还可以将仿真代码平稳转换为在Internet上的实验代码
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
	 * @param key
	 *            String representation of id routing message
	 */
	public void removeMessageListener(String key) {
		listeners.remove(key);
	}
	
	/**
	 * Returns information of the node
	 * 
	 * @return info Hashtable with the information
	 */
	public abstract Hashtable getInfo();
	private void writeObject(java.io.ObjectOutputStream out)
			throws java.io.IOException {
		out.defaultWriteObject();
	}
	
	private void readObject(java.io.ObjectInputStream in)
			throws java.io.IOException, ClassNotFoundException {
		in.defaultReadObject();
		init();
	}
	
	/**
	 * Returns the local NodeHandle
	 * @see planet.commonapi.Node#getLocalHandle()
	 * @return The actual local NodeHandle
	 */
	public NodeHandle getLocalHandle() {
		return nodeHandle;
	}
	
	/**
	 * Sets a task to be executed periodicly at each <b>period</b> of time.
	 * @see planet.commonapi.Node#setTimer(planet.util.timer.TimerTask, long, long)
	 * @param task Job to do at each activation of the task.
	 * @param firstTime First activation of the task, measured in steps or millis.
	 * Its value is the relative time, not in absolute time.
	 * @param period Number of steps or millis to periodicly execute the task.
	 */
	public void setTimer(TimerTask task, long firstTime, long period) {
		timer.add(new long[]{firstTime,period});
		tasks.add(task);
		timerNext = (firstTime<timerNext)?firstTime:timerNext;
	}
	
	/**
	 * Sets a task to be executed only one time at specified <b>firstTime</b>.
	 * @see planet.commonapi.Node#setTimer(planet.util.timer.TimerTask, long)
	 * @param task Job to do at activation.
	 * @param firstTime Moment to be activated, in steps or millis, measured
	 * in relative time, not in absolute time. 
	 */
	public void setTimer(TimerTask task, long firstTime) {
		setTimer(task,firstTime,0);
	}
	
	/**
	 * Evaluates if requires any timertask. 
	 *
	 */
	private void processTasks() {
		timerCount++;
		if (timerNext>timerCount) return;
		long[] temp = null;
		boolean evaluate;
		int i=0;
		while(i< timer.size()) {
			evaluate = true;
			temp = (long[])timer.get(i);
			temp[0]=temp[0]-timerCount;
			if (temp[0]<=0) {
				((TimerTask)tasks.get(i)).run();
				if (temp[1]==0) { //if period==0 ==> only once
					timer.remove(i);
					tasks.remove(i);
					i--; //update index
					evaluate = false;
				} else {
					temp[0]=temp[1];
				}
			}
			if (evaluate)
				timerNext = (timerNext>temp[0])?temp[0]:timerNext;
			i++;
		}
		timerCount=0;
	}
	
	/**
	 * This returns a VirtualizedNode specific to the given application and
	 * instance name to the application, which the application can then use in
	 * order to send an receive messages.
	 * 
	 * @param app
	 *            The Application
	 * @param instance
	 *            An identifier for a given instance
	 * @return The endpoint specific to this application, which can be used
	 *         for message sending/receiving. Return null if cannot build the
	 *         required EndPoint.
	 */
	public EndPoint registerApplication(Application app, String instance) {
		EndPoint endpoint = null;
		try {
			endpoint = GenericFactory.buildEndPoint(app, this);
			endpoints.put(app.getId(), endpoint);
			app.setEndPoint(endpoint);
		} catch (InitializationException e) {
			Logger.log("Cannot build a new EndPoint for this Application ["
					+ app + "] and Node [" + this.getId() + "].",
					Logger.ERROR_LOG);
			e.printStackTrace();
		}
		return endpoint;
	}
	
	/**
	 * Get the registered application by the <b>instanceName</b> name.
	 * @param instanceName Name of the registered application.
	 * @return null if there isn't an instance of <b>instanceName</b>, or 
	 * the related endpoint for the application.
	 */
	public EndPoint getRegisteredApplication(String instanceName)
	{
	    return (EndPoint)endpoints.get(instanceName);
	}
	/**
	 * Returns all references of the applications that mantains this node.
	 * 
	 * @return An array with all references to the applications that they are
	 *         mantained for this node.
	 */
	public Application[] getRegisteredApplications() {
		Collection values = this.endpoints.values();
		Application[] apps = new Application[values.size()];
		Iterator it = values.iterator();
		for (int i = 0; it.hasNext(); i++) {
			apps[i] = ((EndPoint) it.next()).getApplication();
		}
		return apps;
	}

    /**
	 * The playsGoodRole's method is an extension method for commonapi specs. This method is
	 * used to allow BehavioursPool decide  wether the <b>Node</b> should run behaviours for
	 * good  peers or instead run  behaviours for bad peers. Moreover, this method  lets the
	 * programmer the responsability of decide node's role. Even it allows a node to  have a
	 * transient behaviour, sometimes behaving as a good peer and sometines behaving as a bad
	 * peer. 
	 * @return True if the Node's Role is positive.
	 */
	public boolean playsGoodRole() {
		return role;
	}
	/**
	 * The setGoodRole's method is an extension method for commonapi specs. This method is 
	 * used to set the role of the node inside the overlay network. A true value means the
	 * node will behave according to the underlying overlay protocol. A false  value means
	 * the node will misbehave.
	 * @param role
	 */
	public void setGoodRole(boolean role) {
		this.role = role;
	}
	/**
	 * The isLocalMessage's method is an extension method for commonapi specs. This method 
	 * is used to allow BehavioursPool decide wether the incoming RouteMessage  is for the
	 * local node or for a  remote node. Remenber, this decision may only be addressed  by 
	 * the underlying overlay protocol. For example, for Symphony's Lookup protocol a node 
	 * is  responsible for all  RouteMessages whose keys have as an immediate succesor the 
	 * node's id or have as destination the own node.  
	 * @see planet.commonapi.behaviours.BehavioursPool
	 * @return True if the incoming RouteMessage taken as input its for the local node.
	 */
	public boolean isLocalMessage(RouteMessage msg) {
		return true;
	}
	
	/* BEGIN **************************** GML  ****************************/
	
    /**
     * Adds new ResultsEdges to <b>edgeCollection</b> according to specified 
     * <b>constraint</b>.
     * @param resultName Result type name to use.
     * @param it Iterator over a collection of nodeHandles.
     * @param constraint Specific constraints to test all built edges.
     * @param edgeCollection Edges collection where they have to be added.
     * @param color Fill color of the edge.
     */
    public void addEdges(String resultName, Iterator it, ResultsConstraint constraint, 
            Collection edgeCollection, String color) {
        ResultsEdge edge = null;
        NodeHandle nh = null;
		while (it.hasNext()) {
			nh = (NodeHandle) it.next();
			if (nh.getId().equals(getId())) continue;
			edge = buildNewEdge(resultName,getId(),nh.getId(),color);
            if (edge!=null)
                if (constraint.isACompliantEdge(edge)) edgeCollection.add(edge);
		}
	}
    
    /**
     * Builds a ResultsEdge with the specified bounds and following the 
     * <b>resultsName</b> type format.
     * @param resultName Result type name to use.
     * @param left One bound of the link.
     * @param right Second bound of the link.
     * @param color Edge color.
     * @return A new instance of the ResultsEdge according the specified <b>resultName</b>
     * or null if any error has ocurred.
     */
    public ResultsEdge buildNewEdge(String resultName, Id left,Id right,String color)
    {
        try {
            return GenericFactory.buildEdge(resultName, left, right, false, color);
        } catch (InitializationException ex)
        { ex.printStackTrace();}
        return null;
    }
	
	/* END ************************ GML ****************************/

	/** 
	 * Returns the NodeHandle closest to <b>id</b>.
	 * @param id Id to find.
	 * @return The NodeHandle closest to <b>id</b>.
	 */
	public abstract NodeHandle getClosestNodeHandle(Id id);
	
	
	/* ****************************  Generic DATA message dispatcher ************************************/
	/**
	 * Make a generic treatment of the DATA messages (application layer messages).
	 * @param msg RouteMessage to be treated.
	 * @param requestMode RouteMessage REQUEST mode for the actual Overlay implementation.
	 * @param refreshMode RouteMessage REFRESH mode for the actual Overlay implementation.
	 */
	public void dispatchDataMessage(RouteMessage msg, int requestMode, int refreshMode)
	{
	    String id_ap = msg.getApplicationId();
	    Id destinationId = msg.getDestination().getId();
		EndPoint endpoint = (EndPoint) endpoints.get(id_ap);
		NodeHandle succ = getSucc();
		
		if (destinationId.betweenE(getPred().getId(),id)) {
		    // Deliver message to End Point
		    boolean forward = endpoint.forward(msg);
		    if (forward) {
		        endpoint.scheduleMessage(msg, 0);
		        Results.decTraffic();
		    } else 
            {
                Results.decTraffic();
                GenericFactory.freeMessage(msg);
            }
		    return;
		}
		
		if (msg.getMode() == requestMode) {
			if (succ != null
					&& destinationId.betweenE(this.id, succ.getId())) 
            {
				//found successor --> send data
				msg.setNextHopHandle(succ);
				if (endpoint.forward(msg))
				{
					msg.setMode(refreshMode);
					try {
						send(msg);
						Results.updateHopsMsg(msg.getSource().getId(),
								msg.getKey());
					} catch (QueueFull e) {
						Logger.log("Outgoing Queue of Node " + this.id + " is Full", Logger.ERROR_LOG);
						GenericFactory.freeMessage(msg);
					}
				} else
                {
				    Results.decTraffic();
                    GenericFactory.freeMessage(msg);
                }
			} else {
				//next node [ROUTING]
				msg.setNextHopHandle(getClosestNodeHandle(
						msg.getDestination().getId()));
				if (endpoint.forward(msg))
				{
					msg.setMode(requestMode);
					try {
						send(msg);
						Results.updateHopsMsg(msg.getSource().getId(),
								msg.getKey());
					} catch (QueueFull e) {
						Logger.log("Outgoing Queue of Node " + this.id + " is Full", Logger.ERROR_LOG);
						GenericFactory.freeMessage(msg);
					}
				} else 
                {
				    Results.decTraffic();
                    GenericFactory.freeMessage(msg);
                }
			}
		} else if (msg.getMode() == refreshMode) {
			// Deliver message to End Point
			boolean forward = endpoint.forward(msg);
			if (forward) {
				endpoint.scheduleMessage(msg, 0);
				Results.decTraffic();
			} else 
            {
                Results.decTraffic();
                GenericFactory.freeMessage(msg);
            }
		} else 
        {
            Results.decTraffic();
            GenericFactory.freeMessage(msg);
        }
	}
	
    
    /**
     * Sets the new Id.
     * @param newId New Id.
     * @return The same instance after has been updated.
     * @see planet.commonapi.Node#setValues(planet.commonapi.Id)
     */
    public Node setValues(Id newId) throws InitializationException {
        this.id = newId;
        nodeHandle = GenericFactory.buildNodeHandle(id, true);
        return this;
    }
}

⌨️ 快捷键说明

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