예제 #1
0
  private Core() {
    boolean f = false;
    try {
      for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
        NetworkInterface intf = (NetworkInterface) en.nextElement();
        for (Enumeration enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
          InetAddress inetAddress = (InetAddress) enumIpAddr.nextElement();
          if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
            String ipAddress = inetAddress.getHostAddress().toString();
            this.ip = inetAddress;
            f = true;
            break;
          }
        }
        if (f) break;
      }
    } catch (SocketException ex) {
      ex.printStackTrace();
      System.exit(1);
    }
    this.teams = new HashMap<String, Team>();
    this.judges = new HashMap<String, Judge>();
    this.problems = new HashMap<String, ProblemInfo>();
    this.scheduler = new Scheduler();
    this.timer = new ContestTimer(300 * 60);

    try {
      readConfigure();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
      System.exit(1);
    }
    this.scoreBoardHttpServer = new ScoreBoardHttpServer(this.scoreBoardPort);
  }
  /**
   * Initializes and binds a socket that on a random port number. The method would try to bind on a
   * random port and retry 5 times until a free port is found.
   *
   * @return the socket that we have initialized on a randomport number.
   */
  private DatagramSocket initRandomPortSocket() {
    DatagramSocket resultSocket = null;
    String bindRetriesStr =
        NetaddrActivator.getConfigurationService().getString(BIND_RETRIES_PROPERTY_NAME);

    int bindRetries = 5;

    if (bindRetriesStr != null) {
      try {
        bindRetries = Integer.parseInt(bindRetriesStr);
      } catch (NumberFormatException ex) {
        logger.error(
            bindRetriesStr
                + " does not appear to be an integer. "
                + "Defaulting port bind retries to "
                + bindRetries,
            ex);
      }
    }

    int currentlyTriedPort = NetworkUtils.getRandomPortNumber();

    // we'll first try to bind to a random port. if this fails we'll try
    // again (bindRetries times in all) until we find a free local port.
    for (int i = 0; i < bindRetries; i++) {
      try {
        resultSocket = new DatagramSocket(currentlyTriedPort);
        // we succeeded - break so that we don't try to bind again
        break;
      } catch (SocketException exc) {
        if (exc.getMessage().indexOf("Address already in use") == -1) {
          logger.fatal(
              "An exception occurred while trying to create" + "a local host discovery socket.",
              exc);
          resultSocket = null;
          return null;
        }
        // port seems to be taken. try another one.
        logger.debug("Port " + currentlyTriedPort + " seems in use.");
        currentlyTriedPort = NetworkUtils.getRandomPortNumber();
        logger.debug("Retrying bind on port " + currentlyTriedPort);
      }
    }

    return resultSocket;
  }
 public String getLocalIpAddress() {
   try {
     for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
         en.hasMoreElements(); ) {
       NetworkInterface intf = en.nextElement();
       for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses();
           enumIpAddr.hasMoreElements(); ) {
         InetAddress inetAddress = enumIpAddr.nextElement();
         // if (!inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress() &&
         // inetAddress.isSiteLocalAddress() ) {
         if (!inetAddress.isLoopbackAddress()
             && InetAddressUtils.isIPv4Address(inetAddress.getHostAddress())) {
           String ipAddr = inetAddress.getHostAddress();
           return ipAddr;
         }
       }
     }
   } catch (SocketException ex) {
     Log.d(TAG, ex.toString());
   }
   return null;
 }
예제 #4
0
 public static void showNIC() {
   // http://www.informatik-blog.net/2009/01/28/informationen-der-netzwerkkarten-auslesen/
   try {
     Enumeration<NetworkInterface> interfaceNIC = NetworkInterface.getNetworkInterfaces();
     // Alle Schnittstellen durchlaufen
     while (interfaceNIC.hasMoreElements()) {
       // Elemente abfragen und ausgeben
       NetworkInterface n = interfaceNIC.nextElement();
       System.out.println(
           String.format("Netzwerk-Interface: %s (%s)", n.getName(), n.getDisplayName()));
       // Adressen abrufen
       Enumeration<InetAddress> addresses = n.getInetAddresses();
       // Adressen durchlaufen
       while (addresses.hasMoreElements()) {
         InetAddress address = addresses.nextElement();
         System.out.println(String.format("- %s", address.getHostAddress()));
       }
     }
     System.out.println();
   } catch (SocketException e) {
     e.printStackTrace();
   }
 }
 /**
  * Discover WS device on the local network
  *
  * @return list of unique devices access strings which might be URLs in most cases
  */
 public static Collection<String> discoverWsDevices() {
   final Collection<String> addresses = new ConcurrentSkipListSet<>();
   final CountDownLatch serverStarted = new CountDownLatch(1);
   final CountDownLatch serverFinished = new CountDownLatch(1);
   final Collection<InetAddress> addressList = new ArrayList<>();
   try {
     final Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
     if (interfaces != null) {
       while (interfaces.hasMoreElements()) {
         NetworkInterface anInterface = interfaces.nextElement();
         if (!anInterface.isLoopback()) {
           final List<InterfaceAddress> interfaceAddresses = anInterface.getInterfaceAddresses();
           for (InterfaceAddress address : interfaceAddresses) {
             addressList.add(address.getAddress());
           }
         }
       }
     }
   } catch (SocketException e) {
     e.printStackTrace();
   }
   ExecutorService executorService = Executors.newCachedThreadPool();
   for (final InetAddress address : addressList) {
     Runnable runnable =
         new Runnable() {
           public void run() {
             try {
               final String uuid = UUID.randomUUID().toString();
               final String probe =
                   WS_DISCOVERY_PROBE_MESSAGE.replaceAll(
                       "<wsa:MessageID>urn:uuid:.*</wsa:MessageID>",
                       "<wsa:MessageID>urn:uuid:" + uuid + "</wsa:MessageID>");
               final int port = random.nextInt(20000) + 40000;
               @SuppressWarnings("SocketOpenedButNotSafelyClosed")
               final DatagramSocket server = new DatagramSocket(port, address);
               new Thread() {
                 public void run() {
                   try {
                     final DatagramPacket packet = new DatagramPacket(new byte[4096], 4096);
                     server.setSoTimeout(WS_DISCOVERY_TIMEOUT);
                     long timerStarted = System.currentTimeMillis();
                     while (System.currentTimeMillis() - timerStarted < (WS_DISCOVERY_TIMEOUT)) {
                       serverStarted.countDown();
                       server.receive(packet);
                       final Collection<String> collection =
                           parseSoapResponseForUrls(
                               Arrays.copyOf(packet.getData(), packet.getLength()));
                       for (String key : collection) {
                         addresses.add(key);
                       }
                     }
                   } catch (SocketTimeoutException ignored) {
                   } catch (Exception e) {
                     e.printStackTrace();
                   } finally {
                     serverFinished.countDown();
                     server.close();
                   }
                 }
               }.start();
               try {
                 serverStarted.await(1000, TimeUnit.MILLISECONDS);
               } catch (InterruptedException e) {
                 e.printStackTrace();
               }
               if (address instanceof Inet4Address) {
                 server.send(
                     new DatagramPacket(
                         probe.getBytes(),
                         probe.length(),
                         InetAddress.getByName(WS_DISCOVERY_ADDRESS_IPv4),
                         WS_DISCOVERY_PORT));
               } else {
                 server.send(
                     new DatagramPacket(
                         probe.getBytes(),
                         probe.length(),
                         InetAddress.getByName(WS_DISCOVERY_ADDRESS_IPv6),
                         WS_DISCOVERY_PORT));
               }
             } catch (Exception e) {
               e.printStackTrace();
             }
             try {
               serverFinished.await((WS_DISCOVERY_TIMEOUT), TimeUnit.MILLISECONDS);
             } catch (InterruptedException e) {
               e.printStackTrace();
             }
           }
         };
     executorService.submit(runnable);
   }
   try {
     executorService.shutdown();
     executorService.awaitTermination(WS_DISCOVERY_TIMEOUT + 2000, TimeUnit.MILLISECONDS);
   } catch (InterruptedException ignored) {
   }
   return addresses;
 }
  /**
   * Create a multicast socket and join the multicast group. This method creates a multicast socket
   * that is used to broadcast The <CODE>DiscoveryResponder</CODE> will then join the multicast
   * group and send a join message. This method has no effect if the <CODE>DiscoveryResponder</CODE>
   * is <CODE>ONLINE</CODE> or <CODE>STOPPING</CODE> or <CODE>STARTING</CODE>.
   *
   * @exception IOException The creation of the Multicast socket failed.
   */
  public void start() throws IOException {
    if (state == OFFLINE) {
      changeState(STARTING);
      if (cmf == null) {
        if (logger.finerOn()) {
          logger.finer("start ", "Can't start discoveryResponder: JDMK MBeanServer is not set");
        }
        return;
      }

      // ----------------
      // Create a new obj to receive multicast msg ;
      // ----------------
      try {
        if (logger.finerOn()) {
          logger.finer("start ", "Create a new responder");
        }
        responder =
            new ActualResponder(multicastGroup, multicastPort, getTimeToLive(), cmf, spy, this);

        if (local != null) {
          responder.setLocalHost(local);
        }

        // NPCTE fix for bugId 4499338, esc 0, 04 Sept 2001
        if (usrInet != null) {
          responder.setInterface(usrInet);

          if (logger.finerOn()) {
            logger.finer("start ", "set interface to " + usrInet);
          }
        }
        // end of NPCTE fix for bugId 4499338

        if (noEvent != null) responder.noEvent();

        if (logger.finerOn()) {
          logger.finer("start ", "call responder connect");
        }
        responder.connectToGroup();

        // ----------------
        // Create a new thread to receive multicast msg ;
        // ----------------
        // responderThread = cmf.getThreadAllocatorSrvIf().obtainThread(responderObjectName,
        // responder);
        responderThread = new Thread(responder);
        responderThread.setName("Multicast responder");

        // ----------------
        // Start thread
        // ----------------
        responderThread.start();

        // ----------------
        // Update state
        // ----------------
        // changeState(ONLINE) ;
      } catch (SocketException e) {
        if (logger.finestOn()) {
          logger.finest("start", e);
        }
        throw new IOException(e.getMessage());

      } catch (IOException e) {
        // ------------------------
        // Keep exception for us
        // ------------------------
        if (logger.finestOn()) {
          logger.finest("start ", e);
        }
        throw e;
      } catch (NullPointerException e) {
        // ------------------------
        // the set group did not worked
        // ------------------------
        if (logger.finestOn()) {
          logger.finest("start ", e);
        }
        throw new IOException(e.getMessage());
      }
    } else {
      if (logger.finerOn()) {
        logger.finer("start ", "Responder is not OFFLINE");
      }
    }
  }
  public void run() {
    CelebTreeMap<String> temp = tNode; // keeps track of the first node
    CelebTreeMap<String> finalMap = temp; // used later to save the MapTree to file

    // prompt for name
    outToClient.println("Please enter your name\n");
    outToClient.flush();
    String name;
    try {
      name = inFromUser.readLine();
      this.player = new User(socket, name);
    } catch (IOException e3) {
      // TODO Auto-generated catch block
      e3.printStackTrace();
    }

    // Initialize variables
    String response; // store user response
    boolean continueRound = true; // continuing round until told otherwise

    while (true) { // inf loop-- Signifies each Guessing Game Match Round
      try { // set Timeout to 0 so user has inf. time to answer. Meant to be used in case user adds
            // to tree, causing
        // user to get their timeout set to 20 secs. This overwrites this
        this.socket.setSoTimeout(0);
      } catch (SocketException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
      }

      boolean hasStartedOver = true; // Keeps track if the game has ended yet

      // Read response
      try {
        do {
          // prompt to play game
          outToClient.println("Would you like to play a guessing game?");
          outToClient.flush();
          invalidResponse = true;
          response = inFromUser.readLine();
          if (response.equals("y")
              || response.equals("yes")) { // play/continue to play guessing game
            voicemail(); // Check to see if this.this.player B guessed your celeb
            continueRound = true;
            invalidResponse = false;
          } else if (response.equals("n") || response.equals("no")) { // exit guessing game
            continueRound = false;
            voicemail(); // Check to see if this.this.player B guessed your celeb
            invalidResponse = false;
            outToClient.println("\nGood Bye!");
            outToClient.flush();
            this.socket.close();
            break;
          }
        } while (invalidResponse);

        while (continueRound) { // inf loop-- Signifies each Guessing Game Question Round
          // start the tree back in its original position if the match starts over

          if (hasStartedOver == true) tNode = temp;

          if (tNode.isLeaf()) { // check to see if the node is a leaf (contains no children)
            // prevent other threads from modifying the tree
            synchronized (tNode) {
              this.socket.setSoTimeout(
                  20000); // prevent one user from blocking another user. 20 secs

              if (tNode
                  .isLeaf()) { // Check again to see if Leaf (or hasnt been added recently). If not,
                               // Loop again

                outToClient.println("Is your Celebrity " + tNode.getItem() + "?");
                outToClient.flush();
                response = inFromUser.readLine();

                if (response.equals("n") || response.equals("no")) { // if celebrity is NOT correct,
                  // add to database

                  outToClient.println("Who were you thinking of?");
                  outToClient.flush();

                  String person = inFromUser.readLine(); // person player was thinking of

                  outToClient.println(
                      "Question that would help distinguish "
                          + person
                          + " from "
                          + tNode.getItem()
                          + "?");
                  outToClient.flush();

                  String question = inFromUser.readLine(); // question player assigns to person

                  outToClient.println("What would you answer to the question?");
                  outToClient.flush();

                  String answerToQuestion = inFromUser.readLine(); // ans to question play assigns

                  outToClient.println("Thank you for adding to the guessing game database!");
                  outToClient.flush();

                  init = new ArrayList<String>();
                  init.add(this.player.toString()); // add play name to arraylist
                  String addedCeleb = new String(person);
                  allCelebs.put(addedCeleb, init); // add archived celeb and arraylist of player
                  this.player.addToList(person); // add the celeb to the User array

                  tNode.setQuestion(question); // add question to node

                  if (answerToQuestion.equals("y")
                      || answerToQuestion.equals("yes")) { // add celeb to corresponding node:
                    tNode.setLeft(new CelebTreeMap<String>(person)); // "yes" set to left
                    tNode.setRight(new CelebTreeMap<String>(tNode.getItem()));
                  } else { // "no" to right
                    tNode.setRight(new CelebTreeMap<String>(person));
                    tNode.setLeft(new CelebTreeMap<String>(tNode.getItem()));
                  }
                  saveToFile(finalMap);

                } else if (response.equals("y")
                    || response.equals(
                        "yes")) { // Program has guessed correctly! Print statement and break
                                  // Question Rounds
                  outToClient.println("\nI have guessed your star!");
                  outToClient.println("\nThank you for playing!\n\n");
                  outToClient.flush();
                  try { // handle adding player who had their celeb guessed. Add them to HashMap
                    init = new ArrayList<String>();
                    init =
                        allCelebs.get(
                            tNode
                                .getItem()); // arraylist is set equal the Arraylist<String>
                                             // containing the player

                    init.add(
                        this.player
                            .toString()); // arraylist adds the player who got celebrity guesed to
                                          // list

                    allCelebs.put(
                        tNode.getItem(),
                        init); // HashMap contains the person guessed correctly with a list of
                               // people who guessed the person
                  } catch (NullPointerException npe) {
                  }
                  break;
                }
                hasStartedOver = true;
                break;
              }
            } // End of Synchronized
          } else {
            hasStartedOver = false; // game has not started over/is in progress
            do {
              outToClient.println(tNode.getQuestion());
              outToClient.flush();

              response = inFromUser.readLine();
              invalidResponse = true;
              if (response.equals("y")
                  || response.equals("yes")) { // move to node to left node if user enters "yes"
                tNode = tNode.getLeft();
                invalidResponse = false;
              } else if (response.equals("n") || response.equals("no")) {
                invalidResponse = false;
                tNode = tNode.getRight(); // move to right if user types anything but yes/no
              }
            } while (invalidResponse);
          }
          // end synchronized
        } // end while
      } // end while
      catch (SocketException s) {
        try {
          this.socket.close();
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      } catch (SocketTimeoutException ste) {
        outToClient.println("timed out");
        outToClient.flush();
      } // end SocketTimeoutEx
      catch (IOException e) {
        System.err.println(e);
        e.printStackTrace();
        try {
          socket.close();
        } catch (IOException e1) {
          e1.printStackTrace();
        } // End  Catch IOException
      } // End IOException
    } // end Guessing Game Round While Loop
  } // end Run Method