Exemplo n.º 1
0
  public void testRejoinSysprocButFail() throws Exception {
    VoltProjectBuilder builder = getBuilderForTest();
    boolean success = builder.compile(Configuration.getPathToCatalogForTest("rejoin.jar"), 1, 1, 0);
    assertTrue(success);
    MiscUtils.copyFile(
        builder.getPathToDeployment(), Configuration.getPathToCatalogForTest("rejoin.xml"));

    VoltDB.Configuration config = new VoltDB.Configuration();
    config.m_pathToCatalog = Configuration.getPathToCatalogForTest("rejoin.jar");
    config.m_pathToDeployment = Configuration.getPathToCatalogForTest("rejoin.xml");
    config.m_isRejoinTest = true;
    ServerThread localServer = new ServerThread(config);

    localServer.start();
    localServer.waitForInitialization();

    Client client = ClientFactory.createClient();
    client.createConnection("localhost");

    SyncCallback scb = new SyncCallback();
    success = false;
    while (!success) {
      success = client.callProcedure(scb, "@Rejoin", "localhost", config.m_internalPort + 1);
      if (!success) Thread.sleep(100);
    }

    scb.waitForResponse();
    ClientResponse response = scb.getResponse();
    assertTrue(response.getStatusString().contains("Unable to find down node"));

    client.close();
    localServer.shutdown();
    localServer.join();
  }
Exemplo n.º 2
0
 /** Prijme spojeni od klienta */
 public ServerThread accept() throws IOException {
   ServerThread st;
   st = new ServerThread(getServerSocket().accept());
   st.setServer(this);
   st.start();
   return st;
 }
 public void close() {
   stop = true;
   ServerThread st = server;
   if (st != null) {
     st.interrupt();
   }
 }
 @Override
 public void run() {
   Log.i(TAG, "Server " + addr.getHostName() + " started");
   while (true) {
     try {
       Socket socket = serverSocket.accept();
       int flag = socket.getInputStream().read();
       if (flag == FLAG_REQUEST) {
         DataInputStream in = new DataInputStream(socket.getInputStream());
         String text = in.readUTF();
         Log.i(TAG, text);
         playText(text, service);
         in.close();
       } else if (flag == FLAG_STOP_ALL) {
         Log.i(
             TAG, "Detected \"stop all\" signal from " + socket.getInetAddress().getHostName());
         for (ServerThread st : serverThreads) {
           st.stop();
         }
         break;
       }
     } catch (IOException ex) {
       Log.e(TAG, "", ex);
     }
   }
   Log.i(TAG, "Server " + addr.getHostName() + " finished");
   if (!destroyed) {
     stop();
   }
 }
Exemplo n.º 5
0
  /** Waits for incoming connections and spins off threads to deal with them. */
  private void listen() {
    Socket client = new Socket();
    ServerThread st;

    /* Should only do this when it hasn't been told to shutdown. */
    while (!shutdown) {
      /* Try to accept an incoming connection. */
      try {
        client = serversock.accept();
        if (debug)
          /* Output info about the client */
          System.out.println(
              "Client on machine "
                  + client.getInetAddress().getHostAddress()
                  + " has connected on port "
                  + client.getLocalPort()
                  + ".");

        /*
         * Create a new thread to deal with the client, add it to the
         * vector of open connections. Finally, start the thread's
         * execution. Start method makes the threads go by calling their
         * run() methods.
         */
        st = new ServerThread(client, this, clientcounter++, debug);
        serverthreads.add(st);
        st.start();
      } catch (IOException e) {
        /*
         * Server Socket is closed, probably because a client told the
         * server to shutdown
         */
      }
    }
  }
 /** Closes all open sockets and stops the internal server thread that processes messages. */
 public void close() {
   ServerThread st = server;
   if (st != null) {
     st.close();
     try {
       st.join();
     } catch (InterruptedException ex) {
       logger.warn(ex);
     }
     server = null;
     for (Iterator it = sockets.values().iterator(); it.hasNext(); ) {
       SocketEntry entry = (SocketEntry) it.next();
       try {
         synchronized (entry) {
           entry.getSocket().close();
         }
         logger.debug("Socket to " + entry.getPeerAddress() + " closed");
       } catch (IOException iox) {
         // ingore
         logger.debug(iox);
       }
     }
     if (socketCleaner != null) {
       socketCleaner.cancel();
     }
     socketCleaner = null;
   }
 }
Exemplo n.º 7
0
 /* starts the socket server */
 private void startServer(boolean isDaemon, int pause) {
   // try to connect, if no connection then start new server
   try {
     System.err.println("testing connection");
     getClient().process("test");
   } catch (Exception ioe) {
     System.err.println("no connection, so starting server");
     // no connection, so start server
     server =
         new ServerThread(
             getModuleName() + "-server",
             getCodeCall() + " " + getPort() + " " + getParams(),
             isDaemon);
     server.start();
     try {
       // pause to allow loading data for some modules
       Thread.sleep(pause);
     } catch (Exception e) {
       System.err.println(e);
     }
     // keep a reference to the process provided through the thread to be
     // able to destroy it when the module gets destroyed.  Otherwise,
     // the process continues to run in the background even when the
     // module has been destroyed.
     p = server.getProcess();
     return;
   }
 }
 /**
  * Returns the name of the listen thread.
  *
  * @return the thread name if in listening mode, otherwise <code>null</code>.
  * @since 1.6
  */
 public String getThreadName() {
   ServerThread st = server;
   if (st != null) {
     return st.getName();
   } else {
     return null;
   }
 }
 /**
  * Returns the priority of the internal listen thread.
  *
  * @return a value between {@link Thread#MIN_PRIORITY} and {@link Thread#MAX_PRIORITY}.
  * @since 1.2.2
  */
 public int getPriority() {
   ServerThread st = server;
   if (st != null) {
     return st.getPriority();
   } else {
     return Thread.NORM_PRIORITY;
   }
 }
Exemplo n.º 10
0
 /**
  * Nastavi server game protihraci
  *
  * @param login Login protihrace
  * @param serverGame Server game
  */
 public synchronized boolean serverGame(String login, ServerGame serverGame) {
   ServerThread st = getClients().get(login.toLowerCase());
   if (st == null) {
     return false;
   } else {
     st.setServerGame(serverGame);
     return true;
   }
 }
Exemplo n.º 11
0
 /**
  * Provede odhlaseni uzivatele Odesle informaci o odhlaseni ostatnim uzivatelum
  *
  * @param serverThread Vlakno serveru
  */
 public synchronized void logout(ServerThread serverThread) {
   if (serverThread.getLogin() != null) {
     clients.remove(serverThread.getLogin().toLowerCase());
     Enumeration<ServerThread> e = getClients().elements();
     while (e.hasMoreElements()) {
       e.nextElement().userLogout(serverThread.getLogin());
     }
   }
 }
Exemplo n.º 12
0
 /**
  * Odesle informaci ostatnim hracum, ze je tento hrac uz neni ve hre
  *
  * @param login Login hrace
  */
 public synchronized void userOutGame(String login) {
   Enumeration<ServerThread> e = getClients().elements();
   while (e.hasMoreElements()) {
     ServerThread serverThread = e.nextElement();
     if (!serverThread.getLogin().toLowerCase().equals(login.toLowerCase())) {
       serverThread.userOutGame(login);
     }
   }
 }
Exemplo n.º 13
0
 /**
  * Odesle konec hry
  *
  * @param login Login protihrace
  */
 public synchronized boolean gameEnd(String login) {
   ServerThread st = getClients().get(login.toLowerCase());
   if (st == null) {
     return false;
   } else {
     st.gameEnd();
     return true;
   }
 }
Exemplo n.º 14
0
 /**
  * Provede tah figurkou
  *
  * @param x Zdrojova souradnice X
  * @param y Zdrojova souradnice Y
  * @param toX Cilova souradnice X
  * @param toY Cilova souradnice Y
  * @return True pokud se tah povedl
  */
 public synchronized boolean turn(String login, int x, int y, int toX, int toY) {
   ServerThread st = getClients().get(login.toLowerCase());
   if (st == null) {
     return false;
   } else {
     st.turn(x, y, toX, toY);
     return true;
   }
 }
Exemplo n.º 15
0
 /**
  * processes the input String and produces an output String.
  *
  * @param input the String to input to the underlying process
  * @throws java.lang.Exception exceptions from Runtime and Process that this class uses
  * @return the output from the underlying process
  */
 public String process(String input) throws Exception {
   String returnValue = new String();
   StringBuffer buffer = new StringBuffer();
   if (socketServer == true) {
     returnValue = client.process(input);
     ServerThread current = getServer();
     if (current != null) {
       if (!current.isDaemon()) {
         current.getProcess().destroy();
       }
       current.interrupt();
     }
   } else { // not a socket server
     Runtime rt = Runtime.getRuntime();
     String output = "";
     String errors = "";
     try {
       p = rt.exec(getCodeCall() + " " + getParams());
       PrintStream processInputStream = new PrintStream(p.getOutputStream(), true, "utf-8");
       processInputStream.println(input + "\n\u0003"); // put in garbage to kill Bikel's loop
       StreamConsumer errorConsumer = new StreamConsumer(p.getErrorStream(), "error", 1);
       StreamConsumer outputConsumer = new StreamConsumer(p.getInputStream(), "output", 10);
       outputConsumer.start();
       errorConsumer.start();
       int countloops = 0;
       int time = 0;
       String message = "";
       while (!outputConsumer.isComplete()) {
         // wait
         Thread.sleep(100);
         countloops++;
         time += 100; // one tenth of a second
         if (time > waittime) { // just wait 5 minutes
           message = "exceeded waittime of " + waittime + " milliseconds";
           break;
         }
       }
       errors = errorConsumer.getOutput();
       output = outputConsumer.getOutput();
       if (!message.equals("")) {
         errors = message;
       }
     } catch (IOException ioe) {
       System.err.println("Module error: " + getModuleName());
       ioe.printStackTrace();
       System.exit(0);
     }
     p.destroy();
     if (errors.equals("")) {
       returnValue = output;
     } else {
       returnValue = errors;
     }
   }
   return returnValue;
 }
Exemplo n.º 16
0
  /**
   * Provede prihlaseni uzivatele Odesle mu seznam aktualnich uzivatelu a r ozesle informaci o
   * prihlaseni ostatnim uzivatelum
   *
   * @param serverThread Vlakno serveru
   */
  public synchronized boolean login(ServerThread serverThread) {
    if (clients.containsKey(serverThread.getLogin().toLowerCase())) {
      return false;
    }

    // Send login info to other clients
    Enumeration<ServerThread> e = getClients().elements();
    while (e.hasMoreElements()) {
      e.nextElement().userLogin(serverThread.getLogin());
    }

    // Send users list to client
    Enumeration<ServerThread> e2 = getClients().elements();
    while (e2.hasMoreElements()) {
      ServerThread serverThread2 = e2.nextElement();
      serverThread.userLogin(serverThread2.getLogin());
      if (serverThread2.getServerGame() != null) {
        serverThread.userInGame(serverThread2.getLogin());
      }
    }

    // Append client to list
    clients.put(serverThread.getLogin().toLowerCase(), serverThread);

    return true;
  }
 /**
  * Listen for incoming and outgoing requests. If the <code>serverEnabled</code> member is <code>
  * false</code> the server for incoming requests is not started. This starts the internal server
  * thread that processes messages.
  *
  * @throws SocketException when the transport is already listening for incoming/outgoing messages.
  * @throws IOException
  */
 public synchronized void listen() throws java.io.IOException {
   if (server != null) {
     throw new SocketException("Port already listening");
   }
   server = new ServerThread();
   if (connectionTimeout > 0) {
     socketCleaner = new Timer(true); // run as daemon
   }
   server.setDaemon(true);
   server.start();
 }
Exemplo n.º 18
0
  @Override
  public void onCreate() {
    if (shouldRunAsServer()) {
      mDataServerBinder = new DataServerBinder();
      mBluetoothReceiver = new BluetoothReceiver();
      mAdapter = BluetoothAdapter.getDefaultAdapter();

      if (!mIsWorkAsGenerator) {
        IntentFilter bluetoothFilter = new IntentFilter();
        bluetoothFilter.addAction(BluetoothDevice.ACTION_PAIRING_REQUEST);
        bluetoothFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        bluetoothFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);

        registerReceiver(mBluetoothReceiver, bluetoothFilter);

        mAdapter.setName("Health Device");
        if (!mAdapter.isEnabled()) {
          mAdapter.enable();
        }
        if (mAdapter.getState() == BluetoothAdapter.STATE_ON) {
          mAdapter.setScanMode(BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE, 0);
          mAdapter.setDiscoverableTimeout(0);
        }
      }

      mServerThread = new ServerThread();
      mServerThread.start();
    }
  }
Exemplo n.º 19
0
  /**
   * Called by a thread who's client has asked to exit. Gets rid of the thread.
   *
   * @param st The ServerThread to remove from the vector of active connections.
   */
  public void kill(ServerThread st) {
    if (debug) System.out.println("Killing Client " + st.getID() + ".");

    /* Find the thread in the vector and remove it. */
    for (int i = 0; i < serverthreads.size(); i++) {
      if (serverthreads.elementAt(i) == st) serverthreads.remove(i);
    }
  }
Exemplo n.º 20
0
 @Override
 public void onCreate() {
   super.onCreate();
   mIpAddress = Util.getHostIp(this);
   mServerThread = new ServerThread();
   mServerThread.start();
   Log.d("MyService", "onCreate()");
 }
Exemplo n.º 21
0
  public void testRejoinPropogateAdminMode() throws Exception {
    // Reset the VoltFile prefix that may have been set by previous tests in this suite
    org.voltdb.utils.VoltFile.resetSubrootForThisProcess();
    VoltProjectBuilder builder = getBuilderForTest();
    builder.setSecurityEnabled(true);

    LocalCluster cluster =
        new LocalCluster("rejoin.jar", 2, 3, 1, BackendTarget.NATIVE_EE_JNI, true);
    boolean success = cluster.compileWithAdminMode(builder, 9998, false);
    assertTrue(success);
    MiscUtils.copyFile(
        builder.getPathToDeployment(), Configuration.getPathToCatalogForTest("rejoin.xml"));
    cluster.setHasLocalServer(false);

    cluster.startUp();

    ClientResponse response;
    Client client;

    client = ClientFactory.createClient(m_cconfig);
    client.createConnection("localhost", 9997);

    response = client.callProcedure("@Pause");
    assertEquals(ClientResponse.SUCCESS, response.getStatus());
    client.close();

    cluster.shutDownSingleHost(0);
    Thread.sleep(100);

    VoltDB.Configuration config = new VoltDB.Configuration();
    config.m_pathToCatalog = Configuration.getPathToCatalogForTest("rejoin.jar");
    config.m_pathToDeployment = Configuration.getPathToCatalogForTest("rejoin.xml");
    config.m_rejoinToHostAndPort = m_username + ":" + m_password + "@localhost:9996";
    config.m_isRejoinTest = true;
    ServerThread localServer = new ServerThread(config);

    localServer.start();
    localServer.waitForInitialization();

    Thread.sleep(1000);

    assertTrue(VoltDB.instance().getMode() == OperationMode.PAUSED);

    localServer.shutdown();
    cluster.shutDown();
  }
Exemplo n.º 22
0
 private void testConnection(
     KeyStore serverKeyStore,
     KeyStore serverTrustStore,
     KeyStore clientKeyStore,
     KeyStore clientTrustStore)
     throws Exception {
   SSLContext serverSSLContext = SSLContexts.create(serverKeyStore, pass, serverTrustStore);
   SSLContext clientSSLContext = SSLContexts.create(clientKeyStore, pass, clientTrustStore);
   ServerThread serverThread = new ServerThread();
   try {
     serverThread.start(serverSSLContext, port, 1);
     String clientErrorMessage = ClientThread.connect(clientSSLContext, port);
     Assert.assertNull(clientErrorMessage);
     Assert.assertNull(serverThread.getErrorMessage());
   } finally {
     serverThread.close();
   }
 }
Exemplo n.º 23
0
 @Override
 public int onStartCommand(Intent intent, int flags, int startId) {
   if (mServerThread == null) {
     mServerThread = new ServerThread();
     mServerThread.start();
   }
   this.registerReceiver(receiver, new IntentFilter(ALARM_REBOOT_ACTION));
   return super.onStartCommand(intent, flags, startId);
 }
Exemplo n.º 24
0
  public static void main(String[] args) {
    int portNumber = 1234;
    try {
      // create server to handles all client sockets
      ServerSocket serverSocket = new ServerSocket(portNumber);

      // loop forever waiting for clients
      while (true) {
        Socket clientSocket = serverSocket.accept();
        ServerThread thread = new ServerThread(clientSocket);
        thread.start();
      }

    } catch (IOException e) {
      System.out.println("exception on port " + portNumber);
      System.out.println(e.getMessage());
    }
  }
Exemplo n.º 25
0
  public Server() {
    try {
      serverSocket = new ServerSocket(1210);
      // window.setText("Сервер запущен. Адрес: " + serverSocket.getInetAddress().toString());
      System.out.println("Сервер запущен. Адрес: " + serverSocket.getInetAddress().toString());
      while (true) {
        // System.out.println("eee");
        klientSocket = serverSocket.accept();
        // window.setText("Подключён клиент. Адрес: " + klientSocket.getInetAddress().toString());
        System.out.println("Подключён клиент. Адрес: " + klientSocket.getInetAddress().toString());
        ServerThread server = new ServerThread(klientSocket);

        server.run(); // запуск потока
        // window.setText(server.getPlane().toString());
      }
    } catch (IOException e) {
      System.err.println(e);
    }
  }
Exemplo n.º 26
0
  public void testServerSocketConnection() throws IOException, InterruptedException {
    ServerSocketConnection scn = (ServerSocketConnection) Connector.open("socket://:" + serverPort);

    try {
      ServerThread t = new ServerThread(scn);
      t.start();
      while (!t.started) {
        Thread.sleep(20);
      }
      assertEquals("Server Port", Integer.valueOf(serverPort).intValue(), scn.getLocalPort());
      assertNotEquals("Server Host", "0.0.0.0", scn.getLocalAddress());
      assertNotEquals("Server Host", "localhost", scn.getLocalAddress());
      // assertNotEquals("Server Host", "127.0.0.1", scn.getLocalAddress());

      runLoopbackTest("socket://" + scn.getLocalAddress() + ":" + scn.getLocalPort());
    } finally {
      scn.close();
    }
  }
Exemplo n.º 27
0
 public String execHtmlPage(String fileName, String input) throws Exception {
   // 'file' protocol is not supported by Selenium Safari driver
   // so we run an embedded Jetty server
   ServerThread thread = new ServerThread(fileName);
   thread.start();
   try {
     while (thread.server == null && thread.ex == null) Thread.sleep(10);
     if (thread.ex != null) throw thread.ex;
     while (thread.server.isStarting()) Thread.sleep(10);
     Thread.sleep(
         400); // despite all the above precautions, driver.get often fails if you don't give time
               // to Jetty
     driver.get("http://localhost:" + httpPort + "/" + fileName);
     driver.findElement(new ById("input")).clear();
     driver.findElement(new ById("output")).clear();
     driver.findElement(new ById("errors")).clear();
     driver.navigate().refresh();
     driver.findElement(new ById("input")).sendKeys(input);
     driver.findElement(new ById("load")).click();
     driver.findElement(new ById("submit")).click();
     String errors = driver.findElement(new ById("errors")).getAttribute("value");
     if (errors != null && errors.length() > 0) {
       this.stderrDuringParse = errors;
       System.err.print(errors);
     }
     String value = driver.findElement(new ById("output")).getAttribute("value");
     // mimic stdout which adds a NL
     if (value.length() > 0 && !value.endsWith("\n")) value = value + "\n";
     return value;
   } catch (Exception e) {
     System.err.println("can't exec recognizer");
     e.printStackTrace(System.err);
   } finally {
     if (thread.server != null) {
       thread.server.stop();
       while (!thread.server.isStopped()) Thread.sleep(10);
       Thread.sleep(100); // ensure the port is freed
     }
   }
   return null;
 }
Exemplo n.º 28
0
  private void handleDisconnection() {
    connectionState = ConnectionState.NOT_CONNECTED;
    if (socketType == SocketType.PLAYER_SOCKET && serverThread != null) {
      serverThread.removeClient(this);
    }

    if (socket != null) {
      this.socket.dispose();
    }

    Gdx.app.debug(TAG, "Socket disconnected.");
  }
Exemplo n.º 29
0
  private void doLogonTest(String keyStoreName, String keyStorePassword)
      throws InterruptedException, ConfigError {
    ServerThread serverThread = new ServerThread(keyStoreName, keyStorePassword);
    try {
      serverThread.setDaemon(true);
      serverThread.start();
      serverThread.waitForInitialization();

      SessionID clientSessionID = new SessionID(FixVersions.BEGINSTRING_FIX42, "TW", "ISLD");
      SessionSettings settings = getClientSessionSettings(clientSessionID);
      ClientApplication clientApplication = new ClientApplication();
      ThreadedSocketInitiator initiator =
          new ThreadedSocketInitiator(
              clientApplication, new MemoryStoreFactory(), settings, new DefaultMessageFactory());

      try {
        log.info("Do login");
        clientApplication.setUpLogonExpectation();
        initiator.start();
        Session clientSession = Session.lookupSession(clientSessionID);
        assertLoggedOn(clientApplication, clientSession);
      } finally {
        initiator.stop();
      }
    } finally {
      serverThread.interrupt();
      serverThread.join();
    }
  }
Exemplo n.º 30
0
 private void testDynamicNameRevocation(
     KeyStore serverKeyStore,
     KeyStore serverTrustStore,
     KeyStore clientKeyStore,
     KeyStore clientTrustStore,
     String revokeName)
     throws Exception {
   logger.info("testRevoke: " + revokeName);
   Set<String> revokedNames = new ConcurrentSkipListSet();
   SSLContext serverSSLContext =
       RevocableNameSSLContexts.create(serverKeyStore, pass, serverTrustStore, revokedNames);
   SSLContext clientSSLContext = SSLContexts.create(clientKeyStore, pass, clientTrustStore);
   ServerThread serverThread = new ServerThread();
   try {
     serverThread.start(serverSSLContext, port, 2);
     Assert.assertNull(ClientThread.connect(clientSSLContext, port));
     Assert.assertNull(serverThread.getErrorMessage());
     revokedNames.add(revokeName);
     logger.debug("revokedNames: " + revokedNames);
     Thread.sleep(1000);
     Assert.assertNotNull(ClientThread.connect(clientSSLContext, port));
     Assert.assertNotNull(serverThread.getErrorMessage());
   } finally {
     serverThread.close();
     serverThread.join(1000);
   }
 }