Exemplo n.º 1
1
  private void loop() {
    while (thread == Thread.currentThread()) {
      try {
        Request key = peekKey();
        if (key == null) throw new IOException("end of stream");
        synchronized (response_map) {
          Response response = (Response) response_map.get(key);
          if (response == null) {
            if (log.level >= 4) log.println("Invalid key, skipping message");
            doSkip();
          } else {
            doRecv(response);
            response.isReceived = true;
            response_map.notifyAll();
          }
        }
      } catch (Exception ex) {
        String msg = ex.getMessage();
        boolean timeout = msg != null && msg.equals("Read timed out");
        /* If just a timeout, try to disconnect gracefully
         */
        boolean hard = timeout == false;

        if (!timeout && log.level >= 3) ex.printStackTrace(log);

        try {
          disconnect(hard);
        } catch (IOException ioe) {
          ioe.printStackTrace(log);
        }
      }
    }
  }
Exemplo n.º 2
0
 public void setObjectValues() {
   ((JTextField) (fields.get("board"))).setText(sketch.getBoard().getName());
   ((JTextField) (fields.get("core"))).setText(sketch.getCore().getName());
   ((JTextField) (fields.get("compiler"))).setText(sketch.getCompiler().getName());
   ((JTextField) (fields.get("port"))).setText(sketch.getDevice().toString());
   ((JTextField) (fields.get("programmer"))).setText(sketch.getProgrammer());
 }
Exemplo n.º 3
0
 /**
  * Returns the index of the given relation in the relation sort order, or the index of "*" if the
  * relation is not explicitly listed.
  */
 public Integer getRelationSortIndex(String rel) {
   Integer retval = _relationIndexMap.get(rel);
   if (retval != null) return retval;
   retval = _relationIndexMap.get("*");
   if (retval != null) return retval;
   return new Integer(-1);
 }
Exemplo n.º 4
0
  public synchronized void messageReceived(int to, Message m) {

    DrainMsg mhMsg = (DrainMsg) m;

    log.debug(
        "incoming: localDest: "
            + to
            + " type:"
            + mhMsg.get_type()
            + " hops:"
            + (16 - mhMsg.get_ttl())
            + " seqNo:"
            + mhMsg.get_seqNo()
            + " source:"
            + mhMsg.get_source()
            + " finalDest:"
            + mhMsg.get_dest());

    // lets assume that the network cannot buffer more than 25 drain msgs from a single source at a
    // time (should be more than reasonable)
    if (seqNos.containsKey(new Integer(mhMsg.get_source()))) {
      int oldSeqNo = ((Integer) seqNos.get(new Integer(mhMsg.get_source()))).intValue();
      int upperBound = mhMsg.get_seqNo() + 25;
      int wrappedUpperBound = 25 - (255 - mhMsg.get_seqNo());
      if ((oldSeqNo >= mhMsg.get_seqNo() && oldSeqNo < upperBound)
          || (oldSeqNo >= 0 && oldSeqNo < wrappedUpperBound)) {
        log.debug(
            "Dropping message from "
                + mhMsg.get_source()
                + " with duplicate seqNo: "
                + mhMsg.get_seqNo());
        return;
      }
    }
    seqNos.put(new Integer(mhMsg.get_source()), new Integer(mhMsg.get_seqNo()));

    if (to != spAddr && to != MoteIF.TOS_BCAST_ADDR && to != TOS_UART_ADDR) {
      log.debug("Dropping message not for me.");
      return;
    }

    HashSet promiscuousSet = (HashSet) idTable.get(new Integer(BCAST_ID));
    HashSet listenerSet = (HashSet) idTable.get(new Integer(mhMsg.get_type()));

    if (listenerSet != null && promiscuousSet != null) {
      listenerSet.addAll(promiscuousSet);
    } else if (listenerSet == null && promiscuousSet != null) {
      listenerSet = promiscuousSet;
    }

    if (listenerSet == null) {
      log.debug("No Listener for type: " + mhMsg.get_type());
      return;
    }

    for (Iterator it = listenerSet.iterator(); it.hasNext(); ) {
      MessageListener ml = (MessageListener) it.next();
      ml.messageReceived(to, mhMsg);
    }
  }
Exemplo n.º 5
0
  /**
   * Returns an icon for the specified file.
   *
   * @param file file reference
   * @return icon
   */
  public static Icon file(final IOFile file) {
    if (file == null) return UNKNOWN;

    // fallback code for displaying icons
    final String path = file.path();
    final MediaType type = MediaType.get(path);
    if (type.isXML()) return XML;
    if (type.isXQuery()) return XQUERY;
    if (path.contains(IO.BASEXSUFFIX)) return BASEX;

    // only works with standard dpi (https://bugs.openjdk.java.net/browse/JDK-6817929)
    if (Prop.WIN && !GUIConstants.large()) {
      // retrieve system icons (only supported on Windows)
      final int p = path.lastIndexOf(path, '.');
      final String suffix = p == -1 ? null : path.substring(p + 1);
      Icon icon = null;
      if (suffix != null) icon = FILES.get(suffix);
      if (icon == null) {
        icon = FS.getSystemIcon(file.file());
        if (suffix != null) FILES.put(suffix, icon);
      }
      return icon;
    }
    // default icon chooser
    return type.isText() ? TEXT : UNKNOWN;
  }
Exemplo n.º 6
0
  /**
   * Returns the specified image as icon.
   *
   * @param name name of icon
   * @return icon
   */
  public static ImageIcon icon(final String name) {
    ImageIcon ii = ICONS.get(name);
    if (ii != null) return ii;

    Image img;
    if (GUIConstants.scale > 1) {
      // choose large image or none
      final URL url =
          GUIConstants.large() ? BaseXImages.class.getResource("/img/" + name + "_32.png") : null;

      if (url == null) {
        // resize low-res image if no hi-res image exists
        img = get(url(name));
        final int w = (int) (img.getWidth(null) * GUIConstants.scale);
        final int h = (int) (img.getHeight(null) * GUIConstants.scale);
        final BufferedImage tmp = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
        final Graphics2D g2 = tmp.createGraphics();
        g2.setRenderingHint(
            RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        g2.drawImage(img, 0, 0, w, h, null);
        g2.dispose();
        img = tmp;
      } else {
        img = get(url);
      }
    } else {
      img = get(name);
    }
    ii = new ImageIcon(img);
    ICONS.put(name, ii);
    return ii;
  }
Exemplo n.º 7
0
  public void save() {
    for (String key : fields.keySet()) {
      JComponent comp = fields.get(key);

      if (comp instanceof JTextField) {
        JTextField c = (JTextField) comp;

        if (c.getText().trim().equals("")) {
          sketch.configFile.unset(key);
        } else {
          sketch.configFile.set(key, c.getText());
        }
      } else if (comp instanceof JTextArea) {
        JTextArea c = (JTextArea) comp;

        if (c.getText().trim().equals("")) {
          sketch.configFile.unset(key);
        } else {
          sketch.configFile.set(key, c.getText());
        }
      }
    }

    sketch.saveConfig();
  }
  private JarFile getCachedJarFile(URL url) {
    JarFile result = (JarFile) fileCache.get(url);

    /* if the JAR file is cached, the permission will always be there */
    if (result != null) {
      Permission perm = getPermission(result);
      if (perm != null) {
        SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
          try {
            sm.checkPermission(perm);
          } catch (SecurityException se) {
            // fallback to checkRead/checkConnect for pre 1.2
            // security managers
            if ((perm instanceof java.io.FilePermission)
                && perm.getActions().indexOf("read") != -1) {
              sm.checkRead(perm.getName());
            } else if ((perm instanceof java.net.SocketPermission)
                && perm.getActions().indexOf("connect") != -1) {
              sm.checkConnect(url.getHost(), url.getPort());
            } else {
              throw se;
            }
          }
        }
      }
    }
    return result;
  }
 /**
  * @param key
  * @param options
  */
 private void addSuffixPluralPattern(String key, HashMap<String, String> options) {
   String option = options.get(key);
   if (option != null) {
     patternMap.put(
         key, Pattern.compile("\\b(\\w{" + minPrefixLength + ",})(" + option + ")s?\\b"));
   }
 }
  /** Looks up the local database, creating if necessary. */
  private DataSource findDatabaseImpl(String url, String driverName) throws SQLException {
    try {
      synchronized (_databaseMap) {
        DBPool db = _databaseMap.get(url);

        if (db == null) {
          db = new DBPool();

          db.setVar(url + "-" + _gId++);

          DriverConfig driver = db.createDriver();

          ClassLoader loader = Thread.currentThread().getContextClassLoader();

          Class driverClass = Class.forName(driverName, false, loader);

          driver.setType(driverClass);
          driver.setURL(url);

          db.init();

          _databaseMap.put(url, db);
        }

        return db;
      }
    } catch (RuntimeException e) {
      throw e;
    } catch (SQLException e) {
      throw e;
    } catch (Exception e) {
      throw ConfigException.create(e);
    }
  }
Exemplo n.º 11
0
 public void run() {
   String line;
   String id = null;
   seqs = new HashMap<String, StringBuffer>();
   try {
     //      System.err.println("quality read start");  // debug
     while (true) {
       line = br.readLine();
       // FIX ME: update to use reader...
       if (line == null) break;
       // EOF
       if (line.indexOf(">") == 0) {
         String[] stuff = line.substring(1).split("\\s+");
         id = new String(stuff[0]);
         // HACK, WRONG if line contains comments...
       } else {
         // sequence
         StringBuffer sb = seqs.get(id);
         if (sb == null) seqs.put(id, sb = new StringBuffer());
         sb.append(line);
       }
     }
     data_loaded = true;
     //      System.err.println("quality read end");  // debug
   } catch (Exception e) {
     System.err.println("FASTASequenceReader load error: " + e); // debug
     System.exit(1);
   }
 }
Exemplo n.º 12
0
  void isReadable(SelectionKey k) {
    EventableChannel ec = (EventableChannel) k.attachment();
    long b = ec.getBinding();

    if (ec.isWatchOnly()) {
      if (ec.isNotifyReadable()) eventCallback(b, EM_CONNECTION_NOTIFY_READABLE, null);
    } else {
      myReadBuffer.clear();

      try {
        ec.readInboundData(myReadBuffer);
        myReadBuffer.flip();
        if (myReadBuffer.limit() > 0) {
          if (ProxyConnections != null) {
            EventableChannel target = ProxyConnections.get(b);
            if (target != null) {
              ByteBuffer myWriteBuffer = ByteBuffer.allocate(myReadBuffer.limit());
              myWriteBuffer.put(myReadBuffer);
              myWriteBuffer.flip();
              target.scheduleOutboundData(myWriteBuffer);
            } else {
              eventCallback(b, EM_CONNECTION_READ, myReadBuffer);
            }
          } else {
            eventCallback(b, EM_CONNECTION_READ, myReadBuffer);
          }
        }
      } catch (IOException e) {
        UnboundConnections.add(b);
      }
    }
  }
Exemplo n.º 13
0
  // returns a macro adder for the given morph item
  private MacroAdder getMacAdder(MorphItem mi) {

    // check map
    MacroAdder retval = macAdderMap.get(mi);
    if (retval != null) return retval;

    // set up macro adder
    IntHashSetMap macrosFromLex = new IntHashSetMap();
    String[] newMacroNames = mi.getMacros();
    List<MacroItem> macroItems = new ArrayList<MacroItem>();
    for (int i = 0; i < newMacroNames.length; i++) {
      Set<FeatureStructure> featStrucs = (Set<FeatureStructure>) _macros.get(newMacroNames[i]);
      if (featStrucs != null) {
        for (Iterator<FeatureStructure> fsIt = featStrucs.iterator(); fsIt.hasNext(); ) {
          FeatureStructure fs = fsIt.next();
          macrosFromLex.put(fs.getIndex(), fs);
        }
      }
      MacroItem macroItem = _macroItems.get(newMacroNames[i]);
      if (macroItem != null) {
        macroItems.add(macroItem);
      } else {
        // should be checked earlier too
        System.err.println(
            "Warning: macro " + newMacroNames[i] + " not found for word '" + mi.getWord() + "'");
      }
    }
    retval = new MacroAdder(macrosFromLex, macroItems);

    // update map and return
    macAdderMap.put(mi, retval);
    return retval;
  }
Exemplo n.º 14
0
  public void deregisterListener(int id, MessageListener m) {
    HashSet listenerSet = (HashSet) idTable.get(new Integer(id));

    if (listenerSet == null) {
      throw new IllegalArgumentException("No listeners registered for message type " + id);
    }
    listenerSet.remove(m);
  }
Exemplo n.º 15
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();
 }
Exemplo n.º 16
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;
 }
Exemplo n.º 17
0
 public SocketChannel detachChannel(long sig) {
   EventableSocketChannel ec = (EventableSocketChannel) Connections.get(sig);
   if (ec != null) {
     UnboundConnections.add(sig);
     return ec.getChannel();
   } else {
     return null;
   }
 }
 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.º 19
0
 /**
  * Add a ServiceMonitorFilter to this MonitorFilter
  *
  * @param serviceMonitorFilter Service Specific Filter
  * @exception MonitorFilterException
  * @return ServiceMonitorFilter Modified Filter to the capabilities of the service
  */
 public ServiceMonitorFilter addServiceMonitorFilter(ServiceMonitorFilter serviceMonitorFilter)
     throws MonitorFilterException {
   ModuleClassID moduleClassID = serviceMonitorFilter.getModuleClassID();
   if (serviceMonitorFilters.get(moduleClassID) != null)
     throw new MonitorFilterException(
         "Attempt to add a second Monitor Filter for: " + moduleClassID);
   serviceMonitorFilters.put(moduleClassID, serviceMonitorFilter);
   return serviceMonitorFilter;
 }
Exemplo n.º 20
0
  public void registerListener(int id, MessageListener m) {
    HashSet listenerSet = (HashSet) idTable.get(new Integer(id));

    if (listenerSet == null) {
      listenerSet = new HashSet();
      idTable.put(new Integer(id), listenerSet);
    }
    listenerSet.add(m);
    log.info("New Listener for id=" + id);
  }
 private String getServerAddress(String servletName) {
   // System.out.println("finding server for "+servletName);
   Integer res = methodHashCodesToClusterIds.get(servletName.hashCode());
   if (res != null) {
     // System.out.println("servlet "+servletName+" going to "+res);
     return serverAddresses[res % numberOfServers];
   } else {
     // System.out.println("could not find info on servlet "+servletName);
     return serverAddresses[0];
   }
 }
Exemplo n.º 22
0
  void send(String msg) {
    Iterator it = clients.keySet().iterator();

    while (it.hasNext()) {
      try {
        DataOutputStream out = (DataOutputStream) clients.get(it.next());
        out.writeUTF(msg);
      } catch (IOException e) {
      }
    }
  }
Exemplo n.º 23
0
 private static void writeDuplicates() {
   Main.status("Writing duplicates.");
   if (!dup_post_list.isEmpty()) {
     Main.status(String.format("%s\t%s", "older_post", "newer_post"));
     for (Post post : dup_post_list.keySet()) {
       Main.status(String.format("%s\t%s", post.post_id, dup_post_list.get(post).post_id));
     }
   } else {
     Main.status("There are no duplicates.");
   }
   Main.status("Writing duplicates done.");
 }
Exemplo n.º 24
0
 public boolean startProxy(long from, long to) {
   // lazy init for proxy support check quickly in isReadable
   if (ProxyConnections == null) {
     ProxyConnections = new HashMap<Long, EventableChannel>();
   }
   EventableChannel target = Connections.get(to);
   if (target != null) {
     ProxyConnections.put(from, target);
     return true;
   } else {
     return false;
   }
 }
Exemplo n.º 25
0
  private void addMenuToTray() {
    HashMap categories = new HashMap();

    // create menu list
    Iterator plugins = PluginManager.getInstance().getAvailablePlugins();
    plugins = PluginComparator.sortPlugins(plugins);

    while (plugins.hasNext()) {
      Plugin p = (Plugin) plugins.next();

      JMenu category = (JMenu) categories.get(p.getCategory());
      if (category == null) {
        category = new JMenu(p.getCategory());
        categories.put(p.getCategory(), category);

        // copy menu to real one
        if (!p.getCategory().equals("Invisible")) this.trayIcon.add(category);
      }

      ImageIcon icon = new ImageIcon();
      try {
        icon = new ImageIcon(new URL(p.getDirectory() + p.getIcon()));
        icon = new ImageIcon(icon.getImage().getScaledInstance(16, 16, Image.SCALE_SMOOTH));
      } catch (Exception e) {
        // error at icon loading
      }

      JMenuItem menu = new JMenuItem(p.getTitle(), icon);
      menu.setName(p.getName());
      menu.setToolTipText(p.getToolTip());
      menu.addActionListener(this);
      category.add(menu);
    }

    this.trayIcon.addSeparator();

    // windows
    this.trayIcon.add(new WindowMenu(this));

    // open main interface
    JMenuItem menu = new JMenuItem(tr("open"));
    menu.setName("org.lucane.applications.maininterface");
    menu.addActionListener(this);
    this.trayIcon.add(menu);

    // exit
    menu = new JMenuItem(tr("exit"));
    menu.setName("exit");
    menu.addActionListener(this);
    this.trayIcon.add(menu);
  }
Exemplo n.º 26
0
    protected void handleMessage(Message msg) throws Exception {
      Address dest = msg.getDest();
      long len;
      List tmp;

      len = msg.size(); // todo: use msg.getLength() instead of msg.getSize()
      if (len > max_bundle_size) {
        throw new Exception(
            "UDP.BundlingOutgoingPacketHandler.handleMessage(): "
                + "message size ("
                + len
                + ") is greater than UDP fragmentation size. "
                + "Set the fragmentation/bundle size in FRAG and UDP correctly");
      }

      if (total_bytes + len >= max_bundle_size) {
        if (Trace.trace) {
          Trace.info(
              "UDP.BundlingOutgoingPacketHandler.handleMessage()",
              "sending " + total_bytes + " bytes");
        }
        bundleAndSend(); // send all pending message and clear table
        total_bytes = 0;
      }

      synchronized (msgs) {
        tmp = (List) msgs.get(dest);
        if (tmp == null) {
          tmp = new List();
          msgs.put(dest, tmp);
        }
        tmp.add(msg);
        total_bytes += len;
      }

      if (!timer_running) { // first message to be bundled
        startTimer();
      }
    }
Exemplo n.º 27
0
  void addNewConnections() {
    ListIterator<EventableSocketChannel> iter = DetachedConnections.listIterator(0);
    while (iter.hasNext()) {
      EventableSocketChannel ec = iter.next();
      ec.cleanup();
    }
    DetachedConnections.clear();

    ListIterator<Long> iter2 = NewConnections.listIterator(0);
    while (iter2.hasNext()) {
      long b = iter2.next();

      EventableChannel ec = Connections.get(b);
      if (ec != null) {
        try {
          ec.register();
        } catch (ClosedChannelException e) {
          UnboundConnections.add(ec.getBinding());
        }
      }
    }
    NewConnections.clear();
  }
  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.º 29
0
 /**
  * Get ServiceMonitorFilter subfilter
  *
  * @param moduleClassID ServiceMonitor's moduleClassID
  * @return ServiceMonitorFilter SubFilter or null if not found
  */
 public ServiceMonitorFilter getServiceMonitorFilter(ModuleClassID moduleClassID) {
   return (ServiceMonitorFilter) serviceMonitorFilters.get(moduleClassID);
 }
Exemplo n.º 30
0
 public static String getInfo(String item) {
   return pluginInfo.get(item);
 }