コード例 #1
0
ファイル: Main.java プロジェクト: templetonm/NetSecurity
 public static void main(String[] args) {
   if (args.length != 1) {
     System.out.println("\nbad args");
     System.out.println(
         "usage:java hw3.java TEMPLETON_STARTING_VALUE SIKORSKI_STARTING_VALUE CR89_STARTING_VALUE\n");
   } else {
     try {
       Client client1 =
           new Client(
               "TEMPLETON",
               MONITOR_NAME,
               MONITOR_PORT,
               HOST_NAME,
               44444,
               Integer.parseInt(args[0]),
               Integer.parseInt(args[1]),
               Integer.parseInt(args[2]));
       client1.start();
       Server server1 = new Server("TEMPLETON", MONITOR_PORT, 44444);
       server1.start();
       Client client2 =
           new Client(
               "SIKORSKI",
               MONITOR_NAME,
               MONITOR_PORT,
               HOST_NAME,
               44445,
               Integer.parseInt(args[0]),
               Integer.parseInt(args[1]),
               Integer.parseInt(args[2]));
       client2.start();
       Server server2 = new Server("SIKORSKI", MONITOR_PORT, 44445);
       server2.start();
       Client client3 =
           new Client(
               "CR89",
               MONITOR_NAME,
               MONITOR_PORT,
               HOST_NAME,
               44446,
               Integer.parseInt(args[0]),
               Integer.parseInt(args[1]),
               Integer.parseInt(args[2]));
       client3.start();
       Server server3 = new Server("CR89", MONITOR_PORT, 44446);
       server3.start();
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
 }
コード例 #2
0
  @Test(timeout = 90000)
  public void testRPCInterruptedSimple() throws IOException {
    final Configuration conf = new Configuration();
    Server server =
        new RPC.Builder(conf)
            .setProtocol(TestProtocol.class)
            .setInstance(new TestImpl())
            .setBindAddress(ADDRESS)
            .setPort(0)
            .setNumHandlers(5)
            .setVerbose(true)
            .setSecretManager(null)
            .build();

    server.start();
    InetSocketAddress addr = NetUtils.getConnectAddress(server);

    final TestProtocol proxy = RPC.getProxy(TestProtocol.class, TestProtocol.versionID, addr, conf);
    // Connect to the server
    proxy.ping();
    // Interrupt self, try another call
    Thread.currentThread().interrupt();
    try {
      proxy.ping();
      fail("Interruption did not cause IPC to fail");
    } catch (IOException ioe) {
      if (!ioe.toString().contains("InterruptedException")) {
        throw ioe;
      }
      // clear interrupt status for future tests
      Thread.interrupted();
    }
  }
コード例 #3
0
ファイル: TestRPC.java プロジェクト: thaingo/hadoop-20-append
  private void doRPCs(Configuration conf, boolean expectFailure) throws Exception {
    SecurityUtil.setPolicy(new ConfiguredPolicy(conf, new TestPolicyProvider()));

    Server server = RPC.getServer(new TestImpl(), ADDRESS, 0, 5, true, conf);

    TestProtocol proxy = null;

    server.start();

    InetSocketAddress addr = NetUtils.getConnectAddress(server);

    try {
      proxy = (TestProtocol) RPC.getProxy(TestProtocol.class, TestProtocol.versionID, addr, conf);
      proxy.ping();

      if (expectFailure) {
        fail("Expect RPC.getProxy to fail with AuthorizationException!");
      }
    } catch (RemoteException e) {
      if (expectFailure) {
        assertTrue(e.unwrapRemoteException() instanceof AuthorizationException);
      } else {
        throw e;
      }
    } finally {
      server.stop();
      if (proxy != null) {
        RPC.stopProxy(proxy);
      }
    }
  }
コード例 #4
0
ファイル: TestIPC.java プロジェクト: Ronald33/hadoop-0.21
  public void testSerial(
      int handlerCount, boolean handlerSleep, int clientCount, int callerCount, int callCount)
      throws Exception {
    Server server = new TestServer(handlerCount, handlerSleep);
    InetSocketAddress addr = NetUtils.getConnectAddress(server);
    server.start();

    Client[] clients = new Client[clientCount];
    for (int i = 0; i < clientCount; i++) {
      clients[i] = new Client(LongWritable.class, conf);
    }

    SerialCaller[] callers = new SerialCaller[callerCount];
    for (int i = 0; i < callerCount; i++) {
      callers[i] = new SerialCaller(clients[i % clientCount], addr, callCount);
      callers[i].start();
    }
    for (int i = 0; i < callerCount; i++) {
      callers[i].join();
      assertFalse(callers[i].failed);
    }
    for (int i = 0; i < clientCount; i++) {
      clients[i].stop();
    }
    server.stop();
  }
コード例 #5
0
ファイル: MainActivity.java プロジェクト: nezharen/FileSharer
 @Override
 public void run() {
   ConnectivityManager connMgr =
       (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
   NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
   if ((networkInfo == null)
       || (!networkInfo.isConnected())
       || (networkInfo.getType() != ConnectivityManager.TYPE_WIFI)) {
     bundle.putInt(
         Constants.SERVER_THREAD_STATUS, Constants.SERVER_THREAD_STATUS_WIFI_NOT_CONNECTED);
     msg.setData(bundle);
     MainActivity.this.serverThreadMessageHandler.sendMessage(msg);
     return;
   }
   WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
   WifiInfo wifiInfo = wifiManager.getConnectionInfo();
   int ipAddress = wifiInfo.getIpAddress();
   String ip =
       (ipAddress & 0xff)
           + "."
           + (ipAddress >> 8 & 0xff)
           + "."
           + (ipAddress >> 16 & 0xff)
           + "."
           + (ipAddress >> 24 & 0xff);
   try {
     serverSocket = new ServerSocket(Constants.SERVER_PORT);
     bundle.putInt(Constants.SERVER_THREAD_STATUS, Constants.SERVER_THREAD_STATUS_LISTENING);
     bundle.putString(Constants.IP_ADDRESS, ip);
     msg.setData(bundle);
     MainActivity.this.serverThreadMessageHandler.sendMessage(msg);
   } catch (Exception e) {
     bundle.putInt(Constants.SERVER_THREAD_STATUS, Constants.SERVER_THREAD_STATUS_INIT_FAILED);
     msg.setData(bundle);
     MainActivity.this.serverThreadMessageHandler.sendMessage(msg);
     return;
   }
   Socket clientSocket;
   while (true) {
     try {
       clientSocket = serverSocket.accept();
       String hostAddress = clientSocket.getInetAddress().getHostAddress();
       boolean inClients = false;
       for (Client client : clients)
         if (client.host.equals(hostAddress)) {
           inClients = true;
           break;
         }
       if (!inClients) {
         Client newClient = new Client(hostAddress);
         clients.add(newClient);
         newClient.connect();
       }
       Server server = new Server(clientSocket, hostAddress);
       servers.add(server);
       server.start();
     } catch (Exception e) {
     }
   }
 }
コード例 #6
0
 public void run() {
   ServerSocket mainSocket = null;
   try {
     mainSocket = new ServerSocket(wyldConfig.getPort());
   } catch (IOException e) {
     Misc.println(Messages.PORT_IN_USE.getDesc());
   }
   Misc.println(
       "[Socket] Listening on port " + wyldConfig.getPort() + " for incoming connections.");
   while (true) {
     Socket connectionSocket = null;
     try {
       connectionSocket = mainSocket.accept();
     } catch (IOException e) {
       Misc.servere(e.toString());
     }
     try {
       Server thread = new Server(connectionSocket, i, irc);
       thread.start();
       irc.clients.add(thread);
     } catch (java.lang.NullPointerException e) {
       e.printStackTrace();
     }
     i++;
   }
 }
コード例 #7
0
  @Test
  public void testConnectionPing() throws Exception {
    Configuration conf = new Configuration();
    int pingInterval = 50;
    conf.setBoolean(CommonConfigurationKeys.IPC_CLIENT_PING_KEY, true);
    conf.setInt(CommonConfigurationKeys.IPC_PING_INTERVAL_KEY, pingInterval);
    final Server server =
        new RPC.Builder(conf)
            .setProtocol(TestProtocol.class)
            .setInstance(new TestImpl())
            .setBindAddress(ADDRESS)
            .setPort(0)
            .setNumHandlers(5)
            .setVerbose(true)
            .build();
    server.start();

    final TestProtocol proxy =
        RPC.getProxy(TestProtocol.class, TestProtocol.versionID, server.getListenerAddress(), conf);
    try {
      // this call will throw exception if server couldn't decode the ping
      proxy.sleep(pingInterval * 4);
    } finally {
      if (proxy != null) RPC.stopProxy(proxy);
    }
  }
コード例 #8
0
  @Test
  public void testProxyAddress() throws IOException {
    Server server =
        new RPC.Builder(conf)
            .setProtocol(TestProtocol.class)
            .setInstance(new TestImpl())
            .setBindAddress(ADDRESS)
            .setPort(0)
            .build();
    TestProtocol proxy = null;

    try {
      server.start();
      InetSocketAddress addr = NetUtils.getConnectAddress(server);

      // create a client
      proxy = RPC.getProxy(TestProtocol.class, TestProtocol.versionID, addr, conf);

      assertEquals(addr, RPC.getServerAddress(proxy));
    } finally {
      server.stop();
      if (proxy != null) {
        RPC.stopProxy(proxy);
      }
    }
  }
コード例 #9
0
  @Test(timeout = 90000)
  public void testRPCInterruptedSimple() throws Exception {
    final Configuration conf = new Configuration();
    Server server =
        RPC.getServer(TestProtocol.class, new TestImpl(), ADDRESS, 0, 5, true, conf, null);
    server.start();
    InetSocketAddress addr = NetUtils.getConnectAddress(server);

    final TestProtocol proxy = RPC.getProxy(TestProtocol.class, TestProtocol.versionID, addr, conf);
    // Connect to the server
    proxy.ping();
    // Interrupt self, try another call
    Thread.currentThread().interrupt();
    try {
      proxy.ping();
      fail("Interruption did not cause IPC to fail");
    } catch (IOException ioe) {
      if (!ioe.toString().contains("InterruptedException")) {
        throw ioe;
      }
      // clear interrupt status for future tests
      Thread.interrupted();
    } finally {
      server.stop();
    }
  }
コード例 #10
0
  /** Test that server.stop() properly stops all threads */
  @Test
  public void testStopsAllThreads() throws IOException, InterruptedException {
    int threadsBefore = countThreads("Server$Listener$Reader");
    assertEquals("Expect no Reader threads running before test", 0, threadsBefore);

    final Server server =
        new RPC.Builder(conf)
            .setProtocol(TestProtocol.class)
            .setInstance(new TestImpl())
            .setBindAddress(ADDRESS)
            .setPort(0)
            .setNumHandlers(5)
            .setVerbose(true)
            .build();
    server.start();
    try {
      // Wait for at least one reader thread to start
      int threadsRunning = 0;
      long totalSleepTime = 0;
      do {
        totalSleepTime += 10;
        Thread.sleep(10);
        threadsRunning = countThreads("Server$Listener$Reader");
      } while (threadsRunning == 0 && totalSleepTime < 5000);

      // Validate that at least one thread started (we didn't timeout)
      threadsRunning = countThreads("Server$Listener$Reader");
      assertTrue(threadsRunning > 0);
    } finally {
      server.stop();
    }
    int threadsAfter = countThreads("Server$Listener$Reader");
    assertEquals("Expect no Reader threads left running after test", 0, threadsAfter);
  }
コード例 #11
0
ファイル: Model.java プロジェクト: Neos3452/ItsMeIM
 /** Model startuje i uruchamia wszystkie potrzebne moduły. */
 public void load() {
   if (self == null) {
     outQueue.add(new ProgramClosingEvent());
     throw new NullPointerException("Self contact nie może być null!");
   }
   server.start();
   multicast.start();
   sender.start();
 }
コード例 #12
0
 protected static void start(final Server s) {
   try {
     s.start();
   } catch (Exception ex) {
     ex.printStackTrace();
     System.exit(-1);
   } finally {
     System.out.println("done!");
   }
 }
コード例 #13
0
 public static void main(String[] args) {
   try {
     Server s = new Server();
     s.start();
   } catch (Exception ex) {
     ex.printStackTrace();
     System.exit(-1);
   } finally {
     System.out.println("done!");
   }
 }
コード例 #14
0
  @Test
  public void testSlowRpc() throws IOException {
    System.out.println("Testing Slow RPC");
    // create a server with two handlers
    Server server =
        new RPC.Builder(conf)
            .setProtocol(TestProtocol.class)
            .setInstance(new TestImpl())
            .setBindAddress(ADDRESS)
            .setPort(0)
            .setNumHandlers(2)
            .setVerbose(false)
            .build();

    TestProtocol proxy = null;

    try {
      server.start();

      InetSocketAddress addr = NetUtils.getConnectAddress(server);

      // create a client
      proxy = RPC.getProxy(TestProtocol.class, TestProtocol.versionID, addr, conf);

      SlowRPC slowrpc = new SlowRPC(proxy);
      Thread thread = new Thread(slowrpc, "SlowRPC");
      thread.start(); // send a slow RPC, which won't return until two fast pings
      assertTrue("Slow RPC should not have finished1.", !slowrpc.isDone());

      proxy.slowPing(false); // first fast ping

      // verify that the first RPC is still stuck
      assertTrue("Slow RPC should not have finished2.", !slowrpc.isDone());

      proxy.slowPing(false); // second fast ping

      // Now the slow ping should be able to be executed
      while (!slowrpc.isDone()) {
        System.out.println("Waiting for slow RPC to get done.");
        try {
          Thread.sleep(1000);
        } catch (InterruptedException e) {
        }
      }
    } finally {
      server.stop();
      if (proxy != null) {
        RPC.stopProxy(proxy);
      }
      System.out.println("Down slow rpc testing");
    }
  }
コード例 #15
0
  private void doRPCs(Configuration conf, boolean expectFailure) throws IOException {
    Server server =
        new RPC.Builder(conf)
            .setProtocol(TestProtocol.class)
            .setInstance(new TestImpl())
            .setBindAddress(ADDRESS)
            .setPort(0)
            .setNumHandlers(5)
            .setVerbose(true)
            .build();

    server.refreshServiceAcl(conf, new TestPolicyProvider());

    TestProtocol proxy = null;

    server.start();

    InetSocketAddress addr = NetUtils.getConnectAddress(server);

    try {
      proxy = RPC.getProxy(TestProtocol.class, TestProtocol.versionID, addr, conf);
      proxy.ping();

      if (expectFailure) {
        fail("Expect RPC.getProxy to fail with AuthorizationException!");
      }
    } catch (RemoteException e) {
      if (expectFailure) {
        assertTrue(e.unwrapRemoteException() instanceof AuthorizationException);
      } else {
        throw e;
      }
    } finally {
      server.stop();
      if (proxy != null) {
        RPC.stopProxy(proxy);
      }
      MetricsRecordBuilder rb = getMetrics(server.rpcMetrics.name());
      if (expectFailure) {
        assertCounter("RpcAuthorizationFailures", 1, rb);
      } else {
        assertCounter("RpcAuthorizationSuccesses", 1, rb);
      }
      // since we don't have authentication turned ON, we should see
      // 0 for the authentication successes and 0 for failure
      assertCounter("RpcAuthenticationFailures", 0, rb);
      assertCounter("RpcAuthenticationSuccesses", 0, rb);
    }
  }
コード例 #16
0
ファイル: TestIPC.java プロジェクト: Ronald33/hadoop-0.21
  public void testErrorClient() throws Exception {
    // start server
    Server server = new TestServer(1, false);
    InetSocketAddress addr = NetUtils.getConnectAddress(server);
    server.start();

    // start client
    Client client = new Client(LongErrorWritable.class, conf);
    try {
      client.call(new LongErrorWritable(RANDOM.nextLong()), addr, null, null);
      fail("Expected an exception to have been thrown");
    } catch (IOException e) {
      // check error
      Throwable cause = e.getCause();
      assertTrue(cause instanceof IOException);
      assertEquals(LongErrorWritable.ERR_MSG, cause.getMessage());
    }
  }
 public static void main(String[] args) {
   FileSendTest test = new FileSendTest();
   JFileChooser jfc = new JFileChooser();
   jfc.setAcceptAllFileFilterUsed(true);
   jfc.showOpenDialog(null);
   Socket socket = null;
   FileInputStream in = null;
   CheckedOutputStream cout = null;
   try {
     File file = jfc.getSelectedFile();
     if (file.canRead()) {
       test.setFILE_NAME(file.getName());
       Server s = new Server(test);
       s.start();
       socket = new Socket("127.0.0.1", Server.PORT);
       cout = new CheckedOutputStream(socket.getOutputStream(), new CRC32());
       in = new FileInputStream(file);
       byte[] buffer = new byte[Server.BUFFER_SIZE];
       System.out.println(Calendar.getInstance().getTimeInMillis());
       while ((in.read(buffer)) != -1) {
         cout.write(buffer);
       }
       cout.close();
       in.close();
       System.out.println(Calendar.getInstance().getTimeInMillis());
       System.out.println("Client CRC: " + Long.toHexString(cout.getChecksum().getValue()));
     }
   } catch (Exception e) {
     e.printStackTrace();
   } finally {
     System.out.println("Clien Out...");
     try {
       if (cout != null) {
         cout.close();
       }
       if (socket != null) {
         socket.close();
       }
     } catch (Exception e1) {
       e1.printStackTrace();
     }
   }
 }
コード例 #18
0
ファイル: TestPubSub.java プロジェクト: ChenXuJasper/pubsub
  @Test
  public void testBPubSub() throws InterruptedException {
    String topic = "test";

    // Start pubsub server
    Server server =
        new Server("127.0.0.1", Settings.CLIENT_SUBSCRIBE_PORT, Settings.CLIENT_PUBLISH_PORT);
    server.start();

    // Create publisher and subscriber
    Publisher publisher = new Publisher("127.0.0.1", Settings.CLIENT_PUBLISH_PORT);
    Subscriber subscriber = new Subscriber("127.0.0.1", Settings.CLIENT_SUBSCRIBE_PORT);

    // Subscribe to test topic
    TestPubSubCallback cb = new TestPubSubCallback();
    subscriber.subscribe(topic, cb);
    Thread.sleep(1000);

    // Publish a message
    System.out.println("Publisher publishing " + "hello" + " on topic " + topic);
    publisher.publish(topic, PubSubProtos.StringMessage.newBuilder().setMessage("hello").build());
    cb.awaitMessage("hello");

    // Publish a message
    System.out.println("Publisher publishing " + "hello" + " on topic " + "badtest");
    publisher.publish(
        "badtest", PubSubProtos.StringMessage.newBuilder().setMessage("hello").build());
    cb.awaitNoMessage("hello");

    // Publish a message
    System.out.println("Publisher publishing " + "hello2" + " on topic " + topic);
    publisher.publish(topic, PubSubProtos.StringMessage.newBuilder().setMessage("hello2").build());
    cb.awaitMessage("hello2");

    // Unsubscribe
    subscriber.unsubscribe(topic, cb);
    Thread.sleep(1000);

    // Publish a message
    System.out.println("Publisher publishing " + "hello2" + " on topic " + topic);
    publisher.publish(topic, PubSubProtos.StringMessage.newBuilder().setMessage("hello2").build());
    cb.awaitNoMessage("hello2");
  }
コード例 #19
0
  /**
   * {@inheritDoc}
   *
   * @see
   *     com.continuent.tungsten.replicator.plugin.ReplicatorPlugin#prepare(com.continuent.tungsten.replicator.plugin.PluginContext)
   */
  public synchronized void prepare(PluginContext context)
      throws ReplicatorException, InterruptedException {
    // Prepare database connection.
    if (url != null && url.trim().length() > 0) {
      logger.info("Preparing SQL catalog tables");
      ReplicatorRuntime runtime = (ReplicatorRuntime) context;
      String metadataSchema = context.getReplicatorSchemaName();
      catalog = new CatalogManager(runtime);
      catalog.connect(url, user, password, metadataSchema, vendor);
      catalog.prepareSchema();
    } else logger.info("SQL catalog tables are disabled");

    // Configure and prepare the log.
    diskLog = new DiskLog();
    diskLog.setDoChecksum(doChecksum);
    diskLog.setEventSerializerClass(eventSerializer);
    diskLog.setLogDir(logDir);
    diskLog.setLogFileSize(logFileSize);
    diskLog.setLogFileRetainMillis(logFileRetainMillis);
    diskLog.setLogConnectionTimeoutMillis(logConnectionTimeout * 1000);
    diskLog.setBufferSize(bufferSize);
    diskLog.setFsyncOnFlush(fsyncOnFlush);
    if (fsyncOnFlush) {
      // Only used with fsync.
      diskLog.setFlushIntervalMillis(flushIntervalMillis);
    }
    diskLog.setReadOnly(readOnly);
    diskLog.prepare();
    logger.info("Log preparation is complete");

    // Start server for THL connections.
    if (context.isRemoteService() == false) {
      try {
        server = new Server(context, sequencer, this);
        server.start();
      } catch (IOException e) {
        throw new ReplicatorException("Unable to start THL server", e);
      }
    }
  }
コード例 #20
0
 /*
  *  To run as a console application just open a console window and:
  * > java Server
  * > java Server portNumber
  * If the port number is not specified 1500 is used
  */
 public static void main(String[] args) {
   // start server on port 1500 unless a PortNumber is specified
   int portNumber = 1500;
   switch (args.length) {
     case 1:
       try {
         portNumber = Integer.parseInt(args[0]);
       } catch (Exception e) {
         System.out.println("Port yang diisikan invalid.");
         System.out.println("Usage is: > java Server [portNumber]");
         return;
       }
     case 0:
       break;
     default:
       System.out.println("Usage is: > java Server [portNumber]");
       return;
   }
   // create a server object and start it
   Server server = new Server(portNumber);
   server.start();
 }
コード例 #21
0
 @Test
 public void testRpcMetrics() throws Exception {
   Configuration configuration = new Configuration();
   final int interval = 1;
   configuration.setBoolean(CommonConfigurationKeys.RPC_METRICS_QUANTILE_ENABLE, true);
   configuration.set(CommonConfigurationKeys.RPC_METRICS_PERCENTILES_INTERVALS_KEY, "" + interval);
   final Server server =
       new RPC.Builder(configuration)
           .setProtocol(TestProtocol.class)
           .setInstance(new TestImpl())
           .setBindAddress(ADDRESS)
           .setPort(0)
           .setNumHandlers(5)
           .setVerbose(true)
           .build();
   server.start();
   final TestProtocol proxy =
       RPC.getProxy(
           TestProtocol.class, TestProtocol.versionID, server.getListenerAddress(), configuration);
   try {
     for (int i = 0; i < 1000; i++) {
       proxy.ping();
       proxy.echo("" + i);
     }
     MetricsRecordBuilder rpcMetrics = getMetrics(server.getRpcMetrics().name());
     assertTrue(
         "Expected non-zero rpc queue time", getLongCounter("RpcQueueTimeNumOps", rpcMetrics) > 0);
     assertTrue(
         "Expected non-zero rpc processing time",
         getLongCounter("RpcProcessingTimeNumOps", rpcMetrics) > 0);
     MetricsAsserts.assertQuantileGauges("RpcQueueTime" + interval + "s", rpcMetrics);
     MetricsAsserts.assertQuantileGauges("RpcProcessingTime" + interval + "s", rpcMetrics);
   } finally {
     if (proxy != null) {
       RPC.stopProxy(proxy);
     }
     server.stop();
   }
 }
コード例 #22
0
  @Test
  public void testErrorMsgForInsecureClient() throws IOException {
    Configuration serverConf = new Configuration(conf);
    SecurityUtil.setAuthenticationMethod(AuthenticationMethod.KERBEROS, serverConf);
    UserGroupInformation.setConfiguration(serverConf);

    final Server server =
        new RPC.Builder(serverConf)
            .setProtocol(TestProtocol.class)
            .setInstance(new TestImpl())
            .setBindAddress(ADDRESS)
            .setPort(0)
            .setNumHandlers(5)
            .setVerbose(true)
            .build();
    server.start();

    UserGroupInformation.setConfiguration(conf);
    boolean succeeded = false;
    final InetSocketAddress addr = NetUtils.getConnectAddress(server);
    TestProtocol proxy = null;
    try {
      proxy = RPC.getProxy(TestProtocol.class, TestProtocol.versionID, addr, conf);
      proxy.echo("");
    } catch (RemoteException e) {
      LOG.info("LOGGING MESSAGE: " + e.getLocalizedMessage());
      assertTrue(e.unwrapRemoteException() instanceof AccessControlException);
      succeeded = true;
    } finally {
      server.stop();
      if (proxy != null) {
        RPC.stopProxy(proxy);
      }
    }
    assertTrue(succeeded);

    conf.setInt(CommonConfigurationKeys.IPC_SERVER_RPC_READ_THREADS_KEY, 2);

    UserGroupInformation.setConfiguration(serverConf);
    final Server multiServer =
        new RPC.Builder(serverConf)
            .setProtocol(TestProtocol.class)
            .setInstance(new TestImpl())
            .setBindAddress(ADDRESS)
            .setPort(0)
            .setNumHandlers(5)
            .setVerbose(true)
            .build();
    multiServer.start();
    succeeded = false;
    final InetSocketAddress mulitServerAddr = NetUtils.getConnectAddress(multiServer);
    proxy = null;
    try {
      UserGroupInformation.setConfiguration(conf);
      proxy = RPC.getProxy(TestProtocol.class, TestProtocol.versionID, mulitServerAddr, conf);
      proxy.echo("");
    } catch (RemoteException e) {
      LOG.info("LOGGING MESSAGE: " + e.getLocalizedMessage());
      assertTrue(e.unwrapRemoteException() instanceof AccessControlException);
      succeeded = true;
    } finally {
      multiServer.stop();
      if (proxy != null) {
        RPC.stopProxy(proxy);
      }
    }
    assertTrue(succeeded);
  }
コード例 #23
0
  private void testCallsInternal(Configuration conf) throws IOException {
    Server server =
        new RPC.Builder(conf)
            .setProtocol(TestProtocol.class)
            .setInstance(new TestImpl())
            .setBindAddress(ADDRESS)
            .setPort(0)
            .build();
    TestProtocol proxy = null;
    try {
      server.start();

      InetSocketAddress addr = NetUtils.getConnectAddress(server);
      proxy = RPC.getProxy(TestProtocol.class, TestProtocol.versionID, addr, conf);

      proxy.ping();

      String stringResult = proxy.echo("foo");
      assertEquals(stringResult, "foo");

      stringResult = proxy.echo((String) null);
      assertEquals(stringResult, null);

      // Check rpcMetrics
      MetricsRecordBuilder rb = getMetrics(server.rpcMetrics.name());
      assertCounter("RpcProcessingTimeNumOps", 3L, rb);
      assertCounterGt("SentBytes", 0L, rb);
      assertCounterGt("ReceivedBytes", 0L, rb);

      // Number of calls to echo method should be 2
      rb = getMetrics(server.rpcDetailedMetrics.name());
      assertCounter("EchoNumOps", 2L, rb);

      // Number of calls to ping method should be 1
      assertCounter("PingNumOps", 1L, rb);

      String[] stringResults = proxy.echo(new String[] {"foo", "bar"});
      assertTrue(Arrays.equals(stringResults, new String[] {"foo", "bar"}));

      stringResults = proxy.echo((String[]) null);
      assertTrue(Arrays.equals(stringResults, null));

      UTF8 utf8Result = (UTF8) proxy.echo(new UTF8("hello world"));
      assertEquals(utf8Result, new UTF8("hello world"));

      utf8Result = (UTF8) proxy.echo((UTF8) null);
      assertEquals(utf8Result, null);

      int intResult = proxy.add(1, 2);
      assertEquals(intResult, 3);

      intResult = proxy.add(new int[] {1, 2});
      assertEquals(intResult, 3);

      // Test protobufs
      EnumDescriptorProto sendProto = EnumDescriptorProto.newBuilder().setName("test").build();
      EnumDescriptorProto retProto = proxy.exchangeProto(sendProto);
      assertEquals(sendProto, retProto);
      assertNotSame(sendProto, retProto);

      boolean caught = false;
      try {
        proxy.error();
      } catch (IOException e) {
        if (LOG.isDebugEnabled()) {
          LOG.debug("Caught " + e);
        }
        caught = true;
      }
      assertTrue(caught);

      proxy.testServerGet();

      // create multiple threads and make them do large data transfers
      System.out.println("Starting multi-threaded RPC test...");
      server.setSocketSendBufSize(1024);
      Thread threadId[] = new Thread[numThreads];
      for (int i = 0; i < numThreads; i++) {
        Transactions trans = new Transactions(proxy, datasize);
        threadId[i] = new Thread(trans, "TransactionThread-" + i);
        threadId[i].start();
      }

      // wait for all transactions to get over
      System.out.println("Waiting for all threads to finish RPCs...");
      for (int i = 0; i < numThreads; i++) {
        try {
          threadId[i].join();
        } catch (InterruptedException e) {
          i--; // retry
        }
      }

    } finally {
      server.stop();
      if (proxy != null) RPC.stopProxy(proxy);
    }
  }
コード例 #24
0
ファイル: Main.java プロジェクト: GRAAFYME/ContainingJ2P2P
        public void actionPerformed(ActionEvent e) {
          String NameItem = (((JMenuItem) e.getSource()).getText());
          if (NameItem == "Load File") {
            // all files disabled
            fc.setAcceptAllFileFilterUsed(false);

            // only XML files
            FileNameExtensionFilter xmlfilter =
                new FileNameExtensionFilter("xml files (*.xml)", "xml");
            fc.setFileFilter(xmlfilter);

            // Set Directory!!
            fc.setCurrentDirectory(new java.io.File("data"));

            // Open XML
            fc.setDialogTitle("Open XML");
            int returnVal = fc.showOpenDialog(null);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
              File file = fc.getSelectedFile();
              String FileLocation = file.getPath();
              textArea.setText("");
              // textArea.setText(FileLocation + "\n" + "\n");

              // Parse XML
              xmlParser parser = new xmlParser();
              final ContainerSetXml containers;

              try {
                long time = System.nanoTime();
                containers = parser.parse(FileLocation);

                System.out.println(
                    "It took" + (System.nanoTime() - time) + "ns to parse the xml file");
                // new Thread for display next container after some time
                Thread t =
                    new Thread() {
                      public void run() {
                        for (ContainerXml c : containers.containers) {
                          DateFormat dateFormat = new SimpleDateFormat(" HH:mm:ss");
                          Calendar now = Calendar.getInstance();
                          String Time = "[" + dateFormat.format(now.getTime()) + "]";

                          textArea.append(Time + " " + c.id + " " + c.ownerName + "\n");
                          textArea.setCaretPosition(textArea.getDocument().getLength());
                          try {
                            sleep(150); // milliseconds
                          } catch (InterruptedException ex) {
                          }
                        }
                      }
                    };
                t.start(); // call back run()

              } catch (Exception ex) {
                System.out.println(ex);
              }
            }

          } else if (NameItem == "Start server") {
            // server.start() launches server.run() in a new thread
            // Meaning server.start won't freeze the gui anymore
            server.start(6666);
          } else if (NameItem == "Login to ftp") {
            FtpLoginView ftpLoginView = new FtpLoginView(server);
            ftpLoginView.display();
            String name = ftpLoginView.name;
            String password = ftpLoginView.name;

            // server.login() is called in ftpLoginView
          } else if (NameItem == "About") {
            JOptionPane.showMessageDialog(
                null,
                "Mede mogelijk gemaakt door Groep 5!",
                "About",
                JOptionPane.INFORMATION_MESSAGE);
          } else if (NameItem == "Help") {
            JOptionPane.showMessageDialog(
                null, "Moet nog ingevuld worden!", "Help", JOptionPane.INFORMATION_MESSAGE);
          } else if (NameItem == "Quit") {
            System.exit(0);
          } else if (NameItem == "Restart server") {
            server.restart(6666);
          } else if (NameItem == "Stop server") {
            server.stop();
          }
        }
コード例 #25
0
ファイル: Node.java プロジェクト: RodrigoSagach/bitsquare
 public synchronized Server startListening(ServerConnectListener listener) throws IOException {
   if (serverRunning.getAndSet(true)) throw new IOException("This node is already listening!");
   final Server server = new Server(descriptor.getServerSocket(), listener);
   server.start();
   return server;
 }
コード例 #26
0
  @Override
  protected void doExecute() throws MojoExecutionException, MojoFailureException {
    final Log log = getLog();
    final File deploymentFile = file();
    // The deployment must exist before we do anything
    if (!deploymentFile.exists()) {
      throw new MojoExecutionException(
          String.format(
              "The deployment '%s' could not be found.", deploymentFile.getAbsolutePath()));
    }
    // Validate the environment
    final Path jbossHome = extractIfRequired(deploymentFile.getParentFile().toPath());
    if (!Files.isDirectory(jbossHome)) {
      throw new MojoExecutionException(
          String.format("JBOSS_HOME '%s' is not a valid directory.", jbossHome));
    }
    final StandaloneCommandBuilder commandBuilder =
        StandaloneCommandBuilder.of(jbossHome)
            .setJavaHome(javaHome)
            .addModuleDirs(modulesPath.getModulePaths());

    // Set the JVM options
    if (javaOpts != null) {
      commandBuilder.setJavaOptions(javaOpts);
    } else if (jvmArgs != null) {
      commandBuilder.setJavaOptions(jvmArgs.split("\\s+"));
    }

    if (serverConfig != null) {
      commandBuilder.setServerConfiguration(serverConfig);
    }

    if (propertiesFile != null) {
      commandBuilder.setPropertiesFile(propertiesFile);
    }

    if (serverArgs != null) {
      commandBuilder.addServerArguments(serverArgs);
    }

    // Check for management overrides
    final ModelControllerClientConfiguration clientConfiguration = getClientConfiguration();
    final String host = clientConfiguration.getHost();
    final int port = clientConfiguration.getPort();
    if (host != null) {
      commandBuilder.setBindAddressHint("management", host);
    }
    if (port > 0) {
      commandBuilder.addServerArguments("-Djboss.management.http.port=" + port);
    }

    // Print some server information
    log.info(String.format("JAVA_HOME=%s", commandBuilder.getJavaHome()));
    log.info(String.format("JBOSS_HOME=%s%n", commandBuilder.getWildFlyHome()));
    Server server = null;
    try (final ManagementClient client = createClient()) {
      // Create the server
      server = Server.create(commandBuilder, client);
      // Start the server
      log.info("Server is starting up. Press CTRL + C to stop the server.");
      server.start(startupTimeout);
      // Deploy the application
      server.checkServerState();
      if (server.isRunning()) {
        log.info(String.format("Deploying application '%s'%n", deploymentFile.getName()));
        final Deployment deployment =
            StandaloneDeployment.create(client, deploymentFile, name, getType(), null, null);
        switch (executeDeployment(client, deployment, jbossHome)) {
          case REQUIRES_RESTART:
            {
              client.execute(ServerOperations.createOperation(ServerOperations.RELOAD));
              break;
            }
          case SUCCESS:
            break;
        }
      } else {
        throw new DeploymentFailureException("Cannot deploy to a server that is not running.");
      }
      while (server.isRunning()) {
        TimeUnit.SECONDS.sleep(1L);
      }
    } catch (Exception e) {
      throw new MojoExecutionException("The server failed to start", e);
    } finally {
      if (server != null) server.stop();
    }
  }
コード例 #27
0
ファイル: Server.java プロジェクト: leesg1/DistLab
 public static void main(String[] args) throws UnknownHostException, IOException {
   int portNumber = Integer.parseInt(args[0]); // get port number from program parameters
   Server server = new Server(portNumber);
   server.start();
 }
コード例 #28
0
ファイル: Start.java プロジェクト: RoadRunner120485/wicket
    public static void main(String[] args) throws Exception {
        int timeout = (int) Duration.ONE_HOUR.getMilliseconds();

        Server server = new Server();
        SocketConnector connector = new SocketConnector();

        // Set some timeout options to make debugging easier.
        connector.setMaxIdleTime(timeout);
        connector.setSoLingerTime(-1);
        connector.setPort(8080);
        server.addConnector(connector);

        Resource keystore = Resource.newClassPathResource("/keystore");
        if (keystore != null && keystore.exists()) {
            // if a keystore for a SSL certificate is available, start a SSL
            // connector on port 8443.
            // By default, the quickstart comes with a Apache Wicket Quickstart
            // Certificate that expires about half way september 2021. Do not
            // use this certificate anywhere important as the passwords are
            // available in the source.

            connector.setConfidentialPort(8443);

            SslContextFactory factory = new SslContextFactory();
            factory.setKeyStoreResource(keystore);
            factory.setKeyStorePassword("wicket");
            factory.setTrustStoreResource(keystore);
            factory.setKeyManagerPassword("wicket");
            SslSocketConnector sslConnector = new SslSocketConnector(factory);
            sslConnector.setMaxIdleTime(timeout);
            sslConnector.setPort(8443);
            sslConnector.setAcceptors(4);
            server.addConnector(sslConnector);

            System.out.println("SSL access to the quickstart has been enabled on port 8443");
            System.out.println("You can access the application using SSL on https://localhost:8443");
            System.out.println();
        }

        WebAppContext bb = new WebAppContext();
        bb.setServer(server);
        bb.setContextPath("/");
        bb.setWar("src/main/webapp");

        // START JMX SERVER
        // MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
        // MBeanContainer mBeanContainer = new MBeanContainer(mBeanServer);
        // server.getContainer().addEventListener(mBeanContainer);
        // mBeanContainer.start();

        server.setHandler(bb);

        try {
            System.out.println(">>> STARTING EMBEDDED JETTY SERVER, PRESS ANY KEY TO STOP");
            server.start();
            System.in.read();
            System.out.println(">>> STOPPING EMBEDDED JETTY SERVER");
            server.stop();
            server.join();
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }
コード例 #29
0
  @Test(timeout = 30000)
  public void testRPCInterrupted() throws IOException, InterruptedException {
    final Configuration conf = new Configuration();
    Server server =
        new RPC.Builder(conf)
            .setProtocol(TestProtocol.class)
            .setInstance(new TestImpl())
            .setBindAddress(ADDRESS)
            .setPort(0)
            .setNumHandlers(5)
            .setVerbose(true)
            .setSecretManager(null)
            .build();

    server.start();

    int numConcurrentRPC = 200;
    InetSocketAddress addr = NetUtils.getConnectAddress(server);
    final CyclicBarrier barrier = new CyclicBarrier(numConcurrentRPC);
    final CountDownLatch latch = new CountDownLatch(numConcurrentRPC);
    final AtomicBoolean leaderRunning = new AtomicBoolean(true);
    final AtomicReference<Throwable> error = new AtomicReference<Throwable>();
    Thread leaderThread = null;

    for (int i = 0; i < numConcurrentRPC; i++) {
      final int num = i;
      final TestProtocol proxy =
          RPC.getProxy(TestProtocol.class, TestProtocol.versionID, addr, conf);
      Thread rpcThread =
          new Thread(
              new Runnable() {
                @Override
                public void run() {
                  try {
                    barrier.await();
                    while (num == 0 || leaderRunning.get()) {
                      proxy.slowPing(false);
                    }

                    proxy.slowPing(false);
                  } catch (Exception e) {
                    if (num == 0) {
                      leaderRunning.set(false);
                    } else {
                      error.set(e);
                    }

                    LOG.error(e);
                  } finally {
                    latch.countDown();
                  }
                }
              });
      rpcThread.start();

      if (leaderThread == null) {
        leaderThread = rpcThread;
      }
    }
    // let threads get past the barrier
    Thread.sleep(1000);
    // stop a single thread
    while (leaderRunning.get()) {
      leaderThread.interrupt();
    }

    latch.await();

    // should not cause any other thread to get an error
    assertTrue("rpc got exception " + error.get(), error.get() == null);
  }
コード例 #30
0
ファイル: ServerFactory.java プロジェクト: rucky2013/godzilla
 static {
   server = new Server(RpcUtil.getRpcPort(), 8);
   server.start();
 }