Exemplo n.º 1
0
 void handleConfigEvent(HashMap map) {
   if (map == null) {
     return;
   }
   if (map.containsKey("additional_data")) {
     additional_data = (byte[]) map.get("additional_data");
   }
   if (map.containsKey("send_buf_size")) {
     mcast_send_buf_size = ((Integer) map.get("send_buf_size")).intValue();
     ucast_send_buf_size = mcast_send_buf_size;
   }
   if (map.containsKey("recv_buf_size")) {
     mcast_recv_buf_size = ((Integer) map.get("recv_buf_size")).intValue();
     ucast_recv_buf_size = mcast_recv_buf_size;
   }
   setBufferSizes();
 }
 public ArrayList getPointList(long handId) {
   ArrayList curList;
   if (_pointLists.containsKey(handId)) curList = (ArrayList) _pointLists.get(handId);
   else {
     curList = new ArrayList(_maxPoints);
     _pointLists.put(handId, curList);
   }
   return curList;
 }
Exemplo n.º 3
0
 /**
  * Obtient le socket enregistré correspondant à l'addresse IP donnée.
  *
  * @return le socket correspondant à l'IP source donnée s'il a été enregistré null sinon.
  */
 public Socket popSocket(InetAddress addr) {
   String addrname = toId(addr);
   if (acceptedSockets.containsKey(addrname)) {
     Socket sock = acceptedSockets.get(addrname);
     acceptedSockets.remove(addrname);
     return sock;
   }
   return null;
 }
    public void OnPointDestroy(long nID) {
      println("OnPointDestroy, handId: " + nID);

      // remove list
      if (_pointLists.containsKey(nID)) _pointLists.remove(nID);
    }
  public static void main(String[] args) throws IOException {

    System.out.println("SimultaneousAscendingAuctionClient starting");

    Socket auctSocket = null;
    PrintWriter out = null;
    BufferedReader in = null;

    String hostName = "127.0.0.1"; // IP of host (may be local IP)
    int socketNum = 1305; // the luckiest socket

    Agent agent = null;
    Valuation valuationMethod = null;

    try {
      in = new BufferedReader(new FileReader("./src/IP_and_Port.txt"));
      // two lines in this file.  First is hostName/IP address, and second is socket number of host
      hostName = in.readLine();
      socketNum = Integer.valueOf(in.readLine());
      in.close();
    } catch (IOException e) {
    }

    // These are values the agent should remember and use
    // Values are initialized when Server sends parameters
    int numSlotsNeeded = -1;
    int deadline = -1;
    double[] valuations = null;

    try {
      auctSocket = new Socket(hostName, socketNum);
      out = new PrintWriter(auctSocket.getOutputStream(), true);
      in = new BufferedReader(new InputStreamReader(auctSocket.getInputStream()));
    } catch (UnknownHostException e) {
      System.err.println("Don't know about host: " + hostName + ".");
      System.exit(1);
    } catch (IOException e) {
      System.err.println("Couldn't get I/O for the connection to: host.");
      System.exit(1);
    }
    System.out.println("Connection to host established");

    BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
    String fromServer;

    // continue to prompt commands from host and respond
    while ((fromServer = in.readLine()) != null) {
      System.out.println("Server: " + fromServer);

      // Send host this client's unique ID
      if (fromServer.equalsIgnoreCase("Send client name")) {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter a unique ID string...");

        out.println(br.readLine());
        // OPTIONAL CHANGE:
        // YOU MAY CHOOSE TO REPLACE THE LINE ABOVE WITH THE LINE BELOW
        // out.println("My_Hardcoded_Name");

        System.out.println("User ID sent.  If prompted again, choose another ID/Name string.");
        System.out.println("Waiting for server to start auction...");
      }

      // ***********************************************************************

      else if (fromServer.startsWith("agent-parameters:")) {
        String[] params = fromServer.split("[ ]"); // tokens delimited with spaces

        numSlotsNeeded = Integer.valueOf(params[1]); // 1st param is number of slots needed

        deadline = Integer.valueOf(params[2]); // 2nd param is deadline
        // DEADLINE IS INDEX OF LAST AUCTION OF VALUE (0-indexed).
        // example: deadline = 1 -->  first two time-slots can be used

        valuations = new double[params.length - 3]; // first 3 stings aren't valuations
        for (int i = 3; i < params.length; i++) valuations[i - 3] = Double.valueOf(params[i]);

        ///////////////////////////////////////////////
        //  YOUR CODE HERE
        //  You probably want to store the parameters sent from host.
        //  For example, you could store them in global variables,
        //  or use them to initialize an agent class you wrote.
        ///////////////////////////////////////////////

        // EDIT HERE
        // ??  how to define the number for each agent ?
        // ?? whether to change to another kind of agent

        valuationMethod = new SchedulingValuation(numSlotsNeeded, valuations);
        agent = new SunkawarePPAgent(0, valuationMethod, 0);

        // Send starting information= to agents
        //		agent.postResult(new Result(null, false, 0, ar.getAskPrice(), 0, ar.getAskEpsilon()));

        agent.openAllAuctions();

        ///////////////////////////////////////////////
        out.println("Parameters accepted");
      }

      // ***********************************************************************

      else if (fromServer.equalsIgnoreCase("submit-bid")) {
        // Here are values you should use... be more clever than random!
        // numSlotsNeeded (int)
        // deadline (int)  index of last timeSlot of value (starts at 0)
        // valuations (double[numSlots])

        ///////////////////////////////////////////////
        //  YOUR CODE HERE
        //  Create a string, like myBids, with your bid(s).
        //  If placing multiple bids, separate bids with spaces spaces.
        //  If multiple bids, order bids as follows:
        //  myBids = "timeSlot1Bid  timeSlot2Bid ... timeslot5Bid";
        //
        // Note:  bids get rounded to 2 decimal places by host. 5.031 -> 5.03
        ///////////////////////////////////////////////

        /*
        String myBids = "";
        Random r = new Random();//make random bids... 1 for each time slot
        for(int i=0; i < valuations.length; i++){
        	myBids = myBids + (r.nextDouble()*10);//random bid 0 to 10
        	if(i < valuations.length-1)
        		myBids = myBids + " ";//separate bids with a space!  IMPORTANT!
        }
        */

        // EDIT HERE!

        HashMap<Integer, Double> a_bids = agent.getBids();
        String myBids = "";
        for (int i = 0; i < valuations.length; i++) {
          if (a_bids.containsKey(i)) {
            myBids = myBids + a_bids.get(i);
          } else {
            myBids = myBids + 0.0;
          }

          if (i < valuations.length - 1) myBids = myBids + " ";
        }

        ///////////////////////////////////////////////

        out.println(myBids); // Send agent's bids to server
        System.out.println("Mybids: " + myBids + "\n");
      }

      // ***********************************************************************

      // Observe the state of auction variables. Store information locally
      else if (fromServer.startsWith("observe-auction-state:")) {
        String[] stateVars = fromServer.split("[ ]"); // tokens delimited with spaces

        int numAgents = Integer.valueOf(stateVars[1]);
        int numTimeSlots = Integer.valueOf(stateVars[2]);
        int currentRound = Integer.valueOf(stateVars[3]); // 1st round -> 0
        // currentRound is 0-indexed, so currentRound = 0 for first round

        String[] leaderIDs = new String[numTimeSlots]; // leaders and their bids for each time-slot
        double[] leaderBids = new double[numTimeSlots];

        if (currentRound > 0) // no winners before first round
        for (int i = 0; i < (numTimeSlots * 2); i += 2) { // 2 records per time slot [leader, bid]
            leaderIDs[i / 2] = stateVars[4 + i];
            leaderBids[i / 2] = Double.valueOf(stateVars[5 + i]);
          }

        System.out.println(
            "Observing state:\nNumber of agents = "
                + numAgents
                + "\nNumber of time slots = "
                + numTimeSlots);
        System.out.println("Current auction state:");
        for (int i = 0; i < leaderIDs.length; i++)
          System.out.println(
              "Time-Slot "
                  + i
                  + ": current-leader: "
                  + leaderIDs[i]
                  + ", current bid = "
                  + leaderBids[i]);
        ///////////////////////////////////////////////
        //  YOUR CODE HERE
        //  You may want to record some of the state
        //  information here, especially the IDs of
        //  current auction leaders for each time-slot
        //  as well as the current leading bids.
        ///////////////////////////////////////////////

        // EDIT HERE

        ///////////////////////////////////////////////
        out.println("State Observed"); // let the server know client received state info
        System.out.println(""); // helps separate the output
      }

      // ***********************************************************************

      else if (fromServer.startsWith("observe-final-outcome:")) {
        // fromServer = "observe-final-outcome: winnerID_0 price_0 winnerID_1 price_1 ..."
        String[] outcomeVars = fromServer.split("[ ]"); // tokens delimited with spaces

        // for each slot, announce winner's ID and their price
        for (int i = 1; i < outcomeVars.length; i += 2) {
          String winnerID = outcomeVars[i];
          double winPrice = Double.valueOf(outcomeVars[i + 1]);
          System.out.println(
              "Time Slot "
                  + ((i + 1) / 2)
                  + " awarded to ["
                  + winnerID
                  + "] for price = "
                  + winPrice);
        }
        out.println("Final Outcome Observed"); // let the server know client received state info
      }

      // ***********************************************************************

      // The server says to end the connection
      else if (fromServer.equals("END")) {
        System.out.println("END called.  closing");
        break;
      }

      // ***********************************************************************

      else System.out.println("Unexpected input: " + fromServer);
    }

    out.close();
    in.close();
    stdIn.close();
    auctSocket.close();
  }
Exemplo n.º 6
0
  /** Loads the lexicon and morph files. */
  public void init(URL lexiconUrl, URL morphUrl) throws IOException {

    List<Family> lexicon = null;
    List<MorphItem> morph = null;
    List<MacroItem> macroModel = null;

    // load category families (lexicon), morph forms and macros
    lexicon = getLexicon(lexiconUrl);
    Pair<List<MorphItem>, List<MacroItem>> morphInfo = getMorph(morphUrl);
    morph = morphInfo.a;
    macroModel = morphInfo.b;

    // index words; also index stems to words, as default preds
    // store indexed coarticulation attrs too
    _words = new GroupMap<Word, MorphItem>();
    _predToWords = new GroupMap<String, Word>();
    _coartAttrs = new HashSet<String>();
    _indexedCoartAttrs = new HashSet<String>();
    for (MorphItem morphItem : morph) {
      Word surfaceWord = morphItem.getSurfaceWord();
      _words.put(surfaceWord, morphItem);
      _predToWords.put(morphItem.getWord().getStem(), surfaceWord);
      if (morphItem.isCoart()) {
        Word indexingWord = morphItem.getCoartIndexingWord();
        _words.put(indexingWord, morphItem);
        Pair<String, String> first = indexingWord.getSurfaceAttrValPairs().next();
        _indexedCoartAttrs.add(first.a);
        for (Iterator<Pair<String, String>> it = surfaceWord.getSurfaceAttrValPairs();
            it.hasNext(); ) {
          Pair<String, String> p = it.next();
          _coartAttrs.add(p.a);
        }
      }
    }

    // index entries based on stem+pos
    _stems = new GroupMap<String, Object>();
    _posToEntries = new GroupMap<String, EntriesItem[]>();
    // index entries by supertag+pos, for supertagging
    _stagToEntries = new GroupMap<String, EntriesItem>();
    // also index rels and coart rels to preds
    _relsToPreds = new GroupMap<String, String>();
    _coartRelsToPreds = new GroupMap<String, String>();
    // and gather list of attributes used per atomic category type
    _catsToAttrs = new GroupMap<String, String>();
    _lfAttrs = new HashSet<String>();
    // and remember family and ent, names, for checking excluded list on morph items
    HashSet<String> familyAndEntryNames = new HashSet<String>();

    // index each family
    for (Family family : lexicon) {

      familyAndEntryNames.add(family.getName());
      EntriesItem[] entries = family.getEntries();
      DataItem[] data = family.getData();

      // for generic use when we get an unknown stem
      // from the morphological analyzer
      if (!family.isClosed()) {
        _posToEntries.put(family.getPOS(), entries);
      }

      // scan through entries
      for (int j = 0; j < entries.length; j++) {
        // index
        EntriesItem eItem = entries[j];
        _stagToEntries.put(eItem.getSupertag() + family.getPOS(), eItem);
        if (eItem.getStem().length() > 0) {
          _stems.put(eItem.getStem() + family.getPOS(), eItem);
        }
        try {
          // gather features
          eItem.getCat().forall(gatherAttrs);
          // record names
          familyAndEntryNames.add(eItem.getName());
          familyAndEntryNames.add(eItem.getQualifiedName());
        } catch (RuntimeException exc) {
          System.err.println("exception for: " + family.getName() + ": " + exc);
        }
      }

      // scan through data
      for (int j = 0; j < data.length; j++) {
        DataItem dItem = data[j];
        _stems.put(
            dItem.getStem() + family.getPOS(), new Pair<DataItem, EntriesItem[]>(dItem, entries));
        // index non-default preds to words
        if (!dItem.getStem().equals(dItem.getPred())) {
          Collection<Word> words = (Collection<Word>) _predToWords.get(dItem.getStem());
          if (words == null) {
            if (!openlex) {
              System.out.print("Warning: couldn't find words for pred '");
              System.out.println(dItem.getPred() + "' with stem '" + dItem.getStem() + "'");
            }
          } else {
            for (Iterator<Word> it = words.iterator(); it.hasNext(); ) {
              _predToWords.put(dItem.getPred(), it.next());
            }
          }
        }
      }

      // index rels to preds
      // nb: this covers relational (eg @x<GenRel>e) and featural (eg @e<tense>past)
      //     elementary predications
      List<String> indexRels = new ArrayList<String>(3);
      String familyIndexRel = family.getIndexRel();
      if (familyIndexRel.length() > 0) {
        indexRels.add(familyIndexRel);
      }
      for (int j = 0; j < entries.length; j++) {
        EntriesItem eItem = entries[j];
        String indexRel = eItem.getIndexRel();
        if (indexRel.length() > 0 && !indexRel.equals(familyIndexRel)) {
          indexRels.add(indexRel);
        }
      }
      for (Iterator<String> it = indexRels.iterator(); it.hasNext(); ) {
        String indexRel = it.next();
        // nb: not indexing on entries items, b/c some stems are still defaults
        for (int j = 0; j < data.length; j++) {
          DataItem dItem = data[j];
          _relsToPreds.put(indexRel, dItem.getPred());
        }
      }

      // index coart rels (features, really) to preds
      String coartRel = family.getCoartRel();
      if (coartRel.length() > 0) {
        for (int j = 0; j < data.length; j++) {
          _coartRelsToPreds.put(coartRel, data[j].getPred());
        }
      }
    }

    // index the macros
    _macros = new GroupMap<String, FeatureStructure>();
    // nb: could just index MacroItem objects for feature structures too;
    //     this might be a bit cleaner, but life is short
    _macroItems = new HashMap<String, MacroItem>();
    for (MacroItem mi : macroModel) {
      String macName = mi.getName();
      FeatureStructure[] specs = mi.getFeatureStructures();
      for (int j = 0; j < specs.length; j++) {
        _macros.put(macName, specs[j]);
      }
      // this is for handling LF part of macros
      _macroItems.put(macName, mi);
    }

    // with morph items, check POS, macro names, excluded list for xref
    for (MorphItem morphItem : morph) {
      Word w = morphItem.getWord();
      if (!openlex
          && !_stems.containsKey(w.getStem() + w.getPOS())
          && !_posToEntries.containsKey(w.getPOS())) {
        System.err.println(
            "Warning: no entries for stem '"
                + w.getStem()
                + "' and POS '"
                + w.getPOS()
                + "' found for word '"
                + w
                + "'");
      }
      String[] macroNames = morphItem.getMacros();
      for (int j = 0; j < macroNames.length; j++) {
        if (!_macroItems.containsKey(macroNames[j])) {
          System.err.println(
              "Warning: macro "
                  + macroNames[j]
                  + " not found for word '"
                  + morphItem.getWord()
                  + "'");
        }
      }
      String[] excludedNames = morphItem.getExcluded();
      for (int j = 0; j < excludedNames.length; j++) {
        if (!familyAndEntryNames.contains(excludedNames[j])) {
          System.err.println(
              "Warning: excluded family or entry '"
                  + excludedNames[j]
                  + "' not found for word '"
                  + morphItem.getWord()
                  + "'");
        }
      }
    }
  }
Exemplo n.º 7
0
  @SuppressWarnings({"unchecked", "rawtypes"})
  public static void main(String[] args) throws IOException {
    boolean useArguments = false;
    Map config = null;

    try {
      yamlInstance = new Yaml();

      /*
       * Try to load configuration file
       */
      FileReader configFile = new FileReader(YAML_PATH + CONFIGURATION_FILE);
      config = (Map) yamlInstance.load(configFile);

    } catch (FileNotFoundException e) {
      System.out.println(
          "Could not load configuration file. Using program " + "arguments instead.");
      useArguments = true;
    }

    /* Scan for program arguments */
    int port = -1;
    try {

      if (useArguments) port = Integer.parseInt(args[0]);
      else
        // take the port number from the config file
        port = (Integer) config.get("port");

    } catch (ArrayIndexOutOfBoundsException e) {
      System.err.println("DungeonServer: specify a port to which to bind");
      System.out.println(usage());
      System.exit(1);
    }

    /* Attempt to bind to port */
    ServerSocket server = null;
    try {
      server = new ServerSocket(port);
    } catch (IOException e) {
      System.err.printf("DungeonServer: could not listen on port %d\n", port);
      System.exit(2);
    }

    System.out.printf("bound to port %d\n", port);

    System.out.println("loading universe:");

    /* Load universe */
    try {
      System.out.println("\tfinding universe file");

      FileReader universeFile = null;
      if (useArguments) universeFile = new FileReader(YAML_PATH + DEFAULT_UNIVERSE_FILE);
      else universeFile = new FileReader(YAML_PATH + config.get("world") + ".universe.yml");

      Object[] docs = new Object[3];
      Map<String, Object> preamble = null;
      Map<String, Map<String, Object>> rooms = null, items = null;

      try {
        System.out.println("\tchecking universe file");

        int i = 0;
        for (Object o : yamlInstance.loadAll(universeFile)) docs[i++] = o;

        preamble = (Map<String, Object>) docs[0];
        rooms = (Map<String, Map<String, Object>>) docs[1];
        items = (Map<String, Map<String, Object>>) docs[2];

        if (preamble == null || rooms == null || items == null) throw new NullPointerException();

      } catch (ArrayIndexOutOfBoundsException e) {
        System.err.println(
            "DungeonServer: error parsing universe " + "file: too many documents in universe file");
        System.exit(3);
      } catch (NullPointerException e) {
        System.err.println(
            "DungeonServer: error parsing universe " + "file: too few documents in universe file");
        System.exit(3);
      }

      /*
       * Used after parsing rooms to set universe parameters
       */
      boolean doWeather = false;
      String spawnRoomID = null;
      int timescale = -1;
      try {
        System.out.println("\treading preamble");

        /*
         * Load universe parameters from the preamble
         */
        doWeather = (Boolean) validateAndGet(preamble, "weather", Boolean.class);

        spawnRoomID = (String) validateAndGet(preamble, "spawn", String.class);

        timescale = (Integer) validateAndGet(preamble, "timescale", Integer.class);

      } catch (Exception e) {
        System.err.println("DungeonServer: failed parsing preamble (" + e.getMessage() + ")");
        System.exit(4);
      }

      /*
       * Loop through room definitions in universe file
       */

      /**
       * This hash map is used to resolve references from one room to another. Each time a room is
       * parsed, it is added to this map, and henceforth back references to the newly added room
       * will be resolved by checking this map.
       */
      HashMap<String, Room> knownRooms = new HashMap<String, Room>();

      /**
       * This list is maintained to easily check at the end of parsing if there are still references
       * to unseen rooms.
       */
      ArrayList<String> unseenRooms = new ArrayList<String>();

      /**
       * This is a list of triples (A, B, C) such that A is a room waiting for a reference to
       * another room, C, through a direction B. For A and B, the string ID of the rooms are used
       * (the same key used in the knownRooms hash map). This list is used whenever a room's exit
       * references cannot actually be resolved because the destination room has not yet been
       * parsed. At the end of parsing, as long as the unseenRooms list is empty, this list is
       * traversed to resolve the remaining references.
       */
      ArrayList<Triple<String, Direction, String>> unresolved;
      unresolved = new ArrayList<Triple<String, Direction, String>>();

      String thisRoomID = null;
      try {
        System.out.println("\tparsing rooms");

        for (Map.Entry<String, Map<String, Object>> m : rooms.entrySet()) {
          thisRoomID = m.getKey();
          Map<String, Object> thisMap = m.getValue();

          String roomName = (String) validateAndGet(thisMap, "name", String.class);

          String description = (String) validateAndGet(thisMap, "description", String.class);

          Hashtable<Pair<DayPart, Weather>, String> details;
          details = getDetails(thisMap);

          Room r = new Room(roomName, description, details);

          if (thisMap.containsKey("neverUseArticle")) {
            boolean neverUseArticle =
                (Boolean) validateAndGet(thisMap, "neverUseArticle", Boolean.class);

            r.setNeverUseArticle(neverUseArticle);
          }

          if (unseenRooms.contains(thisRoomID)) unseenRooms.remove(thisRoomID);

          knownRooms.put(thisRoomID, r);

          /*
           * Process exits out of this room
           */
          Map<String, String> exits = (Map) validateAndGet(thisMap, "exits", Map.class);

          for (Map.Entry<String, String> exit : exits.entrySet()) {
            String thisDirection = exit.getKey();
            String toRoomID = exit.getValue();

            /*
             * Verify the direction from the file
             */
            Direction dir;
            dir = Direction.fromString(thisDirection);
            if (dir == null) throw new InvalidDirectionException(thisDirection);

            /*
             * Look up the destination room in the hash map
             */
            if (knownRooms.containsKey(toRoomID)) r.addExit(dir, knownRooms.get(toRoomID));
            else {
              if (!unseenRooms.contains(toRoomID)) unseenRooms.add(toRoomID);

              Triple<String, Direction, String> t;
              t = new Triple<String, Direction, String>(thisRoomID, dir, toRoomID);
              unresolved.add(t);
            }
          }
        }
      } catch (Exception e) {
        System.err.println(
            "DungeonServer: failed parsing room '" + thisRoomID + "' (" + e.getMessage() + ")");
        System.exit(4);
      }

      if (!unseenRooms.isEmpty()) throw new UnresolvedReferenceException(unseenRooms);

      /*
       * Invariant: There were no references to undefined rooms in the
       * file. Invariant: All the rooms in the file have been
       * instantiated.
       *
       * All rooms in the universe file have been parsed, but there may
       * still be exits waiting to be added because their destination was
       * not yet parsed at the time. Now loop through the unresolved list
       * to set them up.
       */
      for (Triple<String, Direction, String> t : unresolved) {
        Room fromRoom = knownRooms.get(t.first);
        Room toRoom = knownRooms.get(t.third);
        Direction dir = t.second;

        fromRoom.addExit(dir, toRoom);
      }

      /*
       * Invariant: All exits in the file have been set up among the
       * rooms.
       */

      Room spawnRoom = knownRooms.get(spawnRoomID);
      universe = new DungeonUniverse(spawnRoom, doWeather, timescale, knownRooms.values());

      universeFile.close();

    } catch (Exception e) {
      System.err.println("DungeonServer: failed loading universe " + "(" + e.getMessage() + ")");
      System.exit(2);
    }

    System.out.println("loaded universe");

    /* Start narrator */
    try {
      narrator = new DungeonNarrator();
    } catch (Exception e) {
      System.err.println("DungeonServer: failed starting narrator");
      System.exit(3);
    }

    System.out.println("started narrator");

    /* Start the game tick */
    try {
      tick = new DungeonGameTick();
      tick.start();
    } catch (Exception e) {
      System.err.println("DungeonServer: failed starting game tick");
      System.exit(3);
    }

    System.out.println("started game tick");

    /* Start accepting events */
    try {
      events = new DungeonDispatcher();
      events.start();
    } catch (Exception e) {
      System.err.println("DungeonServer: failed starting event queue");
      System.exit(3);
    }

    System.out.println("started event queue");

    /* Listen for clients */
    try {
      System.out.println("listening for clients");

      while (true) new DungeonConnectionThread(server.accept()).start();
    } catch (IOException e) {
      System.err.printf("DungeonServer: failed accepting client on port %d\n", port);
      System.exit(2);
    } finally {
      server.close();
    }
  }