示例#1
0
  public static void main(String[] args) throws Exception {
    ExecutorService exec = Executors.newCachedThreadPool();
    for (int i = 0; i < 5; i++) exec.execute(new Task());
    exec.execute(new Task2());
    Timer timer = new Timer();
    timer.scheduleAtFixedRate(
        new TimerTask() {
          boolean prod = true;

          public void run() {
            if (prod) {
              System.out.print("\nnotify() ");
              Task.blocker.prod();
              prod = false;
            } else {
              System.out.print("\nnotifyAll() ");
              Task.blocker.prodAll();
              prod = true;
            }
          }
        },
        400,
        400); // Run every .4 second
    TimeUnit.SECONDS.sleep(5); // Run for a while...
    timer.cancel();
    System.out.println("\nTimer canceled");
    TimeUnit.MILLISECONDS.sleep(500);
    System.out.print("Task2.blocker.prodAll() ");
    Task2.blocker.prodAll();
    TimeUnit.MILLISECONDS.sleep(500);
    System.out.println("\nShutting down");
    exec.shutdownNow(); // Interrupt all tasks
  }
 public static void main(String[] args) throws Exception {
   ToastQueue dryQueue = new ToastQueue(),
       butteredQueue = new ToastQueue(),
       finishedQueue = new ToastQueue();
   ExecutorService exec = Executors.newCachedThreadPool();
   exec.execute(new Toaster(dryQueue));
   exec.execute(new Butterer(dryQueue, butteredQueue));
   exec.execute(new Jammer(butteredQueue, finishedQueue));
   exec.execute(new Eater(finishedQueue));
   TimeUnit.SECONDS.sleep(5);
   exec.shutdownNow();
 }
示例#3
0
 public static void main(String[] args) throws Exception {
   if (args.length > 0) size = new Integer(args[0]);
   if (args.length > 1) delay = new Integer(args[1]);
   ExecutorService exec = Executors.newCachedThreadPool();
   Exchanger<List<Fat>> xc = new Exchanger<List<Fat>>();
   List<Fat> producerList = new CopyOnWriteArrayList<Fat>(),
       consumerList = new CopyOnWriteArrayList<Fat>();
   exec.execute(new ExchangerProducer<Fat>(xc, BasicGenerator.create(Fat.class), producerList));
   exec.execute(new ExchangerConsumer<Fat>(xc, consumerList));
   TimeUnit.SECONDS.sleep(delay);
   exec.shutdownNow();
 }
 public Restaurant(ExecutorService e, int nWaitPersons, int nChefs) {
   exec = e;
   for (int i = 0; i < nWaitPersons; i++) {
     WaitPerson waitPerson = new WaitPerson(this);
     waitPersons.add(waitPerson);
     exec.execute(waitPerson);
   }
   for (int i = 0; i < nChefs; i++) {
     Chef chef = new Chef(this);
     chefs.add(chef);
     exec.execute(chef);
   }
 }
 public static void main(String[] args) throws Exception {
   ExecutorService exec = Executors.newCachedThreadPool();
   // If line is too long, customers will leave:
   CustomerLine customers = new CustomerLine(MAX_LINE_SIZE);
   exec.execute(new CustomerGenerator(customers));
   // Manager will add and remove tellers as necessary:
   exec.execute(new TellerManager(exec, customers, ADJUSTMENT_PERIOD));
   if (args.length > 0) // Optional argument
   TimeUnit.SECONDS.sleep(new Integer(args[0]));
   else {
     System.out.println("Press ‘Enter’ to quit");
     System.in.read();
   }
   exec.shutdownNow();
 }
 public void adjustTellerNumber() {
   // This is actually a control system. By adjusting
   // the numbers, you can reveal stability issues in
   // the control mechanism.
   // If line is too long, add another teller:
   if (customers.size() / workingTellers.size() > 2) {
     // If tellers are on break or doing
     // another job, bring one back:
     if (tellersDoingOtherThings.size() > 0) {
       Teller teller = tellersDoingOtherThings.remove();
       teller.serveCustomerLine();
       workingTellers.offer(teller);
       return;
     }
     // Else create (hire) a new teller
     Teller teller = new Teller(customers);
     exec.execute(teller);
     workingTellers.add(teller);
     return;
   }
   // If line is short enough, remove a teller:
   if (workingTellers.size() > 1 && customers.size() / workingTellers.size() < 2)
     reassignOneTeller();
   // If there is no line, we only need one teller:
   if (customers.size() == 0) while (workingTellers.size() > 1) reassignOneTeller();
 }
 /**
  * Executes the specified runnable on the worker thread of the view. Execution is performed
  * sequentially in the same sequence as the runnables have been passed to this method.
  */
 @Override
 public void execute(Runnable worker) {
   if (executor == null) {
     executor = Executors.newSingleThreadExecutor();
   }
   executor.execute(worker);
 }
  /** {@inheritDoc} */
  @Override
  protected void maybeStartStream() throws IOException {
    // connector
    final StreamConnector connector = getStreamConnector();

    if (connector == null) return;

    synchronized (this) {
      if (started) return;

      threadPool.execute(
          new Runnable() {
            @Override
            public void run() {
              try {
                Sctp.init();

                runOnDtlsTransport(connector);
              } catch (IOException e) {
                logger.error(e, e);
              } finally {
                try {
                  Sctp.finish();
                } catch (IOException e) {
                  logger.error("Failed to shutdown SCTP stack", e);
                }
              }
            }
          });

      started = true;
    }
  }
 public static void main(String[] args) throws Exception {
   ExecutorService exec = Executors.newCachedThreadPool();
   for (int i = 0; i < N_ELEMENTS; i++)
     for (int j = 0; j < N_GENES; j++) GRID[i][j] = new AtomicInteger(rand.nextInt(1000));
   for (int i = 0; i < N_EVOLVERS; i++) exec.execute(new Evolver());
   TimeUnit.SECONDS.sleep(5);
   exec.shutdownNow();
 }
 public TellerManager(ExecutorService e, CustomerLine customers, int adjustmentPeriod) {
   exec = e;
   this.customers = customers;
   this.adjustmentPeriod = adjustmentPeriod;
   // Start with a single teller:
   Teller teller = new Teller(customers);
   exec.execute(teller);
   workingTellers.add(teller);
 }
示例#11
0
  public static void start() {
    if (started) return;

    // start code
    pool = Executors.newFixedThreadPool(poolSize);
    System.out.println("downloader start!!");
    for (DownloadTask task : tasks) pool.execute(task);
    started = true;
  }
  /*
      Use this version for fire and forget style messaging.
  */
  public void sendOneWay(Message message, EndPoint to) {
    // do local deliveries
    if (message.getFrom().equals(to)) {
      MessagingService.receive(message);
      return;
    }

    Runnable tcpWriteEvent = new MessageSerializationTask(message, to);
    messageSerializerExecutor_.execute(tcpWriteEvent);
  }
示例#13
0
 public static void main(String[] args) {
   Random rand = new Random(47);
   ExecutorService exec = Executors.newCachedThreadPool();
   DelayQueue<DelayedTask> queue = new DelayQueue<DelayedTask>();
   // Fill with tasks that have random delays:
   for (int i = 0; i < 20; i++) queue.put(new DelayedTask(rand.nextInt(5000)));
   // Set the stopping point
   queue.add(new DelayedTask.EndSentinel(5000, exec));
   exec.execute(new DelayedTaskConsumer(queue));
 }
 public static void main(String[] args) throws Exception {
   ExecutorService exec = Executors.newCachedThreadPool();
   Restaurant restaurant = new Restaurant(exec, 5, 2);
   exec.execute(restaurant);
   if (args.length > 0) // Optional argument
   TimeUnit.SECONDS.sleep(new Integer(args[0]));
   else {
     print("Press ‘Enter’ to quit");
     System.in.read();
   }
   exec.shutdownNow();
 }
  private static void enqueueRunnable(String stageName, Runnable runnable) {

    IStage stage = StageManager.getStage(stageName);

    if (stage != null) {
      logger_.info("Running on stage " + stage.getName());
      stage.execute(runnable);
    } else {
      logger_.info("Running on default stage - beware");
      messageSerializerExecutor_.execute(runnable);
    }
  }
 public void start() {
   while (statementIterator.hasNext()) {
     final CQLStatement next = statementIterator.next();
     Runnable r =
         new Runnable() {
           @Override
           public void run() {
             handle(next);
           }
         };
     executorService.execute(r);
   }
 }
 public void run() {
   try {
     while (!Thread.interrupted()) {
       // A new customer arrives; assign a WaitPerson:
       WaitPerson wp = waitPersons.get(rand.nextInt(waitPersons.size()));
       Customer c = new Customer(wp);
       exec.execute(c);
       TimeUnit.MILLISECONDS.sleep(100);
     }
   } catch (InterruptedException e) {
     print("Restaurant interrupted");
   }
   print("Restaurant closing");
 }
示例#18
0
  public static void execute(Collection<? extends Runnable> tasks, long waitingTimeInMillis) {
    ExecutorService executor = Executors.newFixedThreadPool(tasks.size());

    for (Runnable task : tasks) {
      executor.execute(task);
    }

    try {
      executor.awaitTermination(waitingTimeInMillis, TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
      throw new RuntimeException(e);
    } finally {
      executor.shutdown();
    }
  }
示例#19
0
 @Override
 public synchronized Receptor<T> takeReceptor() {
   if (!freeReceptors.isEmpty()) {
     ReceptorImpl impl = (ReceptorImpl) freeReceptors.remove(0);
     impl.skips = 0;
     return impl;
   }
   int length = inputs.length() + 1;
   final AtomicReferenceArray<T> inputs = new AtomicReferenceArray<>(length);
   this.inputs = inputs;
   final List<ReceptorImpl> newReuseReceptors = new ArrayList<>(length);
   for (int i = 0; i < length; i++) {
     newReuseReceptors.add(new ReceptorImpl(i));
   }
   executor.execute(
       () -> {
         long lastTime = System.currentTimeMillis();
         try {
           boolean empty = false;
           while (!empty && started) {
             empty = true;
             for (int i = 0; i < outputs.length(); i++) {
               T result = outputs.get(i);
               if (result == null) continue;
               Thread.sleep(1);
               empty = false;
               if (lastTime + 30_000 < System.currentTimeMillis()) {
                 lastTime = System.currentTimeMillis();
                 logger.error(
                     "unable to set receptors for " + producer + " i=" + i + " result=" + result);
                 if (pool != null) logger.warn("pool=" + pool.producer);
               }
               break;
             }
           }
         } catch (InterruptedException e) {
           logger.warn("takeReceptor", e);
         } finally {
           reuseReceptors = newReuseReceptors;
           outputs = inputs;
         }
       });
   return new ReceptorImpl(length - 1);
 }
示例#20
0
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // get the number of workers to run
    int count = this.getRequestedCount(request, 4);
    // get the executor service
    final ServletContext sc = this.getServletContext();
    final ExecutorService executorService = (ExecutorService) sc.getAttribute("myExecutorService");
    // create work coordinator
    CountDownLatch countDownLatch = new CountDownLatch(count);

    Long t1 = System.nanoTime();
    // create the workers
    List<RunnableWorkUnit2> workers = new ArrayList<RunnableWorkUnit2>();
    for (int i = 0; i < count; i++) {
      RunnableWorkUnit2 wu =
          new RunnableWorkUnit2("RunnableTask" + String.valueOf(i + 1), countDownLatch);
      workers.add(wu);
    }
    // run the workers through the executor
    for (RunnableWorkUnit2 wu : workers) {
      executorService.execute(wu);
    }

    try {
      System.out.println("START WAITING");
      countDownLatch.await();
      System.out.println("DONE WAITING");
    } catch (InterruptedException ex) {
      ex.printStackTrace();
    }

    Long t2 = System.nanoTime();
    Writer w = response.getWriter();
    w.write(String.format("\n Request processed in %dms!", (t2 - t1) / 1000000));
    w.flush();
    w.close();
  }
示例#21
0
  public static void performTest(final Map<String, Integer> m) throws Exception {

    out.println("Test started for: " + m.getClass());
    long avgTime = 0;
    for (int i = 0; i < 5; i++) {

      long startTime = System.nanoTime();
      ExecutorService exService = Executors.newFixedThreadPool(POOL_SIZE);

      for (int j = 0; j < POOL_SIZE; j++) {
        exService.execute(
            new Runnable() {
              @SuppressWarnings("unused")
              public void run() {
                for (int i = 0; i < 500000; i++) {
                  Integer randomNum = (int) Math.ceil(Math.random() * 550000);
                  // Retrieve value. We are not using it anywhere
                  Integer value = m.get(String.valueOf(randomNum));
                  // Put value
                  m.put(String.valueOf(randomNum), randomNum);
                }
              }
            });
      }

      // Make sure executor stops
      exService.shutdown();
      // Blocks until all tasks have completed execution after a shutdown request
      exService.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);

      long entTime = System.nanoTime();
      long totalTime = (entTime - startTime) / 1000000L;
      avgTime += totalTime;
      out.println("500K entried added/retrieved in " + totalTime + " ms");
    }
    out.println("For " + m.getClass() + " the average time is " + avgTime / 5 + " ms\n");
  }
  /**
   * Sets the simulcast layers for this receiver and fires an event about it.
   *
   * @param simulcastLayers the simulcast layers for this receiver.
   */
  public void setSimulcastLayers(SimulcastLayer[] simulcastLayers) {
    this.simulcastLayers = simulcastLayers;

    if (logger.isInfoEnabled()) {
      if (simulcastLayers == null) {
        logInfo("Simulcast disabled.");
      } else {
        for (SimulcastLayer l : simulcastLayers) {
          logInfo(l.getOrder() + ": " + l.getPrimarySSRC());
        }
      }
    }

    executorService.execute(
        new Runnable() {
          public void run() {
            firePropertyChange(SIMULCAST_LAYERS_PNAME, null, null);
          }
        });

    // TODO If simulcastLayers has changed, then simulcastLayerFrameHistory
    // has very likely become irrelevant. In other words, clear
    // simulcastLayerFrameHistory.
  }
示例#23
0
 public static void main(String[] args) throws Exception {
   try {
     lock = new Object();
     if (args.length > 0) {
       NUM = Integer.parseInt(args[0]);
     }
     execs = Executors.newFixedThreadPool(5);
     httpServer = createHttpServer(execs);
     port = httpServer.getAddress().getPort();
     pool = Executors.newFixedThreadPool(10);
     httpServer.start();
     for (int i = 0; i < NUM; i++) {
       pool.execute(new Client());
       if (error) {
         throw new Exception("error in test");
       }
     }
     System.out.println("Main thread waiting");
     pool.shutdown();
     long latest = System.currentTimeMillis() + 200 * 1000;
     while (System.currentTimeMillis() < latest) {
       if (pool.awaitTermination(2000L, TimeUnit.MILLISECONDS)) {
         System.out.println("Main thread done!");
         return;
       }
       if (error) {
         throw new Exception("error in test");
       }
     }
     throw new Exception("error in test: timed out");
   } finally {
     httpServer.stop(0);
     pool.shutdownNow();
     execs.shutdownNow();
   }
 }
 @Test
 public void putAndget100000RecordsWith1ClusterMemberFrom10Threads() throws InterruptedException {
   HazelcastClient hClient = getHazelcastClient();
   final Map<String, String> map =
       hClient.getMap("putAndget100000RecordsWith1ClusterMemberFrom10Threads");
   int count = 100000;
   int threads = 16;
   final AtomicInteger getCounter = new AtomicInteger(count);
   final AtomicInteger putCounter = new AtomicInteger(count);
   ExecutorService executorService = Executors.newFixedThreadPool(threads);
   final long beginTime = Clock.currentTimeMillis();
   final CountDownLatch latch = new CountDownLatch(threads);
   for (int i = 0; i < threads; i++) {
     executorService.execute(
         new Runnable() {
           public void run() {
             int i;
             while ((i = putCounter.getAndDecrement()) > 0) {
               map.put("key_" + i, String.valueOf(i));
             }
             while ((i = getCounter.getAndDecrement()) > 0) {
               map.get("key_" + i);
             }
             latch.countDown();
           }
         });
   }
   latch.await();
   System.out.println(
       threads
           + " Threads made in total "
           + count
           + " puts and gets in "
           + (Clock.currentTimeMillis() - beginTime)
           + " ms");
 }
示例#25
0
  public void connect() {
    service.execute(
        new Runnable() {
          @Override
          public void run() {
            MinecraftBotData.Builder builder = MinecraftBotData.builder();
            builder.username(data.username).password(data.password);

            String server = data.server;
            int port = 25565;
            if (server.contains(":")) {
              String[] parts = server.split(":");
              server = parts[0];
              port = Integer.parseInt(parts[1]);
            }
            builder.server(server).port(port);

            if (data.proxy != null) {
              String proxy = data.proxy;
              int proxyPort;
              ProxyType type = null;
              if (proxy.contains(":")) {
                String[] parts = proxy.split(":");
                proxy = parts[0];
                proxyPort = Integer.parseInt(parts[1]);
                if (parts.length > 2) {
                  try {
                    type = ProxyType.values()[Integer.parseInt(parts[2])];
                  } catch (NumberFormatException exception) {
                    type = ProxyType.valueOf(parts[2].toUpperCase());
                  }
                }
              } else throw new IllegalArgumentException("Invalid proxy");
              ProxyData data =
                  new ProxyData(proxy, proxyPort, type == null ? ProxyType.SOCKS : type);
              builder.socksProxy(data);
            }
            MinecraftBotData botData = builder.build();

            clearLog();
            log("[BOT] Connecting...");
            status("Connecting...");
            progress(true);
            try {
              bot = new MinecraftBot(GUIBotWrapper.getInstance().getDarkBot(), botData);
            } catch (Exception exception) {
              exception.printStackTrace();

              Throwable cause = exception.getCause();
              if (cause != null && cause instanceof AuthenticationException) {
                log("[BOT] Error: Invalid login (" + cause.getMessage() + ")");
              } else {
                log("[BOT] Error: Unable to connect (" + exception.toString() + ")");
              }
              status("Waiting.");
              progress(false);
              return;
            }
            progress(20, false);
            status("Logging in...");
            bot.getEventManager().registerListener(RegularBot.this);
            TaskManager taskManager = bot.getTaskManager();
            for (Class<? extends Task> task : data.tasks) {
              try {
                Constructor<? extends Task> constructor = task.getConstructor(MinecraftBot.class);
                taskManager.registerTask(constructor.newInstance(bot));
              } catch (Exception exception) {
              }
            }
          }
        });
  }
示例#26
0
 private void handleFailedDownload(DownloadStatus status, DownloadRequest request) {
   if (BuildConfig.DEBUG) Log.d(TAG, "Handling failed download");
   syncExecutor.execute(new FailedDownloadHandler(status, request));
 }
示例#27
0
 /** Is called whenever a FeedMedia is downloaded. */
 private void handleCompletedFeedMediaDownload(DownloadStatus status, DownloadRequest request) {
   if (BuildConfig.DEBUG) Log.d(TAG, "Handling completed FeedMedia Download");
   syncExecutor.execute(new MediaHandlerThread(status, request));
 }
  private void runOnDtlsTransport(StreamConnector connector) throws IOException {
    DtlsControlImpl dtlsControl = (DtlsControlImpl) getTransportManager().getDtlsControl(this);
    DtlsTransformEngine engine = dtlsControl.getTransformEngine();
    final DtlsPacketTransformer transformer = (DtlsPacketTransformer) engine.getRTPTransformer();

    byte[] receiveBuffer = new byte[SCTP_BUFFER_SIZE];

    if (LOG_SCTP_PACKETS) {
      System.setProperty(
          ConfigurationService.PNAME_SC_HOME_DIR_LOCATION, System.getProperty("java.io.tmpdir"));
      System.setProperty(
          ConfigurationService.PNAME_SC_HOME_DIR_NAME, SctpConnection.class.getName());
    }

    synchronized (this) {
      // FIXME local SCTP port is hardcoded in bridge offer SDP (Jitsi
      // Meet)
      sctpSocket = Sctp.createSocket(5000);
      assocIsUp = false;
      acceptedIncomingConnection = false;
    }

    // Implement output network link for SCTP stack on DTLS transport
    sctpSocket.setLink(
        new NetworkLink() {
          @Override
          public void onConnOut(SctpSocket s, byte[] packet) throws IOException {
            if (LOG_SCTP_PACKETS) {
              LibJitsi.getPacketLoggingService()
                  .logPacket(
                      PacketLoggingService.ProtocolName.ICE4J,
                      new byte[] {0, 0, 0, (byte) debugId},
                      5000,
                      new byte[] {0, 0, 0, (byte) (debugId + 1)},
                      remoteSctpPort,
                      PacketLoggingService.TransportName.UDP,
                      true,
                      packet);
            }

            // Send through DTLS transport
            transformer.sendApplicationData(packet, 0, packet.length);
          }
        });

    if (logger.isDebugEnabled()) {
      logger.debug("Connecting SCTP to port: " + remoteSctpPort + " to " + getEndpoint().getID());
    }

    sctpSocket.setNotificationListener(this);
    sctpSocket.listen();

    // FIXME manage threads
    threadPool.execute(
        new Runnable() {
          @Override
          public void run() {
            SctpSocket sctpSocket = null;
            try {
              // sctpSocket is set to null on close
              sctpSocket = SctpConnection.this.sctpSocket;
              while (sctpSocket != null) {
                if (sctpSocket.accept()) {
                  acceptedIncomingConnection = true;
                  break;
                }
                Thread.sleep(100);
                sctpSocket = SctpConnection.this.sctpSocket;
              }
              if (isReady()) {
                notifySctpConnectionReady();
              }
            } catch (Exception e) {
              logger.error("Error accepting SCTP connection", e);
            }

            if (sctpSocket == null && logger.isInfoEnabled()) {
              logger.info(
                  "SctpConnection " + getID() + " closed" + " before SctpSocket accept()-ed.");
            }
          }
        });

    // Notify that from now on SCTP connection is considered functional
    sctpSocket.setDataCallback(this);

    // Setup iceSocket
    DatagramSocket datagramSocket = connector.getDataSocket();
    if (datagramSocket != null) {
      this.iceSocket = new IceUdpSocketWrapper(datagramSocket);
    } else {
      this.iceSocket = new IceTcpSocketWrapper(connector.getDataTCPSocket());
    }

    DatagramPacket rcvPacket = new DatagramPacket(receiveBuffer, 0, receiveBuffer.length);

    // Receive loop, breaks when SCTP socket is closed
    try {
      do {
        iceSocket.receive(rcvPacket);

        RawPacket raw =
            new RawPacket(rcvPacket.getData(), rcvPacket.getOffset(), rcvPacket.getLength());

        raw = transformer.reverseTransform(raw);
        // Check for app data
        if (raw == null) continue;

        if (LOG_SCTP_PACKETS) {
          LibJitsi.getPacketLoggingService()
              .logPacket(
                  PacketLoggingService.ProtocolName.ICE4J,
                  new byte[] {0, 0, 0, (byte) (debugId + 1)},
                  remoteSctpPort,
                  new byte[] {0, 0, 0, (byte) debugId},
                  5000,
                  PacketLoggingService.TransportName.UDP,
                  false,
                  raw.getBuffer(),
                  raw.getOffset(),
                  raw.getLength());
        }

        // Pass network packet to SCTP stack
        sctpSocket.onConnIn(raw.getBuffer(), raw.getOffset(), raw.getLength());
      } while (true);
    } finally {
      // Eventually, close the socket although it should happen from
      // expire().
      synchronized (this) {
        assocIsUp = false;
        acceptedIncomingConnection = false;
        if (sctpSocket != null) {
          sctpSocket.close();
          sctpSocket = null;
        }
      }
    }
  }
  public static void main(String[] args) {
    // TODO main
    OptionParser parser = new OptionParser();
    parser.acceptsAll(Arrays.asList("h", "help"), "Show this help dialog.");
    OptionSpec<String> serverOption =
        parser
            .acceptsAll(Arrays.asList("s", "server"), "Server to join.")
            .withRequiredArg()
            .describedAs("server-address[:port]");
    OptionSpec<String> proxyOption =
        parser
            .acceptsAll(
                Arrays.asList("P", "proxy"),
                "SOCKS proxy to use. Ignored in presence of 'socks-proxy-list'.")
            .withRequiredArg()
            .describedAs("proxy-address");
    OptionSpec<String> ownerOption =
        parser
            .acceptsAll(
                Arrays.asList("o", "owner"), "Owner of the bot (username of in-game control).")
            .withRequiredArg()
            .describedAs("username");
    OptionSpec<?> offlineOption =
        parser.acceptsAll(
            Arrays.asList("O", "offline"),
            "Offline-mode. Ignores 'password' and 'account-list' (will "
                + "generate random usernames if 'username' is not supplied).");
    OptionSpec<?> autoRejoinOption =
        parser.acceptsAll(Arrays.asList("a", "auto-rejoin"), "Auto-rejoin a server on disconnect.");
    OptionSpec<Integer> loginDelayOption =
        parser
            .acceptsAll(
                Arrays.asList("d", "login-delay"),
                "Delay between bot joins, in milliseconds. 5000 is "
                    + "recommended if not using socks proxies.")
            .withRequiredArg()
            .describedAs("delay")
            .ofType(Integer.class);
    OptionSpec<Integer> botAmountOption =
        parser
            .acceptsAll(
                Arrays.asList("b", "bot-amount"),
                "Amount of bots to join. Must be <= amount of accounts.")
            .withRequiredArg()
            .describedAs("amount")
            .ofType(Integer.class);

    OptionSpec<String> accountListOption =
        parser
            .accepts(
                "account-list",
                "File containing a list of accounts, in username/email:password format.")
            .withRequiredArg()
            .describedAs("file");
    OptionSpec<String> socksProxyListOption =
        parser
            .accepts(
                "socks-proxy-list",
                "File containing a list of SOCKS proxies, in address:port format.")
            .withRequiredArg()
            .describedAs("file");
    OptionSpec<String> httpProxyListOption =
        parser
            .accepts(
                "http-proxy-list",
                "File containing a list of HTTP proxies, in address:port format.")
            .withRequiredArg()
            .describedAs("file");

    OptionSet options;
    try {
      options = parser.parse(args);
    } catch (OptionException exception) {
      try {
        parser.printHelpOn(System.out);
      } catch (Exception exception1) {
        exception1.printStackTrace();
      }
      return;
    }

    if (options.has("help")) {
      printHelp(parser);
      return;
    }

    final boolean offline = options.has(offlineOption);
    final boolean autoRejoin = options.has(autoRejoinOption);

    final List<String> accounts;
    if (options.has(accountListOption)) {
      accounts = loadAccounts(options.valueOf(accountListOption));
    } else if (!offline) {
      System.out.println("Option 'accounts' must be supplied in " + "absence of option 'offline'.");
      printHelp(parser);
      return;
    } else accounts = null;

    final String server;
    if (!options.has(serverOption)) {
      System.out.println("Option 'server' required.");
      printHelp(parser);
      return;
    } else server = options.valueOf(serverOption);

    final String owner;
    if (!options.has(ownerOption)) {
      System.out.println("Option 'owner' required.");
      printHelp(parser);
      return;
    } else owner = options.valueOf(ownerOption);

    final List<String> socksProxies;
    if (options.has(socksProxyListOption))
      socksProxies = loadProxies(options.valueOf(socksProxyListOption));
    else socksProxies = null;
    final boolean useProxy = socksProxies != null;

    final List<String> httpProxies;
    if (options.has(httpProxyListOption))
      httpProxies = loadLoginProxies(options.valueOf(httpProxyListOption));
    else if (!offline && accounts != null) {
      System.out.println(
          "Option 'http-proxy-list' required if " + "option 'account-list' is supplied.");
      printHelp(parser);
      return;
    } else httpProxies = null;

    final int loginDelay;
    if (options.has(loginDelayOption)) loginDelay = options.valueOf(loginDelayOption);
    else loginDelay = 0;

    final int botAmount;
    if (!options.has(botAmountOption)) {
      System.out.println("Option 'bot-amount' required.");
      printHelp(parser);
      return;
    } else botAmount = options.valueOf(botAmountOption);

    initGui();
    while (!sessions.get()) {
      synchronized (sessions) {
        try {
          sessions.wait(5000);
        } catch (InterruptedException exception) {
        }
      }
    }

    final Queue<Runnable> lockQueue = new ArrayDeque<Runnable>();

    ExecutorService service = Executors.newFixedThreadPool(botAmount + (loginDelay > 0 ? 1 : 0));
    final Object firstWait = new Object();
    if (loginDelay > 0) {
      service.execute(
          new Runnable() {
            @Override
            public void run() {
              synchronized (firstWait) {
                try {
                  firstWait.wait();
                } catch (InterruptedException exception) {
                }
              }
              while (true) {
                if (die) return;
                while (slotsTaken.get() >= 2) {
                  synchronized (slotsTaken) {
                    try {
                      slotsTaken.wait(500);
                    } catch (InterruptedException exception) {
                    }
                  }
                }
                synchronized (lockQueue) {
                  if (lockQueue.size() > 0) {
                    Runnable thread = lockQueue.poll();
                    synchronized (thread) {
                      thread.notifyAll();
                    }
                    lockQueue.offer(thread);
                  } else continue;
                }
                try {
                  Thread.sleep(loginDelay);
                } catch (InterruptedException exception) {
                }
                while (!sessions.get()) {
                  synchronized (sessions) {
                    try {
                      sessions.wait(5000);
                    } catch (InterruptedException exception) {
                    }
                  }
                }
              }
            }
          });
    }
    final List<String> accountsInUse = new ArrayList<String>();
    for (int i = 0; i < botAmount; i++) {
      final int botNumber = i;
      Runnable runnable =
          new Runnable() {
            @Override
            public void run() {
              if (loginDelay > 0)
                synchronized (lockQueue) {
                  lockQueue.add(this);
                }
              Random random = new Random();

              if (!offline) {
                boolean authenticated = false;
                user:
                while (true) {
                  if (authenticated) {
                    authenticated = false;
                    sessionCount.decrementAndGet();
                  }
                  Session session = null;
                  String loginProxy;
                  String account = accounts.get(random.nextInt(accounts.size()));
                  synchronized (accountsInUse) {
                    if (accountsInUse.size() == accounts.size()) System.exit(0);
                    while (accountsInUse.contains(account))
                      account = accounts.get(random.nextInt(accounts.size()));
                    accountsInUse.add(account);
                  }
                  String[] accountParts = account.split(":");
                  while (true) {
                    while (!sessions.get()) {
                      synchronized (sessions) {
                        try {
                          sessions.wait(5000);
                        } catch (InterruptedException exception) {
                        }
                      }
                    }
                    loginProxy = httpProxies.get(random.nextInt(httpProxies.size()));
                    try {
                      session = Util.retrieveSession(accountParts[0], accountParts[1], loginProxy);
                      // addAccount(session);
                      sessionCount.incrementAndGet();
                      authenticated = true;
                      break;
                    } catch (AuthenticationException exception) {
                      System.err.println("[Bot" + botNumber + "] " + exception);
                      if (!exception.getMessage().startsWith("Exception"))
                        // && !exception.getMessage().equals(
                        // "Too many failed logins"))
                        continue user;
                    }
                  }
                  System.out.println(
                      "["
                          + session.getUsername()
                          + "] Password: "******", Session ID: "
                          + session.getSessionId());
                  while (!joins.get()) {
                    synchronized (joins) {
                      try {
                        joins.wait(5000);
                      } catch (InterruptedException exception) {
                      }
                    }
                  }
                  if (loginDelay > 0) {
                    synchronized (this) {
                      try {
                        synchronized (firstWait) {
                          firstWait.notifyAll();
                        }
                        wait();
                      } catch (InterruptedException exception) {
                      }
                    }
                  }

                  while (true) {
                    String proxy =
                        useProxy ? socksProxies.get(random.nextInt(socksProxies.size())) : null;
                    try {
                      new DarkBotMCSpambot(
                          DARK_BOT,
                          server,
                          session.getUsername(),
                          session.getPassword(),
                          session.getSessionId(),
                          null,
                          proxy,
                          owner);
                      if (die) break user;
                      else if (!autoRejoin) break;
                    } catch (Exception exception) {
                      exception.printStackTrace();
                      System.out.println(
                          "["
                              + session.getUsername()
                              + "] Error connecting: "
                              + exception.getCause().toString());
                    }
                  }
                  System.out.println("[" + session.getUsername() + "] Account failed");
                }
              } else {
                while (true) {
                  String proxy =
                      useProxy ? socksProxies.get(random.nextInt(socksProxies.size())) : null;
                  try {
                    String username = "";
                    if (accounts != null) {
                      username = accounts.get(random.nextInt(accounts.size())).split(":")[0];
                      synchronized (accountsInUse) {
                        while (accountsInUse.contains(username))
                          username = accounts.get(random.nextInt(accounts.size()));
                        accountsInUse.add(username);
                      }
                    } else
                      for (int i = 0; i < 10 + random.nextInt(6); i++)
                        username += alphas[random.nextInt(alphas.length)];
                    if (loginDelay > 0) {
                      synchronized (this) {
                        try {
                          synchronized (firstWait) {
                            firstWait.notifyAll();
                          }
                          wait();
                        } catch (InterruptedException exception) {
                        }
                      }
                    }
                    new DarkBotMCSpambot(DARK_BOT, server, username, "", "", null, proxy, owner);
                    if (die || !autoRejoin) break;
                    else continue;
                  } catch (Exception exception) {
                    System.out.println(
                        "[Bot" + botNumber + "] Error connecting: " + exception.toString());
                  }
                }
              }
            }
          };
      service.execute(runnable);
    }
    service.shutdown();
    while (!service.isTerminated()) {
      try {
        service.awaitTermination(9000, TimeUnit.DAYS);
      } catch (InterruptedException exception) {
        exception.printStackTrace();
      }
    }
    System.exit(0);
  }
示例#30
0
 public void execute(Runnable command) {
   e.execute(command);
 }