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

📄 bt.java

📁 一个p2p仿真软件
💻 JAVA
字号:
/*
 * @(#)BT.java ver 1.2 6/20/2005
 * 
 * Copyright 2005 Weishuai Yang (wyang@cs.binghamton.edu). All rights reserved.
 *  
 */

package gps.protocol.BT;

import gps.Simulator;
import gps.event.SimEvent;
import gps.event.SimEventHandler;
import gps.network.graph.Node;
import gps.protocol.Protocol;
import gps.protocol.BT.param.BTTorrent;
import gps.util.Config;
import gps.util.LogFormatter;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Random;
import java.util.StringTokenizer;


/**
 * BT protocol object
 *
 * @author  Weishuai Yang
 * @version 1.2,  6/20/2005
 */
public class BT extends Protocol {

	/**
	 * singleton instance
	 */
    protected static BT mInstance = null;

    /**
     * gets the singleton instance of bt 
     */
    public static synchronized BT getInstance() {
        if (mInstance == null)
            mInstance = new BT();
        return mInstance;
    }

    /**
     * Initionlizer
     */
    public BT() {
        mProtocolConf = "config/bt.cfg";
        Config.loadConfFromFile(mProtocolConf, mProtocolProperties);
        int nodeNum = Integer.parseInt(mProtocolProperties.getProperty("BTTrackers")) + Integer.parseInt(mProtocolProperties.getProperty("BTPeers"));
        mProtocolProperties.setProperty("TotalNodeNum", "" + nodeNum);
    }
    /**
     * loads protocol properties
     * @param path configuration file path
     */
	public void loadProtocolProperties(String path){
    	mProtocolConf=path;
	    mProtocolProperties.clear();
		Config.loadConfFromFile(path, mProtocolProperties);
    	int nodeNum=Integer.parseInt(mProtocolProperties.getProperty("BTTrackers"))+Integer.parseInt(mProtocolProperties.getProperty("BTPeers"));
		mProtocolProperties.setProperty("TotalNodeNum", ""+nodeNum);
	}
    /**
     * configures agents
     */
    public void confAgents() {
        int snum = Integer.parseInt(mProtocolProperties.getProperty("BTTrackers"));
        int pnum = Integer.parseInt(mProtocolProperties.getProperty("BTPeers"));

        Node[] nodes = mTopology.getNodes();
        int totalnodes = nodes.length;
        int tnodes = 0;
        for (int i = 0; i < totalnodes; i++) {
            if (nodes[i].getProperties().getType() == 16)
                tnodes++;
        }

        mDebugLog.info("\nAgent attachment information:\n");

        //I'm not trying to attaching agent to Transit nodes
        setAgentNum(snum, pnum);

        boolean nodeSpecification = Boolean.parseBoolean(mProtocolProperties.getProperty("NodeSpecification"));

        Random rand = new Random(20 + Integer.parseInt(mSimulatorProperties.getProperty("RandomSeed")));

        int r = 0;
        ArrayList attached = new ArrayList();
        for (int i = 0; i < snum; i++) {
            BTTracker btt = new BTTracker(i);

            if (nodeSpecification) {
                r = Integer.parseInt(mProtocolProperties.getProperty("S" + i));
                btt.attachTo(mTopology.getNode(r));
                mDebugLog.info("According to Specification Tracker Agent " + i + " attached to node " + (r));
            } else {
                int count = 0;
                do {
                    count++;
                    r = rand.nextInt() % (totalnodes - tnodes);
                    if (r < 0)
                        r = -r;
                    if (count > 100)
                        mDebugLog.info("Didn't finish attaching agent to nodes within 100 loop!");
                } while (attached.contains(mTopology.getNode(r + tnodes)));
                attached.add(mTopology.getNode(r + tnodes));
                btt.attachTo(mTopology.getNode(r + tnodes));
                mDebugLog.info("Tracker Agent " + i + " attached to node " + (r + tnodes));
            }
            setSAgent(i, btt);
        }
        for (int i = snum ; i < snum + pnum; i++) {
            BTPeer btp = new BTPeer(i);

            if (nodeSpecification) {
                r = Integer.parseInt(mProtocolProperties.getProperty("P" + i));
                btp.attachTo(mTopology.getNode(r));
                mDebugLog.info("Peer Agent " + i + " attached to node " + (r));
            } else {
                int count = 0;
                do {
                    count++;
                    r = rand.nextInt() % (totalnodes - tnodes);
                    if (r < 0)
                        r = -r;
                    if (count > 100)
                        mDebugLog.info("Didn't finish attaching agent to nodes within 100 loop!");
                } while (attached.contains(mTopology.getNode(r + tnodes)));
                attached.add(mTopology.getNode(r + tnodes));
                btp.attachTo(mTopology.getNode(r + tnodes));
                mDebugLog.info("Peer Agent " + i + " attached to node " + (r + tnodes));
            }
            setPAgent(i, btp);
        }

        //debug begin
        StringBuffer s0 = new StringBuffer("\nDelay Information between agents:\n");
        for (int i = 0; i < snum + pnum; i++) {
            s0.append("Node " + i + " to others:");
            for (int j = 0; j < snum + pnum; j++) {

                s0.append(LogFormatter.sprintf(" % 6.1f ms  ", getDelayAgent(i, j) * 1000));

            }
            s0.append("\n");
        }
        mDebugLog.info("" + s0);

    }

    /**
     * configures initial documents
     */
    public void confDocuments() {
        FileInputStream infile;
        String file = mSimulatorProperties.getProperty("DocumentsFile");
        if (file != null) {
            try {
                infile = new FileInputStream(mSimulatorProperties.getProperty("DocumentsFile"));
                BufferedReader rdr = new BufferedReader(new InputStreamReader(infile));
                String s;
                StringTokenizer tk;
                int i = 0;

                //debug begin
                StringBuffer ss = new StringBuffer("Loading document information finish:\n");
                while ((s = rdr.readLine()) != null) {
                    i++;
                    s.trim();
                    if (s.length() == 0)
                        continue;
                    if (s.charAt(0) == '#')
                        continue;
                    tk = new StringTokenizer(s, ",");
                    //it should contain at least 5 tokens
                    if (tk.countTokens() <= 5) {
                        mDebugLog.warning("Reading document config file, at line " + i + ": " + "format error!");
                        //	continue;
                    }
                    int id = Integer.parseInt(tk.nextToken());
                    BTDocument doc = new BTDocument(id);
                    //debug begin
                    ss.append("Document(" + id + ") ");
                    //debug end

                    String key = tk.nextToken();
                    doc.setKey(key);
                    //debug begin
                    ss.append(" key: " + key);
                    //debug end

                    double size = Double.parseDouble(tk.nextToken());
                    doc.setSize(size * 1024);
                    doc.setWhole();
                    //debug begin
                    ss.append(" size: " + size + "KB");
                    //debug end

                    int p = Integer.parseInt(tk.nextToken());
                    doc.setPopularity(p);
                    //debug begin
                    ss.append(" popularity rank: " + p);
                    //debug end
                    
                    //add record to peer node
                    int pid = Integer.parseInt(tk.nextToken());
                    BTPeer peer = (BTPeer) getAgent(pid);
                    peer.ownDocument(doc);
                    //debug begin
                    ss.append(" initial location: " + peer);
                    //debug end

                    //add record to server node
                    if (tk.hasMoreTokens()) {
                        BTTracker tracker = (BTTracker) getAgent(Integer.parseInt(tk.nextToken()));
                        tracker.addTorrent(new BTTorrent(doc, tracker));
                        tracker.addNodeAssociatedWithDoc(key, peer);
                        //debug begin
                        ss.append(" record kept at: " + tracker + "\n");
                        //debug end
                    }
                }
                infile.close();

                //debug begin
                mDebugLog.info("" + ss);
                //debug end
            } catch (FileNotFoundException e) {
                System.err.println(file + " not found");
            } catch (IOException e) {
                System.err.println(file + " io exception");
            } catch (Exception e) {
                System.err.println(e);
                e.printStackTrace();
            }
        } else {
            System.err.println("Please specify DocumentsFile location in config file");
        }
    }

    /**
     * configures scheduled events
     */
    public void confEvents() {
        FileInputStream infile;
        String file = mSimulatorProperties.getProperty("EventsFile");
        if (file != null) {
            try {
                infile = new FileInputStream(mSimulatorProperties.getProperty("EventsFile"));
                BufferedReader rdr = new BufferedReader(new InputStreamReader(infile));
                String s;
                StringTokenizer tk;
                int i = 0;

                //debug begin
                StringBuffer ss = new StringBuffer("Loading event information finish\n");
                //debug end

                while ((s = rdr.readLine()) != null) {
                    i++;
                    s.trim();
                    if (s.length() == 0)
                        continue;
                    if (s.charAt(0) == '#')
                        continue;
                    tk = new StringTokenizer(s, ",");

                    if (tk.countTokens() == 2) {
                        double time = Double.parseDouble(tk.nextToken());
                        String event = tk.nextToken();
                        if (event != "STOP") {
                            BTEvent bte = new BTEvent(time, SimEvent.SIM_END, (SimEventHandler) Simulator.getInstance(), null);
                            mScheduler.enqueue(bte);
                            Simulator.getInstance().setEnd((int) time);
                            //debug begin
                            ss.append("at time " + time + " simulation stop\n");
                            //debug end

                        } else {
                            mDebugLog.warning("Reading event config file, at line " + i + ": " + "format error!");
                        }
                        continue;

                    }
                    //it should contain at least 4 tokens
                    else if (tk.countTokens() < 4) {
                        mDebugLog.warning("Reading event config file, at line " + i + ": " + "format error!");
                        continue;
                    }

                    double t = Double.parseDouble(tk.nextToken());
                    int nodeid = Integer.parseInt(tk.nextToken());

                    int serverid = Integer.parseInt(tk.nextToken());

                    String cmd = tk.nextToken();
                    //key is the hashkey of the document
                    String key = null;
                    BTEvent bte = null;
                    //if command is download or publish
                    if (cmd.equals("D")) {
                        key = tk.nextToken();
                        bte = new BTEvent(t, BTEvent.USER_DOWNLOAD, (SimEventHandler) BT.getInstance().getAgent(nodeid), new Integer(serverid));
                        bte.setAddParam(key);
                        //debug begin
                        ss.append("at time " + t + "Peer " + nodeid + " initiate download for document" + key + " from tracker " + serverid + "\n");
                        //debug end
                    } else if (cmd.equals("P")) {
                        key = tk.nextToken();
                        bte = new BTEvent(t, BTEvent.USER_PUBLISH, (SimEventHandler) BT.getInstance().getAgent(nodeid), new Integer(serverid));
                        bte.setAddParam(key);
                        //debug begin
                        ss.append("at time " + t + "Peer " + nodeid + " publish document" + key + " to tracker " + serverid + "\n");
                        //debug end
                    }

                    else {
                        //cmd should equals RR, random download
                        bte = new BTEvent(t, BTEvent.USER_RANDOM_DOWNLOAD, (SimEventHandler) BT.getInstance().getAgent(nodeid), new Integer(serverid));
                        //debug begin
                        ss.append("at time " + t + "Peer " + nodeid + " randomly download a document from tracker " + serverid + "\n");
                        //debug end
                    }

                    mScheduler.enqueue(bte);
                }
                //debug begin
                mDebugLog.fine("" + ss);
                //debug end
                infile.close();

            } catch (FileNotFoundException e) {
                System.err.println(file + " not found");
            } catch (IOException e) {
                System.err.println(file + " io exception");
            } catch (Exception e) {
                System.err.println(e);
                e.printStackTrace();
            }
        } else {
            System.err.println("Please specify EventsFile location in config file");
        }
    }

}

⌨️ 快捷键说明

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