public static <T> List<T> executeAndGetResult( Collection<? extends Callable<T>> tasks, long waitingTimeInMillis) { ExecutorService executor = Executors.newFixedThreadPool(tasks.size()); List<T> finalResults = new ArrayList<T>(tasks.size()); List<Future<T>> temporaryResults = new ArrayList<Future<T>>(tasks.size()); try { for (Callable<T> task : tasks) { Future<T> future = executor.submit(task); temporaryResults.add(future); } executor.awaitTermination(waitingTimeInMillis, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { throw new RuntimeException(e); } finally { executor.shutdown(); } finalResults = new ArrayList<T>(temporaryResults.size()); for (Future<T> result : temporaryResults) { try { finalResults.add(result.get()); } catch (InterruptedException e) { throw new RuntimeException(e); } catch (ExecutionException e) { throw new RuntimeException(e); } } return finalResults; }
public static CudaEngine getCudaEngine(CudaObject co) { synchronized (cudaEngines) { if (!isCudaAvailable()) throw new CudaException("No cuda device found"); try { initialization.awaitTermination(100, TimeUnit.SECONDS); } catch (InterruptedException e) { e.printStackTrace(); } Pheromone p = (Pheromone) co; final int pheroID = cudaObjectID.incrementAndGet(); final CudaEngine ce = cudaEngines.get(pheroID % availableDevicesNb); // final CudaEngine ce = cudaEngines.get(1); // final CudaEngine ce = cudaEngines.get(0); // final CudaEngine ce; // if(p.getName().contains("PRE")){ // ce = cudaEngines.get(0); // } // else{ // ce = cudaEngines.get(1); // } // ce.cudaObjects.add(co); System.err.println(co + "ID " + pheroID + " getting cuda engine Id " + ce.Id); return ce; } }
public <T> Collection<T> getParallelResults(List<Node<T>> nodes) throws InterruptedException { ExecutorService exec = Executors.newCachedThreadPool(); Queue<T> resultQueue = new ConcurrentLinkedQueue<T>(); parallelRecursive(exec, nodes, resultQueue); exec.shutdown(); exec.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS); return resultQueue; }
private void shutdownAndAwaitTermination(int seconds) { // disable submission of new tasks executorService.shutdown(); try { // wait for existing tasks to terminate if (!executorService.awaitTermination(seconds, TimeUnit.SECONDS)) { // cancel lingering tasks executorService.shutdownNow(); // wait for lingering tasks to terminate if (!executorService.awaitTermination(seconds, TimeUnit.SECONDS)) { System.err.println("executorService did not terminate!"); } } } catch (InterruptedException ie) { // (re-)cancel if current thread also interrupted executorService.shutdownNow(); // preserve interrupt status Thread.currentThread().interrupt(); } }
private synchronized void shutdown() { if (!exe.isShutdown()) { freeCUObjectsMemory(); } exe.shutdown(); try { System.err.println( "cuda device " + Id + " freed ? " + exe.awaitTermination(10, TimeUnit.SECONDS)); } catch (InterruptedException e) { e.printStackTrace(); } }
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(); } }
/** {@inheritDoc} */ @Override public void loadCache(GridBiInClosure<K, V> c, @Nullable Object... args) throws GridException { ExecutorService exec = new ThreadPoolExecutor( threadsCnt, threadsCnt, 0L, MILLISECONDS, new ArrayBlockingQueue<Runnable>(batchQueueSize), new BlockingRejectedExecutionHandler()); Iterator<I> iter = inputIterator(args); Collection<I> buf = new ArrayList<>(batchSize); try { while (iter.hasNext()) { if (Thread.currentThread().isInterrupted()) { U.warn(log, "Working thread was interrupted while loading data."); break; } buf.add(iter.next()); if (buf.size() == batchSize) { exec.submit(new Worker(c, buf, args)); buf = new ArrayList<>(batchSize); } } if (!buf.isEmpty()) exec.submit(new Worker(c, buf, args)); } catch (RejectedExecutionException ignored) { // Because of custom RejectedExecutionHandler. assert false : "RejectedExecutionException was thrown while it shouldn't."; } finally { exec.shutdown(); try { exec.awaitTermination(Long.MAX_VALUE, MILLISECONDS); } catch (InterruptedException ignored) { U.warn(log, "Working thread was interrupted while waiting for put operations to complete."); Thread.currentThread().interrupt(); } } }
static void test() throws Throwable { final ExecutorService executor = Executors.newCachedThreadPool(); final NotificationReceiver notifiee1 = new NotificationReceiver(); final NotificationReceiver notifiee2 = new NotificationReceiver(); final Collection<Callable<Object>> tasks = new ArrayList<Callable<Object>>(); tasks.add(new BlockingTask(notifiee1)); tasks.add(new BlockingTask(notifiee2)); tasks.add(new NonBlockingTask()); // start a thread to invoke the tasks Thread thread = new Thread() { public void run() { try { executor.invokeAll(tasks); } catch (RejectedExecutionException t) { /* OK */ } catch (Throwable t) { unexpected(t); } } }; thread.start(); // Wait until tasks begin execution notifiee1.waitForNotification(); notifiee2.waitForNotification(); // Now try to shutdown the executor service while tasks // are blocked. This should cause the tasks to be // interrupted. executor.shutdownNow(); if (!executor.awaitTermination(5, TimeUnit.SECONDS)) throw new Error("Executor stuck"); // Wait for the invocation thread to complete. thread.join(1000); if (thread.isAlive()) { thread.interrupt(); thread.join(1000); throw new Error("invokeAll stuck"); } }
@Override public void destroy() throws Exception { if (internalExecutorServiceRegistry.isEmpty()) { logger.info("开始释放相关资源"); for (ExecutorService executor : internalExecutorServiceRegistry) { if (executor != null) { try { executor.shutdown(); executor.awaitTermination(5, TimeUnit.MINUTES); executor = null; } catch (InterruptedException e) { logger.warn("interrupted when shuting down the query executor:\n{}", e); } } } getDataSourceSpecificExecutors().clear(); logger.info("所有相关资源释放完闭"); } }
public static void main(String[] args) throws Exception { int maxThreads = 5; if (args.length > 0) maxThreads = Integer.parseInt(args[0]); print = true; for (int i = 2; i <= maxThreads; i += (i + 1) >>> 1) { System.out.print("Threads: " + i); try { new FutureLoop(i).test(); } catch (BrokenBarrierException bb) { // OK; ignore } catch (ExecutionException ee) { // OK; ignore } Thread.sleep(TIMEOUT); } pool.shutdown(); if (!pool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS)) throw new Error(); }
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"); }
/** Shutdown-related method behaviour when the cluster is running */ @Test public void testShutdownBehaviour() throws Exception { ExecutorService executor = createSingleNodeExecutorService("testShutdownBehaviour"); // Fresh instance, is not shutting down assertFalse(executor.isShutdown()); assertFalse(executor.isTerminated()); executor.shutdown(); assertTrue(executor.isShutdown()); assertTrue(executor.isTerminated()); // shutdownNow() should return an empty list and be ignored List<Runnable> pending = executor.shutdownNow(); assertTrue(pending.isEmpty()); assertTrue(executor.isShutdown()); assertTrue(executor.isTerminated()); // awaitTermination() should return immediately false try { boolean terminated = executor.awaitTermination(60L, TimeUnit.SECONDS); assertFalse(terminated); } catch (InterruptedException ie) { fail("InterruptedException"); } assertTrue(executor.isShutdown()); assertTrue(executor.isTerminated()); }
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(); } }
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); }
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> protocolOption = parser .accepts( "protocol", "Protocol version to use. Can be either protocol number or Minecraft version.") .withRequiredArg(); OptionSpec<?> protocolsOption = parser.accepts("protocols", "List available protocols and exit."); 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"); OptionSpec<String> captchaListOption = parser .accepts("captcha-list", "File containing a list of chat baised captcha to bypass.") .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; } if (options.has(protocolsOption)) { System.out.println("Available protocols:"); for (ProtocolProvider provider : ProtocolProvider.getProviders()) System.out.println( "\t" + provider.getMinecraftVersion() + " (" + provider.getSupportedVersion() + "): " + provider.getClass().getName()); System.out.println( "If no protocols are listed above, you may attempt to specify a protocol version in case the provider is actually in the class-path."); 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 List<String> captcha; if (options.has(captchaListOption)) readCaptchaFile(options.valueOf(captchaListOption)); 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 int protocol; if (options.has(protocolOption)) { String protocolString = options.valueOf(protocolOption); int parsedProtocol; try { parsedProtocol = Integer.parseInt(protocolString); } catch (NumberFormatException exception) { ProtocolProvider foundProvider = null; for (ProtocolProvider provider : ProtocolProvider.getProviders()) if (protocolString.equals(provider.getMinecraftVersion())) foundProvider = provider; if (foundProvider == null) { System.out.println("No provider found for Minecraft version '" + protocolString + "'."); return; } else parsedProtocol = foundProvider.getSupportedVersion(); } protocol = parsedProtocol; } else protocol = MinecraftBot.LATEST_PROTOCOL; 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) { try { Thread.sleep(loginDelay); } catch (InterruptedException exception) { } synchronized (lockQueue) { if (lockQueue.size() > 0) { Runnable thread = lockQueue.poll(); synchronized (thread) { thread.notifyAll(); } lockQueue.offer(thread); } else continue; } while (!sessions.get()) { synchronized (sessions) { try { sessions.wait(5000); } catch (InterruptedException exception) { } } } } } }); } final List<String> accountsInUse = new ArrayList<String>(); final Map<String, AtomicInteger> workingProxies = new HashMap<String, AtomicInteger>(); 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) { AuthService authService = new LegacyAuthService(); 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) { } } } synchronized (workingProxies) { Iterator<String> iterator = workingProxies.keySet().iterator(); if (iterator.hasNext()) loginProxy = iterator.next(); else loginProxy = httpProxies.get(random.nextInt(httpProxies.size())); ; } try { session = authService.login( accountParts[0], accountParts[1], toProxy(loginProxy, Proxy.Type.HTTP)); // addAccount(session); synchronized (workingProxies) { AtomicInteger count = workingProxies.get(loginProxy); if (count != null) count.set(0); else workingProxies.put(loginProxy, new AtomicInteger()); } sessionCount.incrementAndGet(); authenticated = true; break; } catch (IOException exception) { synchronized (workingProxies) { workingProxies.remove(loginProxy); } System.err.println("[Bot" + botNumber + "] " + loginProxy + ": " + exception); } catch (AuthenticationException exception) { if (exception.getMessage().contains("Too many failed logins")) { synchronized (workingProxies) { AtomicInteger count = workingProxies.get(loginProxy); if (count != null && count.incrementAndGet() >= 5) workingProxies.remove(loginProxy); } } System.err.println("[Bot" + botNumber + "] " + loginProxy + ": " + exception); continue user; } } System.out.println("[" + session.getUsername() + "] " + session); 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 { DarkBotMCSpambot bot = new DarkBotMCSpambot( generateData( server, session.getUsername(), session.getPassword(), authService, session, protocol, null, proxy), owner); while (bot.getBot().isConnected()) { try { Thread.sleep(500); } catch (InterruptedException exception) { exception.printStackTrace(); } } 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 username = Util.generateRandomString(10 + random.nextInt(6)); if (loginDelay > 0) { synchronized (this) { try { synchronized (firstWait) { firstWait.notifyAll(); } wait(); } catch (InterruptedException exception) { } } } DarkBotMCSpambot bot = new DarkBotMCSpambot( generateData(server, username, null, null, null, protocol, null, proxy), owner); while (bot.getBot().isConnected()) { try { Thread.sleep(500); } catch (InterruptedException exception) { exception.printStackTrace(); } } if (!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); }
/** * Discover WS device on the local network * * @return list of unique devices access strings which might be URLs in most cases */ public static Collection<String> discoverWsDevices() { final Collection<String> addresses = new ConcurrentSkipListSet<>(); final CountDownLatch serverStarted = new CountDownLatch(1); final CountDownLatch serverFinished = new CountDownLatch(1); final Collection<InetAddress> addressList = new ArrayList<>(); try { final Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); if (interfaces != null) { while (interfaces.hasMoreElements()) { NetworkInterface anInterface = interfaces.nextElement(); if (!anInterface.isLoopback()) { final List<InterfaceAddress> interfaceAddresses = anInterface.getInterfaceAddresses(); for (InterfaceAddress address : interfaceAddresses) { addressList.add(address.getAddress()); } } } } } catch (SocketException e) { e.printStackTrace(); } ExecutorService executorService = Executors.newCachedThreadPool(); for (final InetAddress address : addressList) { Runnable runnable = new Runnable() { public void run() { try { final String uuid = UUID.randomUUID().toString(); final String probe = WS_DISCOVERY_PROBE_MESSAGE.replaceAll( "<wsa:MessageID>urn:uuid:.*</wsa:MessageID>", "<wsa:MessageID>urn:uuid:" + uuid + "</wsa:MessageID>"); final int port = random.nextInt(20000) + 40000; @SuppressWarnings("SocketOpenedButNotSafelyClosed") final DatagramSocket server = new DatagramSocket(port, address); new Thread() { public void run() { try { final DatagramPacket packet = new DatagramPacket(new byte[4096], 4096); server.setSoTimeout(WS_DISCOVERY_TIMEOUT); long timerStarted = System.currentTimeMillis(); while (System.currentTimeMillis() - timerStarted < (WS_DISCOVERY_TIMEOUT)) { serverStarted.countDown(); server.receive(packet); final Collection<String> collection = parseSoapResponseForUrls( Arrays.copyOf(packet.getData(), packet.getLength())); for (String key : collection) { addresses.add(key); } } } catch (SocketTimeoutException ignored) { } catch (Exception e) { e.printStackTrace(); } finally { serverFinished.countDown(); server.close(); } } }.start(); try { serverStarted.await(1000, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { e.printStackTrace(); } if (address instanceof Inet4Address) { server.send( new DatagramPacket( probe.getBytes(), probe.length(), InetAddress.getByName(WS_DISCOVERY_ADDRESS_IPv4), WS_DISCOVERY_PORT)); } else { server.send( new DatagramPacket( probe.getBytes(), probe.length(), InetAddress.getByName(WS_DISCOVERY_ADDRESS_IPv6), WS_DISCOVERY_PORT)); } } catch (Exception e) { e.printStackTrace(); } try { serverFinished.await((WS_DISCOVERY_TIMEOUT), TimeUnit.MILLISECONDS); } catch (InterruptedException e) { e.printStackTrace(); } } }; executorService.submit(runnable); } try { executorService.shutdown(); executorService.awaitTermination(WS_DISCOVERY_TIMEOUT + 2000, TimeUnit.MILLISECONDS); } catch (InterruptedException ignored) { } return addresses; }
public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { return e.awaitTermination(timeout, unit); }
protected void handleCommand(String command) { if (command.contains("__")) { namespace = command.split("__")[0]; command = command.substring(command.indexOf("__") + 2); } if (echo) { if (Thread.currentThread().getName().toLowerCase().indexOf("main") < 0) println(" [" + Thread.currentThread().getName() + "] " + command); else println(command); } if (command == null || command.startsWith("//")) return; command = command.trim(); if (command == null || command.length() == 0) { return; } String first = command; int spaceIndex = command.indexOf(' '); String[] argsSplit = command.split(" "); String[] args = new String[argsSplit.length]; for (int i = 0; i < argsSplit.length; i++) { args[i] = argsSplit[i].trim(); } if (spaceIndex != -1) { first = args[0]; } if (command.startsWith("help")) { handleHelp(command); } else if (first.startsWith("#") && first.length() > 1) { int repeat = Integer.parseInt(first.substring(1)); long t0 = Clock.currentTimeMillis(); for (int i = 0; i < repeat; i++) { handleCommand(command.substring(first.length()).replaceAll("\\$i", "" + i)); } println("ops/s = " + repeat * 1000 / (Clock.currentTimeMillis() - t0)); return; } else if (first.startsWith("&") && first.length() > 1) { final int fork = Integer.parseInt(first.substring(1)); ExecutorService pool = Executors.newFixedThreadPool(fork); final String threadCommand = command.substring(first.length()); for (int i = 0; i < fork; i++) { final int threadID = i; pool.submit( new Runnable() { public void run() { String command = threadCommand; String[] threadArgs = command.replaceAll("\\$t", "" + threadID).trim().split(" "); // TODO &t #4 m.putmany x k if ("m.putmany".equals(threadArgs[0]) || "m.removemany".equals(threadArgs[0])) { if (threadArgs.length < 4) { command += " " + Integer.parseInt(threadArgs[1]) * threadID; } } handleCommand(command); } }); } pool.shutdown(); try { pool.awaitTermination(60 * 60, TimeUnit.SECONDS); // wait 1h } catch (Exception e) { e.printStackTrace(); } } else if (first.startsWith("@")) { if (first.length() == 1) { println("usage: @<file-name>"); return; } File f = new File(first.substring(1)); println("Executing script file " + f.getAbsolutePath()); if (f.exists()) { try { BufferedReader br = new BufferedReader(new FileReader(f)); String l = br.readLine(); while (l != null) { handleCommand(l); l = br.readLine(); } br.close(); } catch (IOException e) { e.printStackTrace(); } } else { println("File not found! " + f.getAbsolutePath()); } } else if (command.indexOf(';') != -1) { StringTokenizer st = new StringTokenizer(command, ";"); while (st.hasMoreTokens()) { handleCommand(st.nextToken()); } return; } else if ("silent".equals(first)) { silent = Boolean.parseBoolean(args[1]); } else if ("shutdown".equals(first)) { hazelcast.getLifecycleService().shutdown(); } else if ("echo".equals(first)) { echo = Boolean.parseBoolean(args[1]); println("echo: " + echo); } else if ("ns".equals(first)) { if (args.length > 1) { namespace = args[1]; println("namespace: " + namespace); // init(); } } else if ("whoami".equals(first)) { println(hazelcast.getCluster().getLocalMember()); } else if ("who".equals(first)) { println(hazelcast.getCluster()); } else if ("jvm".equals(first)) { System.gc(); println("Memory max: " + Runtime.getRuntime().maxMemory() / 1024 / 1024 + "M"); println( "Memory free: " + Runtime.getRuntime().freeMemory() / 1024 / 1024 + "M " + (int) (Runtime.getRuntime().freeMemory() * 100 / Runtime.getRuntime().maxMemory()) + "%"); long total = Runtime.getRuntime().totalMemory(); long free = Runtime.getRuntime().freeMemory(); println("Used Memory:" + ((total - free) / 1024 / 1024) + "MB"); println("# procs: " + Runtime.getRuntime().availableProcessors()); println( "OS info: " + ManagementFactory.getOperatingSystemMXBean().getArch() + " " + ManagementFactory.getOperatingSystemMXBean().getName() + " " + ManagementFactory.getOperatingSystemMXBean().getVersion()); println( "JVM: " + ManagementFactory.getRuntimeMXBean().getVmVendor() + " " + ManagementFactory.getRuntimeMXBean().getVmName() + " " + ManagementFactory.getRuntimeMXBean().getVmVersion()); } else if (first.indexOf("ock") != -1 && first.indexOf(".") == -1) { handleLock(args); } else if (first.indexOf(".size") != -1) { handleSize(args); } else if (first.indexOf(".clear") != -1) { handleClear(args); } else if (first.indexOf(".destroy") != -1) { handleDestroy(args); } else if (first.indexOf(".iterator") != -1) { handleIterator(args); } else if (first.indexOf(".contains") != -1) { handleContains(args); } else if (first.indexOf(".stats") != -1) { handStats(args); } else if ("t.publish".equals(first)) { handleTopicPublish(args); } else if ("q.offer".equals(first)) { handleQOffer(args); } else if ("q.take".equals(first)) { handleQTake(args); } else if ("q.poll".equals(first)) { handleQPoll(args); } else if ("q.peek".equals(first)) { handleQPeek(args); } else if ("q.capacity".equals(first)) { handleQCapacity(args); } else if ("q.offermany".equals(first)) { handleQOfferMany(args); } else if ("q.pollmany".equals(first)) { handleQPollMany(args); } else if ("s.add".equals(first)) { handleSetAdd(args); } else if ("s.remove".equals(first)) { handleSetRemove(args); } else if ("s.addmany".equals(first)) { handleSetAddMany(args); } else if ("s.removemany".equals(first)) { handleSetRemoveMany(args); } else if (first.equals("m.replace")) { handleMapReplace(args); } else if (first.equalsIgnoreCase("m.putIfAbsent")) { handleMapPutIfAbsent(args); } else if (first.equals("m.putAsync")) { handleMapPutAsync(args); } else if (first.equals("m.getAsync")) { handleMapGetAsync(args); } else if (first.equals("m.put")) { handleMapPut(args); } else if (first.equals("m.get")) { handleMapGet(args); } else if (first.equalsIgnoreCase("m.getMapEntry")) { handleMapGetMapEntry(args); } else if (first.equals("m.remove")) { handleMapRemove(args); } else if (first.equals("m.evict")) { handleMapEvict(args); } else if (first.equals("m.putmany") || first.equalsIgnoreCase("m.putAll")) { handleMapPutMany(args); } else if (first.equals("m.getmany")) { handleMapGetMany(args); } else if (first.equals("m.removemany")) { handleMapRemoveMany(args); } else if (command.equalsIgnoreCase("m.localKeys")) { handleMapLocalKeys(); } else if (command.equals("m.keys")) { handleMapKeys(); } else if (command.equals("m.values")) { handleMapValues(); } else if (command.equals("m.entries")) { handleMapEntries(); } else if (first.equals("m.lock")) { handleMapLock(args); } else if (first.equalsIgnoreCase("m.tryLock")) { handleMapTryLock(args); } else if (first.equals("m.unlock")) { handleMapUnlock(args); } else if (first.indexOf(".addListener") != -1) { handleAddListener(args); } else if (first.equals("m.removeMapListener")) { handleRemoveListener(args); } else if (first.equals("m.unlock")) { handleMapUnlock(args); } else if (first.equals("l.add")) { handleListAdd(args); } else if (first.equals("l.set")) { handleListSet(args); } else if ("l.addmany".equals(first)) { handleListAddMany(args); } else if (first.equals("l.remove")) { handleListRemove(args); } else if (first.equals("l.contains")) { handleListContains(args); } else if ("a.get".equals(first)) { handleAtomicNumberGet(args); } else if ("a.set".equals(first)) { handleAtomicNumberSet(args); } else if ("a.inc".equals(first)) { handleAtomicNumberInc(args); } else if ("a.dec".equals(first)) { handleAtomicNumberDec(args); // } else if (first.equals("execute")) { // execute(args); } else if (first.equals("partitions")) { handlePartitions(args); // } else if (first.equals("txn")) { // hazelcast.getTransaction().begin(); // } else if (first.equals("commit")) { // hazelcast.getTransaction().commit(); // } else if (first.equals("rollback")) { // hazelcast.getTransaction().rollback(); // } else if (first.equalsIgnoreCase("executeOnKey")) { // executeOnKey(args); // } else if (first.equalsIgnoreCase("executeOnMember")) { // executeOnMember(args); // } else if (first.equalsIgnoreCase("executeOnMembers")) { // executeOnMembers(args); // } else if (first.equalsIgnoreCase("longOther") || // first.equalsIgnoreCase("executeLongOther")) { // executeLongTaskOnOtherMember(args); // } else if (first.equalsIgnoreCase("long") || first.equalsIgnoreCase("executeLong")) // { // executeLong(args); } else if (first.equalsIgnoreCase("instances")) { handleInstances(args); } else if (first.equalsIgnoreCase("quit") || first.equalsIgnoreCase("exit")) { System.exit(0); } else { println("type 'help' for help"); } }