/** * Test concurrent reader and writer (GH-458). * * <p><b>Test case:</b> * * <ol> * <li/>start a long running reader; * <li/>try to start a writer: it should time out; * <li/>stop the reader; * <li/>start the writer again: it should succeed. * </ol> * * @throws Exception error during request execution */ @Test @Ignore("There is no way to stop a query on the server!") public void testReaderWriter() throws Exception { final String readerQuery = "?query=(1%20to%20100000000000000)%5b.=1%5d"; final String writerQuery = "/test.xml"; final byte[] content = Token.token("<a/>"); final Get readerAction = new Get(readerQuery); final Put writerAction = new Put(writerQuery, content); final ExecutorService exec = Executors.newFixedThreadPool(2); // start reader exec.submit(readerAction); Performance.sleep(TIMEOUT); // delay in order to be sure that the reader has started // start writer Future<HTTPResponse> writer = exec.submit(writerAction); try { final HTTPResponse result = writer.get(TIMEOUT, TimeUnit.MILLISECONDS); if (result.status.isSuccess()) fail("Database modified while a reader is running"); throw new Exception(result.toString()); } catch (final TimeoutException e) { // writer is blocked by the reader: stop it writerAction.stop = true; } // stop reader readerAction.stop = true; // start the writer again writer = exec.submit(writerAction); assertEquals(HTTPCode.CREATED, writer.get().status); }
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; }
public class Client { private static final int PORT = 7788; private static ExecutorService exec = Executors.newCachedThreadPool(); public static void main(String[] args) { new Client(); } public Client() { try { Socket socket = new Socket("192.168.1.34", PORT); exec.execute(new SendMsg(socket)); System.out.println("[" + socket.getInetAddress() + "] ' Joining ... "); BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); String msg; while ((msg = br.readLine()) != null) { System.out.println(msg); } } catch (IOException e) { } } /* Client thread get infor from Servers */ static class SendMsg implements Runnable { private Socket socket; public SendMsg(Socket socket) { this.socket = socket; } public void run() { try { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(socket.getOutputStream(), true); String msg; while (true) { msg = br.readLine(); pw.println(msg); if (msg.trim().equals("-quit")) { pw.close(); br.close(); exec.shutdownNow(); break; } } } catch (Exception e) { e.printStackTrace(); } } } }
class DaemonThreadFactory implements ThreadFactory { static final ThreadFactory INSTANCE = new DaemonThreadFactory(); private static final ThreadFactory DEFAULT = Executors.defaultThreadFactory(); public Thread newThread(Runnable r) { Thread t = DEFAULT.newThread(r); t.setDaemon(true); return t; } }
/** * Create the HttpServer to use. Can be overridden if a custom or already existing HttpServer * should be used * * @return HttpServer to use * @throws IOException if something fails during the initialisation */ private HttpServer createHttpServer(JolokiaServerConfig pConfig) throws IOException { int port = pConfig.getPort(); InetAddress address = pConfig.getAddress(); InetSocketAddress socketAddress = new InetSocketAddress(address, port); HttpServer server = pConfig.useHttps() ? createHttpsServer(socketAddress, pConfig) : HttpServer.create(socketAddress, pConfig.getBacklog()); // Prepare executor pool Executor executor; String mode = pConfig.getExecutor(); if ("fixed".equalsIgnoreCase(mode)) { executor = Executors.newFixedThreadPool(pConfig.getThreadNr(), daemonThreadFactory); } else if ("cached".equalsIgnoreCase(mode)) { executor = Executors.newCachedThreadPool(daemonThreadFactory); } else { executor = Executors.newSingleThreadExecutor(daemonThreadFactory); } server.setExecutor(executor); return server; }
/** {@inheritDoc} */ @Override public void run() { List<Grid> clientGrids = runGrid(); assert clientGrids.size() == clientNodes; int threadsCnt = clientNodes * threadsPerClient; Executor e = Executors.newFixedThreadPool(threadsCnt); for (Grid grid : clientGrids) { for (int j = 0; j < threadsPerClient; j++) e.execute(new GridJobLoadTestSubmitter(grid, taskParams, cancelRate, submitDelay)); } }
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) throws Exception { HttpServer s1 = null; HttpsServer s2 = null; ExecutorService executor = null; try { String root = System.getProperty("test.src") + "/docs"; System.out.print("Test12: "); InetSocketAddress addr = new InetSocketAddress(0); s1 = HttpServer.create(addr, 0); s2 = HttpsServer.create(addr, 0); HttpHandler h = new FileServerHandler(root); HttpContext c1 = s1.createContext("/test1", h); HttpContext c2 = s2.createContext("/test1", h); executor = Executors.newCachedThreadPool(); s1.setExecutor(executor); s2.setExecutor(executor); ctx = new SimpleSSLContext(System.getProperty("test.src")).get(); s2.setHttpsConfigurator(new HttpsConfigurator(ctx)); s1.start(); s2.start(); int port = s1.getAddress().getPort(); int httpsport = s2.getAddress().getPort(); Runner r[] = new Runner[8]; r[0] = new Runner(true, "http", root + "/test1", port, "smallfile.txt", 23); r[1] = new Runner(true, "http", root + "/test1", port, "largefile.txt", 2730088); r[2] = new Runner(true, "https", root + "/test1", httpsport, "smallfile.txt", 23); r[3] = new Runner(true, "https", root + "/test1", httpsport, "largefile.txt", 2730088); r[4] = new Runner(false, "http", root + "/test1", port, "smallfile.txt", 23); r[5] = new Runner(false, "http", root + "/test1", port, "largefile.txt", 2730088); r[6] = new Runner(false, "https", root + "/test1", httpsport, "smallfile.txt", 23); r[7] = new Runner(false, "https", root + "/test1", httpsport, "largefile.txt", 2730088); start(r); join(r); System.out.println("OK"); } finally { delay(); if (s1 != null) s1.stop(2); if (s2 != null) s2.stop(2); if (executor != null) executor.shutdown(); } }
public void run() { System.out.println("JSSE Server listening on port " + cipherTest.serverPort); Executor exec = Executors.newFixedThreadPool(cipherTest.THREADS, DaemonThreadFactory.INSTANCE); try { while (true) { final SSLSocket socket = (SSLSocket) serverSocket.accept(); socket.setSoTimeout(cipherTest.TIMEOUT); Runnable r = new Runnable() { public void run() { try { InputStream in = socket.getInputStream(); OutputStream out = socket.getOutputStream(); handleRequest(in, out); out.flush(); socket.close(); socket.getSession().invalidate(); } catch (IOException e) { cipherTest.setFailed(); e.printStackTrace(); } finally { if (socket != null) { try { socket.close(); } catch (IOException e) { cipherTest.setFailed(); System.out.println("Exception closing socket on server side:"); e.printStackTrace(); } } } } }; exec.execute(r); } } catch (IOException e) { cipherTest.setFailed(); e.printStackTrace(); // } }
/** * Test 2 concurrent readers (GH-458). * * <p><b>Test case:</b> * * <ol> * <li/>start a long running reader; * <li/>start a fast reader: it should succeed. * </ol> * * @throws Exception error during request execution */ @Test public void testMultipleReaders() throws Exception { final String number = "63177"; final String slowQuery = "?query=(1%20to%20100000000000000)%5b.=1%5d"; final String fastQuery = "?query=" + number; final Get slowAction = new Get(slowQuery); final Get fastAction = new Get(fastQuery); final ExecutorService exec = Executors.newFixedThreadPool(2); exec.submit(slowAction); Performance.sleep(TIMEOUT); // delay in order to be sure that the reader has started final Future<HTTPResponse> fast = exec.submit(fastAction); try { final HTTPResponse result = fast.get(TIMEOUT, TimeUnit.MILLISECONDS); assertEquals(HTTPCode.OK, result.status); assertEquals(number, result.data); } finally { slowAction.stop = true; } }
/** * Test concurrent writers (GH-458). * * <p><b>Test case:</b> * * <ol> * <li/>start several writers one after another; * <li/>all writers should succeed. * </ol> * * @throws Exception error during request execution */ @Test public void testMultipleWriters() throws Exception { final int count = 10; final String template = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<command xmlns=\"http://basex.org/rest\"><text><![CDATA[" + "ADD TO %1$d <node id=\"%1$d\"/>" + "]]></text></command>"; @SuppressWarnings("unchecked") final Future<HTTPResponse>[] tasks = new Future[count]; final ExecutorService exec = Executors.newFixedThreadPool(count); // start all writers (not at the same time, but still in parallel) for (int i = 0; i < count; i++) { final String command = String.format(template, i); tasks[i] = exec.submit(new Post("", Token.token(command))); } // check if all have finished successfully for (final Future<HTTPResponse> task : tasks) { assertEquals(HTTPCode.OK, task.get(TIMEOUT, TimeUnit.MILLISECONDS).status); } }
public static Executor getExecutor() { if (executor == null) executor = Executors.newFixedThreadPool(4); return executor; }
/** Hello world! */ public class SceneLayoutApp { private static JInternalFrame dumpWindow; public static final JTextPane permText = new JTextPane(); public static final Timer TIMER = new Timer(); public static final XStream XSTREAM; static { XSTREAM = new XStream(); final Class<Pair> aClass = Pair.class; final Class<Triple> tripleClass = Triple.class; desktopPane = new JDesktopPane() { final JEditorPane ed = new JEditorPane(); { setOpaque(false); try { ed.setOpaque(false); ed.setBackground(Color.black); ed.setPage("http://www.vsiwest.com"); ed.setEditable(false); ed.setEnabled(false); } catch (IOException e) { e.printStackTrace(); } } @Override public void paint(Graphics g) { ed.setSize(getSize()); ed.paint(g); super.paint(g); } }; } public static void main(String[] args) { // final BrowserFrame browserFrame = new BrowserFrame(); new SceneLayoutApp(); } public static final JDesktopPane desktopPane; private static SceneLayoutApp instance; public static ExecutorService threadPool = Executors.newCachedThreadPool(); public SceneLayoutApp() { super(); new Pair(); final JFrame frame = new JFrame("Scene Layout"); final JPanel panel = new JPanel(new BorderLayout()); frame.setContentPane(panel); final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); frame.setMaximumSize(screenSize); frame.setSize(screenSize); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); final JMenuBar mb = new JMenuBar(); frame.setJMenuBar(mb); final JMenu jMenu = new JMenu("File"); mb.add(jMenu); mb.add(new JMenu("Edit")); mb.add(new JMenu("Help")); JMenu menu = new JMenu("Look and Feel"); // // Get all the available look and feel that we are going to use for // creating the JMenuItem and assign the action listener to handle // the selection of menu item to change the look and feel. // UIManager.LookAndFeelInfo[] lookAndFeelInfos = UIManager.getInstalledLookAndFeels(); for (int i = 0; i < lookAndFeelInfos.length; i++) { final UIManager.LookAndFeelInfo lookAndFeelInfo = lookAndFeelInfos[i]; JMenuItem item = new JMenuItem(lookAndFeelInfo.getName()); item.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { try { // // Set the look and feel for the frame and update the UI // to use a new selected look and feel. // UIManager.setLookAndFeel(lookAndFeelInfo.getClassName()); SwingUtilities.updateComponentTreeUI(frame); } catch (ClassNotFoundException e1) { e1.printStackTrace(); } catch (InstantiationException e1) { e1.printStackTrace(); } catch (IllegalAccessException e1) { e1.printStackTrace(); } catch (UnsupportedLookAndFeelException e1) { e1.printStackTrace(); } } }); menu.add(item); } mb.add(menu); jMenu.add(new JMenuItem(new scene.action.QuitAction())); panel.add(new JScrollPane(desktopPane), BorderLayout.CENTER); final JToolBar bar = new JToolBar(); panel.add(bar, BorderLayout.NORTH); final JComboBox comboNewWindow = new JComboBox( new String[] {"320:180", "320:240", "640:360", "640:480", "1280:720", "1920:1080"}); comboNewWindow.addActionListener(new CreateSceneWindowAction()); comboNewWindow.setBorder(BorderFactory.createTitledBorder("Create New Window")); bar.add(comboNewWindow); bar.add( new AbstractAction("Progress Bars") { /** Invoked when an action occurs. */ @Override public void actionPerformed(ActionEvent e) { new ProgressBarAnimator(); } }); bar.add( new AbstractAction("Sliders") { /** Invoked when an action occurs. */ @Override public void actionPerformed(ActionEvent e) { new SliderBarAnimator(); } }); final JCheckBox permaViz = new JCheckBox(); permaViz.setText("Show the dump window"); permaViz.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED)); dumpWindow = new JInternalFrame("perma dump window"); dumpWindow.setContentPane(new JScrollPane(permText)); permaViz.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { dumpWindow.setVisible(permaViz.isSelected()); } }); comboNewWindow.setMaximumSize(comboNewWindow.getPreferredSize()); permaViz.setSelected(false); bar.add(new CreateWebViewV1Action()); bar.add(new CreateWebViewV2Action()); bar.add(permaViz); desktopPane.add(dumpWindow); dumpWindow.setSize(400, 400); dumpWindow.setResizable(true); dumpWindow.setClosable(false); dumpWindow.setIconifiable(false); final JMenuBar m = new JMenuBar(); final JMenu cmenu = new JMenu("Create"); m.add(cmenu); final JMenuItem menuItem = new JMenuItem( new AbstractAction("new") { @Override public void actionPerformed(ActionEvent e) { Runnable runnable = new Runnable() { public void run() { Object[] in = (Object[]) XSTREAM.fromXML(permText.getText()); final JInternalFrame ff = new JInternalFrame(); final ScenePanel c = new ScenePanel(); ff.setContentPane(c); desktopPane.add(ff); final Dimension d = (Dimension) in[0]; c.setMaximumSize(d); c.setPreferredSize(d); ff.setSize(d.width + 50, d.height + 50); ScenePanel.panes.put(c, (List<Pair<Point, ArrayList<URL>>>) in[1]); c.invalidate(); c.repaint(); ff.pack(); ff.setClosable(true); ff.setMaximizable(false); ff.setIconifiable(false); ff.setResizable(false); ff.show(); } }; SwingUtilities.invokeLater(runnable); } }); cmenu.add(menuItem); // JMenuBar menuBar = new JMenuBar(); // getContentPane().add(menuBar); dumpWindow.setJMenuBar(m); frame.setVisible(true); } public static SceneLayoutApp getInstance() { return instance == null ? instance = new SceneLayoutApp() : instance; } }
/** Created by Adrian on 11/26/2015. */ public class TransportListener { private static final ExecutorService executor = Executors.newFixedThreadPool(10); private InetSocketAddress mavenLocation; public TransportListener(int dataServerPort) throws IOException, JSONException { mavenLocation = new InetSocketAddress("127.0.0.1", 3333); switch (dataServerPort) { case 1111: sendDataUdp( mavenLocation, "{\"employee\":{\"firstName\":\"Victor\",\"lastName\":\"Rotaru\",\"department\":\"Tehnic\",\"salary\":504}}"); System.out.println( "[INFO] -----------------------------------------\n" + "[INFO] Data was sent to Maven"); break; case 2222: sendDataUdp( mavenLocation, "{\"employee\":{\"firstName\":\"Eugenia\",\"lastName\":\"Blanaru\",\"department\":\"Vinzari\",\"salary\":501}}"); System.out.println( "[INFO] -----------------------------------------\n" + "[INFO] Data was sent to Maven"); break; case 3333: String xmlEmployees = receiveDataUdp(mavenLocation); sendDataTcp(dataServerPort, xmlEmployees); System.out.println( "[INFO] -----------------------------------------\n" + "[INFO] Data was sent to client"); break; case 4444: sendDataUdp( mavenLocation, "{\"employee\":{\"firstName\":\"Gigi\",\"lastName\":\"Iures\",\"department\":\"Marketing\",\"salary\":502}}"); System.out.println( "[INFO] -----------------------------------------\n" + "[INFO] Data was sent to Maven"); break; case 5555: sendDataUdp( mavenLocation, "{\"employee\":{\"firstName\":\"Igor\",\"lastName\":\"Ignat\",\"department\":\"Financiar\",\"salary\":503}}"); System.out.println( "[INFO] -----------------------------------------\n" + "[INFO] Data was sent to Maven"); break; case 6666: System.out.println( "[INFO] ----------------------------------------- \n" + "[INFO] This node is isolated."); break; default: System.out.println( "[WARNING] ----------------------------------------- \n" + "[WARNING] Server port is not correct."); break; } } private void sendDataTcp(int dataServerPort, String xmlEmployees) throws IOException { ServerSocket serverSocket = new ServerSocket(dataServerPort); serverSocket.setSoTimeout((int) SECONDS.toMillis(100)); boolean isTimeExpired = false; while (!isTimeExpired) { try { Socket socket = serverSocket.accept(); // Blocking call! serialize(xmlEmployees, socket.getOutputStream()); socket.close(); } catch (SocketTimeoutException e) { System.out.println( "[WARNING] ----------------------------------------- \n" + "[WARNING] Waiting time expired... Socket is closed."); isTimeExpired = true; continue; } } serverSocket.close(); } private Future sendDataUdp(final InetSocketAddress clientLocation, final String employee) { return executor.submit( new Runnable() { public void run() { try { Thread.sleep(SECONDS.toMillis(1)); DatagramSocket clientSocket = new DatagramSocket(); byte[] sendDataServer = serialize((String) employee); DatagramPacket pongPacket = new DatagramPacket(sendDataServer, sendDataServer.length, clientLocation); clientSocket.send(pongPacket); clientSocket.close(); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } }); } private String receiveDataUdp(InetSocketAddress clientAddress) throws IOException, JSONException { EmployeeList employees = new EmployeeList(); DatagramSocket datagramServer = new DatagramSocket(clientAddress); byte dataFromServer[] = new byte[2048]; boolean isTimeExpired = false; datagramServer.setSoTimeout((int) SECONDS.toMillis(PROTOCOL_GROUP_TIMEOUT - 5)); System.out.println( "[INFO] -----------------------------------------\n" + "[INFO] Collecting information from nodes...."); while (!isTimeExpired) { DatagramPacket datagramPacketacket = new DatagramPacket(dataFromServer, dataFromServer.length); try { datagramServer.receive(datagramPacketacket); } catch (SocketTimeoutException e) { System.out.println( "[WARNING] -----------------------------------------\n" + "[WARNING] Waiting time expired..."); isTimeExpired = true; continue; } String receivedJson = (String) deserialize(datagramPacketacket.getData()); System.out.println("[INFO] " + "Received employee in JSON: " + receivedJson); employees.add(jsonToEmployee(receivedJson)); } datagramServer.close(); return employeeToXml(employees); } private Employee jsonToEmployee(String jsonString) throws JSONException { // Creating a JSONObject from a String JSONObject nodeRoot = new JSONObject(jsonString); // Creating a sub-JSONObject from another JSONObject JSONObject nodeStats = nodeRoot.getJSONObject("employee"); // Getting the value of a attribute in a JSONObject String firstName = nodeStats.getString("firstName"); String lastName = nodeStats.getString("lastName"); String department = nodeStats.getString("department"); Double salary = nodeStats.getDouble("salary"); return new Employee(firstName, lastName, department, salary); } private String employeeToXml(EmployeeList list) { XStream xstream = new XStream(); xstream.alias("employee", Employee.class); xstream.alias("employees", EmployeeList.class); xstream.addImplicitCollection(EmployeeList.class, "list"); return xstream.toXML(list); } }
/** * 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 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); }