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

📄 simulation.java

📁 发布/订阅系统路由重配算法,可应用于ad hoc环境
💻 JAVA
字号:
/* * Created on May 4, 2005 * * To change the template for this generated file go to * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments */package sim;import broker.*;import java.util.*;import java.io.*;import com.Message;/** * @author parzy * * To change the template for this generated type comment go to * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments */public class Simulation {		/**	 * The properties for initializing all classes.	 */	protected Properties properties = null;		/**	 * The simulation's event queue.	 */	protected EventQueue eventQueue = new EventQueue();		/**	 * The simulation's current time.	 */	protected double time = 0.0d;	/**	 * The simulated borker network.	 */	protected Network net = null;		/**	 * The simulated application setting.	 */	protected Application application = null;		protected double costs = 0.0d;	protected double processingCosts = 0.0d;	protected double communicationCosts = 0.0d;	protected int pureForwarding = 0;	protected int correctProcessing = 0;		protected String outFile = null;		protected PrintWriter out = new PrintWriter(System.out,true);		protected double[] measureStarts = {0.0d, -1.0d, -1.0d, -1.0d, -1.0d, -1.0d, -1.0d, -1.0d, -1.0d, -1.0d};	protected double[] measureStops = {Double.MAX_VALUE, -1.0d, -1.0d, -1.0d, -1.0d, -1.0d, -1.0d, -1.0d, -1.0d, -1.0d};			protected double measureInterval = 10;		Event measureEvent = null;		/**	 * Creates a new simulation object.	 * @param properties the properties to initialize.	 */	public Simulation(Properties properties){		this.properties = properties;	}		/**	 * Initializes the fields of all needed classes, where default values	 * may be overriden.	 */	public void initialize(){		// initialize own object		initializeProperties(properties);				// initialize all classes acting as factories		Network.initializeProperties(properties);		Application.initializeProperties(properties);	}	protected void initializeProperties(Properties properties) {		// TODO: implement		outFile = properties.getProperty("outFile");		if (outFile != null) {			try {				out = new PrintWriter(new FileWriter(outFile),true);			} catch (IOException e) {				System.err.println(e);				e.printStackTrace();				System.exit(-1);			}		}		measureInterval = properties.getProperty("measureInterval") != null ?				          Double.parseDouble(properties.getProperty("measureInterval")) :						  measureInterval;	}	/**	 * Sets up the simulation by creating network and application setting.	 * Subclasses are encouraged to override this method to set up	 * simulation specific events.	 */	public void setup() {		// create the overlay and broker network		System.out.println(measureInterval);		net = Network.createOverlay(this);		net.createRandomTree();		net.startHeuristic();				// create the applications		application = Application.createApplication(this);		application.assignTo(net);				for (int i=0; i<measureStarts.length; i++) {			if(measureStarts[i]>=0.0d) {				this.scheduleEventAt(measureStarts[i], new MeasureStartEvent());			}		}				for (int i=0; i<measureStops.length; i++) {			if(measureStops[i]>=0.0d) {				this.scheduleEventAt(measureStops[i], new MeasureStopEvent());			}		}				scheduleEventAt(100000, new StopEvent());	}		/**	 * Starts the simulation by handling the events in the event queue	 * until it gets empty.	 */	private void run() {		double mytime = 0;		Event e; // the current event				// handle events until the queue gets empty		while(!eventQueue.isEmpty()) {			e = eventQueue.dequeue();			time = e.getTime();			if(mytime+500<time) {				mytime = time;				System.out.println("time: "+time+" queueSize: "+eventQueue.size());				//pureForwarding = 0;				//correctProcessing = 0;				//System.gc();				//try {Thread.sleep(60000);}catch(Exception x) {}				//eventQueue.stats();				//net.checkSize();				//Broker[] brokers = new Broker[100];				//int i = 0;				//for(Iterator it = net.brokerIterator(); it.hasNext(); ) {				//	brokers[i++] = (Broker)it.next();				//				//}				//System.out.print("Brokers von "+brokers[67]+" sind ");								//for(Iterator it = brokers[67].getNeighbors().iterator(); it.hasNext();) {				//	System.out.print(""+it.next()+" ");				//}				//System.out.println();			}						e.handle();		}    }	/**	 * Returns all simulation's properties.	 * @return all simulation's properties.	 */	public Properties getProperties(){		return properties;	}		/**	 * Returns a single property.	 * @param key the property's key.	 * @return a single property.	 */	public String getProperty(String key){		return properties.getProperty(key);	}		/**	 * Returns the simulation's current time.	 * @return the simulation's current time.	 */	public double getTime(){		return time;	}		/**	 * Schedules a new event after a given delay.	 * @param delay the delay to wait.	 * @param e the event itself.	 */	public void scheduleEventIn(double delay, Event e){		e.setTime(this.time+delay);		eventQueue.enqueue(e);	}		/**	 * Schedules an event at a certain time.	 * @param time the time for which the event is scheduled.	 * @param e the event itself.	 */	public void scheduleEventAt(double time, Event e){		e.setTime(time);		eventQueue.enqueue(e);	}		/**	 * Schedules an already timed event.	 * @param e the event itself.	 */	public void scheduleEvent(Event e){		eventQueue.enqueue(e);	}		/**	 * Schedules the event for a current handling.	 * @param e the event itself.	 */	public void scheduleEventNow(Event e){		scheduleEventIn(0,e);	}	/**	 * Removes a scheduled event from the event queue.	 * @param e the event to remove.	 */	public void removeEvent(Event e){		eventQueue.remove(e);	}	/**	 * Main method to start a simulation. It parses the simulations 	 * property file given in the first argument and overrides the default	 * values.  	 * @param args arg1 is the simulations property file. 	 */	public static void main(String[] args) {			Properties properties; // the (parsed) properties		Class simClass;        // requested simulation class		Simulation sim;         // simulation instance				properties = new Properties();				// parse the property file		if(args.length>0){			try{				LineNumberReader in;				String line;				String[] tokens;							in = new LineNumberReader(new FileReader(args[0]));				while((line = in.readLine())!= null){					line = line.trim();					if(line.startsWith("#") || line.equals("")){						continue;					}					tokens = line.split("=");					if(tokens.length!=2){						throw new ParseException("Parse error at line " + 								in.getLineNumber() + 								": "+ line );   					}					properties.setProperty(tokens[0],tokens[1]);				}			}catch(Exception e){				System.err.println(e);				e.printStackTrace();				System.exit(-1);			}		}				// TODO remove//		properties.setProperty("outFile","bla");//		properties.setProperty("simulation","sim.Experiment");//		//properties.setProperty("heuristic","INTERESTS");//		//properties.setProperty("heuristic","COSTS");//		properties.setProperty("heuristic","COSTS_AND_INTERESTS");//		properties.setProperty("minCommunicationCosts","0");//		properties.setProperty("maxCommunicationCosts","100");//		properties.setProperty("minProcessingCosts", "0");//		properties.setProperty("maxProcessingCosts", "10");//		properties.setProperty("reassignmentInterval","EXPONENTIAL");//		properties.setProperty("reassignmentConstant", "0.0004");//		properties.setProperty("reassignmentInterval","CONSTANT");//		properties.setProperty("reassignmentConstant", "100000");//		properties.setProperty("publicationInterval","EXPONENTIAL");//		properties.setProperty("publicationConstant","0.2");//		properties.setProperty("publicationInterval","CONSTANT");//		properties.setProperty("publicationConstant","5");		//		properties.setProperty("filterMethod","PROBABILISTIC");//		properties.setProperty("updateInterval","400");//		properties.setProperty("timeShift","5000");//		properties.setProperty("environmentSize","5");//		properties.setProperty("numberOfSubscribers","9");//		properties.setProperty("numberOfJobs","50");//		properties.setProperty("netFile","small.sim");				// dynamically create a simulation of the requested class		simClass = Simulation.class;		sim = new Simulation(properties);		if(properties.getProperty("simulation") != null) {			try{				simClass = Class.forName(properties.getProperty("simulation"));				sim = (Simulation)simClass.getConstructor(new Class[]{Properties.class}).newInstance(new Object[]{properties});			}catch(Exception e){				System.err.println(e);				e.printStackTrace();				System.exit(-1);			}		}			// initialize, setup and start the simulation		sim.initialize();		sim.setup();		sim.run();	}		public Network getNetwork() {		return net;	}		public Application getApplication() {		return application;	}		public void collectStatisticsSending(Destination from, Destination to, Message message) {				double c;		 		if(from.isClient() || to.isClient()){			return;    	}				// TODO remove//		if(message.getType()!=Message.NORMAL){//			return;//		}		    	c = net.getCommunicationCosts((Broker)from,(Broker)to);    	costs += c;    	communicationCosts += c;    }		public void collectStatisticsProcessing(Broker broker, Message message) {		double p;		//		 TODO remove//		if(message.getType()!=Message.NORMAL){//			return;//		}				p = net.getProcessingCosts(broker);		costs += p;		processingCosts += p;	}		public void collectStatisticsPureForwarding() {		this.pureForwarding++;	}		public void collectStatisticsCorrectProcessing() {		this.correctProcessing++;	}		public void collectStatisticsEnqueue(Broker b, Message message){			}		public void collectStatisticsDequeue(Broker b, Message message){			}		protected class MeasureStartEvent extends Event{		public void handle() {			if(measureEvent == null) {				costs = 0;				processingCosts = 0;				communicationCosts = 0;				measureEvent = new MeasureEvent();				scheduleEventIn(measureInterval, measureEvent);			}		}	}		protected class MeasureStopEvent extends Event{		public void handle() {			if (measureEvent != null) {				removeEvent(measureEvent);				measureEvent = null;			}		}	}		protected class MeasureEvent extends Event{		public void handle() {			measure();		}	}		public void measure() {		//out.println("time: "+time+" costs: "+costs+" (processing: "+processingCosts+" communication: "+communicationCosts);		//out.println(""+time+"\t"+costs);		costs = 0;		processingCosts = 0;		communicationCosts = 0;		measureEvent=new MeasureEvent();		scheduleEventIn(measureInterval,measureEvent);	}		protected class StopEvent extends Event {		public void handle() {			stop();		}	}		public void stop() {		eventQueue.clear();		out.flush();		out.close();	}}	

⌨️ 快捷键说明

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