コード例 #1
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();
    }
  }
コード例 #2
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);
      server.stop();
    }
  }
コード例 #3
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();
  }
コード例 #4
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);
      }
    }
  }
コード例 #5
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);
      }
    }
  }
コード例 #6
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);
  }
コード例 #7
0
  @Test
  public void testConfRpc() throws IOException {
    Server server =
        new RPC.Builder(conf)
            .setProtocol(TestProtocol.class)
            .setInstance(new TestImpl())
            .setBindAddress(ADDRESS)
            .setPort(0)
            .setNumHandlers(1)
            .setVerbose(false)
            .build();
    // Just one handler
    int confQ =
        conf.getInt(
            CommonConfigurationKeys.IPC_SERVER_HANDLER_QUEUE_SIZE_KEY,
            CommonConfigurationKeys.IPC_SERVER_HANDLER_QUEUE_SIZE_DEFAULT);
    assertEquals(confQ, server.getMaxQueueSize());

    int confReaders =
        conf.getInt(
            CommonConfigurationKeys.IPC_SERVER_RPC_READ_THREADS_KEY,
            CommonConfigurationKeys.IPC_SERVER_RPC_READ_THREADS_DEFAULT);
    assertEquals(confReaders, server.getNumReaders());
    server.stop();

    server =
        new RPC.Builder(conf)
            .setProtocol(TestProtocol.class)
            .setInstance(new TestImpl())
            .setBindAddress(ADDRESS)
            .setPort(0)
            .setNumHandlers(1)
            .setnumReaders(3)
            .setQueueSizePerHandler(200)
            .setVerbose(false)
            .build();

    assertEquals(3, server.getNumReaders());
    assertEquals(200, server.getMaxQueueSize());
    server.stop();
  }
コード例 #8
0
ファイル: ServerGUI.java プロジェクト: Hlidskjalf/Java-chat
  public void windowClosing(WindowEvent e) {
    if (server != null) {
      try {
        server.stop();
      } catch (Exception eClose) {
      }
      server = null;
    }

    dispose();
    System.exit(0);
  }
コード例 #9
0
  @Test
  public void session() throws Exception {
    Client c = new Client();

    Server<Object> s = new Server<Object>(TEST_AUTHENTICATOR, TEST_MANAGER);
    assertEquals(TEST_AUTHENTICATOR, s.getAuthenticator());

    try {
      c.assertValidSession();
      fail();
    } catch (I18NException ex) {
      assertEquals(Messages.NOT_LOGGED_IN, ex.getI18NBoundMessage());
    }

    c.login(TEST_USER, TEST_PASSWORD);
    SessionId id = c.getSessionId();
    assertNotNull(id);
    assertEquals(id, c.getContext().getSessionId());
    assertEquals(TEST_USER, TEST_MANAGER.get(id).getUser());

    try {
      c.login(TEST_USER, TEST_PASSWORD);
      fail();
    } catch (I18NException ex) {
      assertEquals(Messages.ALREADY_LOGGED_IN, ex.getI18NBoundMessage());
    }

    assertEquals(id, c.getSessionId());
    assertEquals(TEST_USER, TEST_MANAGER.get(id).getUser());

    c.logout();
    assertNull(c.getSessionId());
    assertNull(c.getContext().getSessionId());
    assertNull(TEST_MANAGER.get(id));

    try {
      c.login(TEST_USER_D, TEST_PASSWORD);
      fail();
    } catch (RemoteException ex) {
      assertEquals(Messages.BAD_CREDENTIALS, ((I18NException) ex.getCause()).getI18NBoundMessage());
    }
    assertNull(c.getSessionId());

    c.logout();

    s.stop();
    try {
      c.login(TEST_USER, TEST_PASSWORD);
      fail();
    } catch (WebServiceException ex) {
      // Desired.
    }
  }
コード例 #10
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");
    }
  }
コード例 #11
0
 /*
  * If the user click the X button to close the application
  * I need to close the connection with the server to free the port
  */
 public void windowClosing(WindowEvent e) {
   // if my Server exist
   if (server != null) {
     try {
       server.stop(); // ask the server to close the conection
     } catch (Exception eClose) {
     }
     server = null;
   }
   // dispose the frame
   dispose();
   System.exit(0);
 }
コード例 #12
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);
    }
  }
コード例 #13
0
  public void actionPerformed(ActionEvent e) {

    // if running we have to stop

    if (server != null) {

      server.stop();

      server = null;

      tPortNumber.setEditable(true);

      stopStart.setText("Start");

      return;
    }

    // OK start the server

    int port;

    try {

      port = Integer.parseInt(tPortNumber.getText().trim());

    } catch (Exception er) {

      appendEvent("Invalid port number");

      return;
    }

    // ceate a new Server

    server = new Server(port, this);

    // and start it as a thread

    new ServerRunning().start();

    stopStart.setText("Stop");

    tPortNumber.setEditable(false);
  }
コード例 #14
0
 @Test
 public void testServerAddress() throws IOException {
   Server server =
       new RPC.Builder(conf)
           .setProtocol(TestProtocol.class)
           .setInstance(new TestImpl())
           .setBindAddress(ADDRESS)
           .setPort(0)
           .setNumHandlers(5)
           .setVerbose(true)
           .build();
   InetSocketAddress bindAddr = null;
   try {
     bindAddr = NetUtils.getConnectAddress(server);
   } finally {
     server.stop();
   }
   assertEquals(bindAddr.getAddress(), InetAddress.getLocalHost());
 }
コード例 #15
0
ファイル: ServerGUI.java プロジェクト: Hlidskjalf/Java-chat
  public void actionPerformed(ActionEvent e) {
    if (server != null) {
      server.stop();
      server = null;
      tPortNumber.setEditable(true);
      stopStart.setText("Start");
      return;
    }

    int port;
    try {
      port = Integer.parseInt(tPortNumber.getText().trim());
    } catch (Exception er) {
      appendEvent("Invalid port number.");
      return;
    }

    server = new Server(port, this);
    new ServerRunning().start();
    stopStart.setText("Stop");
    tPortNumber.setEditable(false);
  }
コード例 #16
0
  /**
   * {@inheritDoc}
   *
   * @see
   *     com.continuent.tungsten.replicator.plugin.ReplicatorPlugin#release(com.continuent.tungsten.replicator.plugin.PluginContext)
   */
  public synchronized void release(PluginContext context)
      throws InterruptedException, ReplicatorException {
    // Cancel server.
    if (server != null) {
      try {
        server.stop();
      } catch (InterruptedException e) {
        logger.warn("Server stop operation was unexpectedly interrupted", e);
      } finally {
        server = null;
      }
    }

    if (catalog != null) {
      catalog.close();
      catalog = null;
    }
    if (diskLog != null) {
      diskLog.release();
      diskLog = null;
    }
  }
コード例 #17
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();
   }
 }
コード例 #18
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);
  }
コード例 #19
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);
    }
  }
コード例 #20
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();
          }
        }
コード例 #21
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);
        }
    }
コード例 #22
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();
    }
  }
コード例 #23
0
  @Test(timeout = 30000)
  public void testRPCInterrupted() throws IOException, InterruptedException {
    final Configuration conf = new Configuration();
    Server server =
        RPC.getServer(TestProtocol.class, new TestImpl(), ADDRESS, 0, 5, true, conf, null);

    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);
    server.stop();
  }
コード例 #24
0
  public void run(int selfId) {
    long initTime, lastRoundTime;
    BufferedWriter out = null;

    if (selfId != 0) // The node is a peer
    {
      try {
        if (OUTPUT) {
          out = new BufferedWriter(new FileWriter(selfId + "_nbDeletedUpdates.txt"));
          out.write(peer.selfId + " " + RTE + " " + UPDATES_PER_ROUND + "\n");
        }

        long currentTimeMillis = System.currentTimeMillis();
        long nextMinuteMillis = (1 + currentTimeMillis / 60000) * (60000);

        try {
          sleepAtLeast(nextMinuteMillis - currentTimeMillis);
        } catch (InterruptedException e) {
        }

        System.out.println("Session starts NOW");

        // Count new rounds until time limit
        initTime = System.currentTimeMillis() / 1000;
        while (System.currentTimeMillis() / 1000 - initTime < SESSION_DURATION) {

          // If the duration of one round passed, treat a new round
          lastRoundTime = System.currentTimeMillis() / 1000;

          // Trigger periodical messages of peer
          peer.newRound();

          // Wait until the end of round
          while (System.currentTimeMillis() / 1000 - lastRoundTime < ROUND_DURATION)
            peer.treatInMessage();

          // End of round: increase the round ID, update the log, and consume received updates
          int[] results = peer.endOfRound();
          if (OUTPUT)
            out.write(
                peer.getRoundId()
                    + " "
                    + results[0]
                    + " "
                    + results[1]
                    + "\n"); // roundId, nodeStatus, nbDeletedUpdates
        }

        if (OUTPUT) out.close();

        peer.sender.mustStop = true;
        peer.receiver.mustStop = true;
        if (OUTPUT) {
          try {
            peer.outLog.close();
          } catch (IOException e1) {
            e1.printStackTrace();
          }
        }

      } catch (IOException e) {
        e.printStackTrace();
      }

    } else // The node is the broadcaster
    {
      long currentTimeMillis = System.currentTimeMillis();
      long nextMinuteMillis = (1 + currentTimeMillis / 60000) * (60000);

      try {
        sleepAtLeast(nextMinuteMillis - currentTimeMillis);
      } catch (InterruptedException e) {
      }

      System.out.println("Session starts NOW");

      // Count new rounds until time limit
      initTime = System.currentTimeMillis() / 1000;

      // If the duration of one round passed, treat a new round
      while (System.currentTimeMillis() / 1000 - initTime < SESSION_DURATION) {
        lastRoundTime = System.currentTimeMillis() / 1000;

        // Trigger periodical messages of peer
        server.newRound();

        // Wait until the end of round
        while (System.currentTimeMillis() / 1000 - lastRoundTime < ROUND_DURATION)
          server.treatInMessage();
      }

      server.stop();

      int nbrServeRounds =
          server.getNbServeRounds()
              - RTE; // The subtraction is related to the final rounds, for which updates cannot
                     // expire
      if (OUTPUT) {
        try {
          out = new BufferedWriter(new FileWriter("0_nbrSentUpdates.txt"));
          out.write(nbrServeRounds + "\n");
          out.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }
コード例 #25
0
ファイル: TestRPC.java プロジェクト: thaingo/hadoop-20-append
  public void testCalls() throws Exception {
    Server server = RPC.getServer(new TestImpl(), ADDRESS, 0, conf);
    TestProtocol proxy = null;
    try {
      server.start();

      InetSocketAddress addr = NetUtils.getConnectAddress(server);
      proxy = (TestProtocol) 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);

      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);

      boolean caught = false;
      try {
        proxy.error();
      } catch (IOException e) {
        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
        }
      }

      // try some multi-calls
      Method echo = TestProtocol.class.getMethod("echo", new Class[] {String.class});
      String[] strings =
          (String[])
              RPC.call(
                  echo, new String[][] {{"a"}, {"b"}}, new InetSocketAddress[] {addr, addr}, conf);
      assertTrue(Arrays.equals(strings, new String[] {"a", "b"}));

      Method ping = TestProtocol.class.getMethod("ping", new Class[] {});
      Object[] voids =
          (Object[])
              RPC.call(ping, new Object[][] {{}, {}}, new InetSocketAddress[] {addr, addr}, conf);
      assertEquals(voids, null);
    } finally {
      server.stop();
      if (proxy != null) RPC.stopProxy(proxy);
    }
  }