Exemple #1
1
 private CIJobStatus deleteCI(CIJob job, List<String> builds) throws PhrescoException {
   S_LOGGER.debug("Entering Method CIManagerImpl.deleteCI(CIJob job)");
   S_LOGGER.debug("Job name " + job.getName());
   cli = getCLI(job);
   String deleteType = null;
   List<String> argList = new ArrayList<String>();
   S_LOGGER.debug("job name " + job.getName());
   S_LOGGER.debug("Builds " + builds);
   if (CollectionUtils.isEmpty(builds)) { // delete job
     S_LOGGER.debug("Job deletion started");
     S_LOGGER.debug("Command " + FrameworkConstants.CI_JOB_DELETE_COMMAND);
     deleteType = DELETE_TYPE_JOB;
     argList.add(FrameworkConstants.CI_JOB_DELETE_COMMAND);
     argList.add(job.getName());
   } else { // delete Build
     S_LOGGER.debug("Build deletion started");
     deleteType = DELETE_TYPE_BUILD;
     argList.add(FrameworkConstants.CI_BUILD_DELETE_COMMAND);
     argList.add(job.getName());
     StringBuilder result = new StringBuilder();
     for (String string : builds) {
       result.append(string);
       result.append(",");
     }
     String buildNos = result.substring(0, result.length() - 1);
     argList.add(buildNos);
     S_LOGGER.debug("Command " + FrameworkConstants.CI_BUILD_DELETE_COMMAND);
     S_LOGGER.debug("Build numbers " + buildNos);
   }
   try {
     int status = cli.execute(argList);
     String message = deleteType + " deletion started in jenkins";
     if (status == FrameworkConstants.JOB_STATUS_NOTOK) {
       deleteType = deleteType.substring(0, 1).toLowerCase() + deleteType.substring(1);
       message = "Error while deleting " + deleteType + " in jenkins";
     }
     S_LOGGER.debug("Delete CI Status " + status);
     S_LOGGER.debug("Delete CI Message " + message);
     return new CIJobStatus(status, message);
   } finally {
     if (cli != null) {
       try {
         cli.close();
       } catch (IOException e) {
         if (debugEnabled) {
           S_LOGGER.error(
               "Entered into catch block of CIManagerImpl.deleteCI(CIJob job) "
                   + e.getLocalizedMessage());
         }
       } catch (InterruptedException e) {
         if (debugEnabled) {
           S_LOGGER.error(
               "Entered into catch block of CIManagerImpl.deleteCI(CIJob job) "
                   + e.getLocalizedMessage());
         }
       }
     }
   }
 }
Exemple #2
0
  public void run() {
    MOVE_PREV = MOVE_DOWN;

    System.out.println("INIT!");
    map = new int[mapX][mapY];

    for (int i = 0; i < map.length; i++) {
      for (int j = 0; j < map[i].length; j++) {
        map[i][j] = 0;
      }
    }
    map[blockP.x][blockP.y] = 1;
    //    	map[0][20] = 1;

    StdDraw.setXscale(-1.0, 1.0);
    StdDraw.setYscale(-1.0, 1.0);

    // initial values

    // double vx = 0.015, vy = 0.023;     // velocity

    // main animation loop
    while (true) {

      drawGame();
      try {
        Thread.sleep(100);
      } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      movePrev();
    }
  }
Exemple #3
0
  private void connect() throws UnknownHostException, IOException {
    IrcServer = new Socket(serverName, 6667);

    BufferedReader br =
        new BufferedReader(
            new InputStreamReader(IrcServer.getInputStream(), BotStats.getInstance().getCharset()));
    PrintWriter pw =
        new PrintWriter(
            new OutputStreamWriter(
                IrcServer.getOutputStream(), BotStats.getInstance().getCharset()),
            true);
    ih = new InputHandler(br);
    oh = new OutputHandler(pw);

    ih.start();
    oh.start();

    new Message("", "NICK", BotStats.getInstance().getBotname(), "").send();
    new Message(
            "", "USER", "goat" + " nowhere.com " + serverName, BotStats.getInstance().getVersion())
        .send();
    // we sleep until we are connected, don't want to send these next messages too soon
    while (!connected) {
      try {
        sleep(100);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }

    joinChannels();
  }
  /**
   * openConnections: open the connection to the master. has retry mechanism
   *
   * @return: true if the connection is built, false if failed
   */
  public boolean openConnections() {

    _log("Try to connect to Master...");

    int i = 0;
    while (true) {

      boolean isConnected = connect();

      if (!isConnected) {
        i++;
        if (i == DropboxConstants.MAX_TRY) {
          break;
        }
        _log("Cannot connect to Master, retry " + i);
        try {
          Thread.sleep(DropboxConstants.TRY_CONNECT_MILLIS);
        } catch (InterruptedException e) {
          if (!_server.noException()) {
            _elog(e.toString());
          }
          if (_server.debugMode()) {
            e.printStackTrace();
          }
          _log("Retry connection is interrupted");
          break;
        }
      } else {
        _log("Success!");
        return true;
      }
    }
    _log("Failed");
    return false;
  }
Exemple #5
0
  private CIJobStatus buildJob(CIJob job) throws PhrescoException {
    if (debugEnabled) {
      S_LOGGER.debug("Entering Method CIManagerImpl.buildJob(CIJob job)");
    }
    cli = getCLI(job);

    List<String> argList = new ArrayList<String>();
    argList.add(FrameworkConstants.CI_BUILD_JOB_COMMAND);
    argList.add(job.getName());
    try {
      int status = cli.execute(argList);
      String message = FrameworkConstants.CI_BUILD_STARTED;
      if (status == FrameworkConstants.JOB_STATUS_NOTOK) {
        message = FrameworkConstants.CI_BUILD_STARTING_ERROR;
      }
      return new CIJobStatus(status, message);
    } finally {
      if (cli != null) {
        try {
          cli.close();
        } catch (IOException e) {
          if (debugEnabled) {
            S_LOGGER.error(e.getLocalizedMessage());
          }
        } catch (InterruptedException e) {
          if (debugEnabled) {
            S_LOGGER.error(e.getLocalizedMessage());
          }
        }
      }
    }
  }
Exemple #6
0
  /** Creates a new instance of TestLoad */
  public void run() {
    //        URL url = new URL(getCodeBase(), "/servlet/ServletName");
    try {
      while (true) {
        URL url = new URL(strURL);

        url.openConnection();
        InputStream in = url.openStream();

        byte[] b = new byte[1000];
        int iTotal = 0;
        int iLen;
        while ((iLen = in.read(b)) != -1) {
          iTotal += iLen;
          this.sleep(READ_DELAY);
        }
        System.out.println("read " + iTotal + " bytes " + this);
        this.sleep(SPIN_DELAY);
        in.close();
      }

    } catch (InterruptedException ex) {
      ex.printStackTrace();
    } catch (IOException ex) {
      ex.printStackTrace();
    }
  }
Exemple #7
0
  private void reconnect() {
    connected = false;
    while (true) {
      try {
        connect();
        return;
      } catch (UnknownHostException uhe) {
        System.out.println("Hmmn unknown host, will wait 400 seconds then try connecting again.. ");
      } catch (IOException ioe) {
        System.out.println("IOException, waiting 400 secs then retry. ");
      } catch (Exception e) {
        System.err.println("Unexpected exception while trying reconnect() :");
        e.printStackTrace();
      }

      try {
        sleep(400000);
      } catch (InterruptedException e) {
        System.err.println("Interrupted from sleep between reconnect attempts :");
        e.printStackTrace();
      } catch (Exception e) {
        System.err.println("Unexpected exception while sleeping between reconnects :");
        e.printStackTrace();
      }
    }
  }
 public void run() throws Exception {
   Thread[] threads = new Thread[THREADS];
   for (int i = 0; i < THREADS; i++) {
     try {
       threads[i] = new Thread(peerFactory.newClient(this), "Client " + i);
     } catch (Exception e) {
       e.printStackTrace();
       return;
     }
     threads[i].start();
   }
   try {
     for (int i = 0; i < THREADS; i++) {
       threads[i].join();
     }
   } catch (InterruptedException e) {
     setFailed();
     e.printStackTrace();
   }
   if (failed) {
     throw new Exception("*** Test '" + peerFactory.getName() + "' failed ***");
   } else {
     System.out.println("Test '" + peerFactory.getName() + "' completed successfully");
   }
 }
 private void downloadImageThread() {
   Thread thread = new Thread(null, runInBackground, "Background");
   thread.start();
   try {
     thread.join();
   } catch (InterruptedException e) {
     e.printStackTrace();
   }
 }
Exemple #10
0
 private void grabPixels(PixelGrabber grabber) {
   try {
     grabber.grabPixels();
   } catch (InterruptedException e) {
     e.printStackTrace();
   }
   // if (grabber.getColorModel() != ColorModel.getRGBdefault()) {
   //	System.err.println("Warning: found other colormodel than default.");
   // }
 }
 public void run() {
   Thread t = Thread.currentThread();
   while (t == gameloop) {
     try {
       Thread.sleep(20);
     } catch (InterruptedException e) {
       e.printStackTrace();
     }
     repaint();
   }
 }
    @Override
    public void run() {
      try {
        Thread.sleep(3000);

        String uberdustServerDnsName = config.getString("uberdustcoapserver.dnsName");
        if (uberdustServerDnsName == null) {
          throw new Exception("Property uberdustcoapserver.dnsName not set.");
        }

        int uberdustServerPort = config.getInt("uberdustcoapserver.port", 0);
        if (uberdustServerPort == 0) {
          throw new Exception("Property uberdustcoapserver.port not set.");
        }

        InetSocketAddress uberdustServerSocketAddress =
            new InetSocketAddress(InetAddress.getByName(uberdustServerDnsName), uberdustServerPort);

        String baseURI = config.getString("baseURIHost", "localhost");
        CoapRequest fakeRequest =
            new CoapRequest(
                MsgType.NON, Code.POST, new URI("coap://" + baseURI + ":5683/here_i_am"));

        CoapNodeRegistrationServer registrationServer = CoapNodeRegistrationServer.getInstance();
        if (registrationServer == null) {
          log.error("NULL!");
        }
        registrationServer.receiveCoapRequest(fakeRequest, uberdustServerSocketAddress);
      } catch (InterruptedException e) {
        e.printStackTrace();
      } catch (UnknownHostException e) {
        e.printStackTrace();
      } catch (URISyntaxException e) {
        e
            .printStackTrace(); // To change body of catch statement use File | Settings | File
                                // Templates.
      } catch (InvalidMessageException e) {
        e
            .printStackTrace(); // To change body of catch statement use File | Settings | File
                                // Templates.
      } catch (InvalidOptionException e) {
        e
            .printStackTrace(); // To change body of catch statement use File | Settings | File
                                // Templates.
      } catch (ToManyOptionsException e) {
        e
            .printStackTrace(); // To change body of catch statement use File | Settings | File
                                // Templates.
      } catch (Exception e) {
        e
            .printStackTrace(); // To change body of catch statement use File | Settings | File
                                // Templates.
      }
    }
Exemple #13
0
 /** Creates a new instance of TestLoad */
 public static void main(String[] args) {
   try {
     while (true) {
       TestLoad test = new TestLoad(args);
       test.start();
       Thread.currentThread().sleep(CREATE_DELAY);
     }
   } catch (InterruptedException ex) {
     ex.printStackTrace();
   }
 }
Exemple #14
0
 public void stop() {
   if (streamReader == null || !streamReader.isAlive()) {
     System.out.println("Camera already stopped");
     return;
   }
   keepAlive = false;
   try {
     streamReader.join();
   } catch (InterruptedException e) {
     System.err.println(e.getMessage());
   }
 }
  /** listen: start to listen if there is any clients connected */
  public void listen() {

    // Firstly spawn a new thread and then the main thread
    // also start listening
    _userNet = new DropboxFileServerUserNet(_server, _userOut, _userIn, _userSock);
    _userNet.start();

    /* Use main thread, cannot be stopped */
    while (_sock != null && !_sock.isClosed()) {
      try {
        String line = NetComm.receive(_in);
        _dlog(line);
        parse(line);
      } catch (Exception e) {
        if (!_server.noException()) {
          _elog(e.toString());
        }
        break;
        // Break the loop
      }
    }

    /* Clear */
    // Close main thread
    clear();
    // Cancel the listening thread and retry
    _server.cancelListeningThread();
    /* Also cancel all of the syncers */
    _server.cancelSyncers();
    // Retry after
    try {

      _log(
          "The connection to master is broken,"
              + " reset everything and retry connection after "
              + DropboxConstants.TRY_CONNECT_MILLIS
              + " milliseconds");

      Thread.sleep(DropboxConstants.TRY_CONNECT_MILLIS);

    } catch (InterruptedException e) {
      if (!_server.noException()) {
        _elog(e.toString());
      }
      if (_server.debugMode()) {
        e.printStackTrace();
      }
    }
    _server.run();

    clear();
    _log(_threadName + " is stopped");
  }
Exemple #16
0
  public static void waitBeforePageLoad(int seconds, boolean testRun) {

    if (testRun || seconds == -1) return;
    if (seconds == 0) seconds = 3;

    Random rand = new Random();
    long mseconds = rand.nextInt((seconds - 1) * 1000) + 1000;
    mseconds += 1500; // sempre almeno 1.5 secs
    try {
      Thread.sleep(mseconds);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
 public void ShutdownAllClientServicers() {
   sf.VERBOSE("CLIENTSERVICER: Shutting down all client connections");
   ClientServicer crrntServicer;
   while (vctServicers.size() != 0) {
     crrntServicer = (ClientServicer) vctServicers.firstElement();
     crrntServicer.Shutdown();
     try {
       crrntServicer.join(1000);
     } catch (InterruptedException e) {
       e.printStackTrace();
     }
     ;
   }
 }
Exemple #18
0
  @SuppressWarnings("deprecation")
  public void run() {
    System.out.println("Inside NewStack.DynamicIP: Starting DynamicIP");
    while (true) {
      try {
        Thread.sleep(1000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }

      flag = true;
      startCheck = true;
      String localIP = detectPPP();
      if (!localIP.equals(controlIP)) {
        controlIP = localIP;
        String custodian = "";
        String[] splitInfo = controlIP.split(",");
        if (!splitInfo[0].equals("127.0.0.1")) {
          if (splitInfo[1].equals("y")) custodian = AppConfig.getProperty("User.Custodian.IP");
          else custodian = AppConfig.getProperty("User.Custodian.IP");

          try {
            Registry registry = LocateRegistry.getRegistry(custodian);

            // Changes by arvind
            if (oldIPAddressGPRS == null || (!oldIPAddressGPRS.equals(splitInfo[0]))) {
              ICustodian stub =
                  (ICustodian) registry.lookup(AppConfig.getProperty("User.Custodian.Service"));
              stub.infoIP(userId, splitInfo[0]);
              oldIPAddressGPRS = splitInfo[0];
            }

          } catch (Exception e) {
            e.printStackTrace();
            System.out.println(
                "Inside NewStack.DynamicIP: Error in locating service for Custodian");
            controlIP = "";
          }
        }
      }

      Status st = Status.getStatus();
      if (!st.executeQuery("select * from status")) {
        flag = false;
        System.out.println("Inside NewStack.DynamicIP: Nothing in Status file");
        suspend();
      }
    }
  }
Exemple #19
0
 public static void ensureLoaded(Image img) throws Exception {
   // System.err.println("In ensureloaded");
   mediatracker.addImage(img, 0);
   try {
     mediatracker.waitForAll();
     if (mediatracker.getErrorsAny() != null) {
       mediatracker.removeImage(img);
       throw new Exception("Error loading image");
     }
   } catch (InterruptedException e) {
     e.printStackTrace();
   }
   mediatracker.removeImage(img);
   // System.err.println("Out ensureloaded");
 }
Exemple #20
0
 public void start() throws UnknownHostException, IOException {
   keepGoing = true;
   serverSocket = new ServerSocket(port, 0, InetAddress.getByName("0.0.0.0"));
   while (keepGoing) {
     Socket socket = serverSocket.accept();
     try {
       ThreadPool.executor.execute(new Worker(socket));
       if (ThreadPool.executor.isShutdown()) // if its shut down, end the program
       keepGoing = false;
     } catch (InterruptedException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
     }
     if (!keepGoing) break;
   }
 }
Exemple #21
0
  public void run() {

    while (1 == 1) {

      System.out.println("Start run OneTimeTimer.bat...");
      try {
        Runtime rt = Runtime.getRuntime();
        // this.sProcess = rt.exec("GuardEternal.bat");
        this.sProcess = rt.exec("OneTimeTimer.bat");

        Process pr = this.sProcess;

        BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
        this.sProcessReader = input;

        String line = null;

        System.out.println(
            "========================= OneTimeTimer.bat Start =========================");

        while ((line = input.readLine()) != null) {
          System.out.println(line);
        }

        int exitVal = pr.waitFor();

        System.out.println(
            "========================= OneTimeTimer.bat end =========================");

      } catch (Exception e) {
        System.out.println("Execute bat failed: " + e.getMessage());
      }

      try {
        System.out.println("Sleep 10 mins");
        Thread.sleep(10 * 60 * 1000);
      } catch (InterruptedException e) {
        System.out.println("Server thread sleep(1000) failed: " + e.getMessage());
      }
    }
  }
  /** @param args */
  public static void main(String[] args) {
    String url = "rtp://192.168.1.1:22224/audio/16";

    MediaLocator mrl = new MediaLocator(url);

    // Create a player for this rtp session
    Player player = null;
    try {
      player = Manager.createPlayer(mrl);
    } catch (NoPlayerException e) {
      e.printStackTrace();
      System.exit(-1);
    } catch (MalformedURLException e) {
      e.printStackTrace();
      System.exit(-1);
    } catch (IOException e) {
      e.printStackTrace();
      System.exit(-1);
    }

    if (player != null) {
      System.out.println("Player created.");
      player.realize();
      // wait for realizing
      while (player.getState() != Controller.Realized) {
        try {
          Thread.sleep(10);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
      System.out.println("Starting player");
      player.start();
    } else {
      System.err.println("Player doesn't created.");
      System.exit(-1);
    }

    System.out.println("Exiting.");
  }
 public void run() {
   int j;
   while (true) {
     try {
       CountDownSem.acquire();
       if (title.getTurn() == 0) // 刚开始游戏,初始化题目
       {
         for (j = 0; j <= 5; j++) {
           if (!players[j].equals("虚位以待")) break;
         }
         title.setDrawer(players[j]);
         title.setId(j + 1);
         title.setTurn(1);
         title.randomkey();
         broadcast(6, title);
         broadcast(11, scores);
       }
       broadcast(2, "-------回合开始-------\n");
       timeVoid();
     } catch (InterruptedException e) {
       e.printStackTrace();
     }
   }
 }
 public void run() {
   while (true) {
     synchronized (pool) {
       while (pool.isEmpty()) {
         try {
           //                    	  System.out.print("is waiting pool ...\r\n");
           log.debug("--- waiting pool .................................\r\n");
           pool.wait();
         } catch (InterruptedException e) {
           e.printStackTrace();
           return;
         } catch (Exception e) {
           e.printStackTrace();
         }
       }
       //                 System.out.print("will doing sth and pool is removing.....!\r\n");
       log.debug("will doing sth and pool is removing.....!\r\n");
       connection = (Socket) pool.remove(0);
     }
     //            System.out.print("doing sth!\r\n");
     log.debug("doing sth!\r\n");
     handleConnection();
   }
 }
  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);
  }
  @Override
  public void onTick() {
    if (!bot.hasSpawned() || !bot.isConnected()) return;
    if (ticksToGo > 0) {
      ticksToGo--;
      return;
    }

    MainPlayerEntity player = bot.getPlayer();
    if (player == null) return;
    if (firstStart) {
      bot.say("/tpa DarkStorm_");
      ticksToGo = 15;
      firstStart = false;
      return;
    } else if (asdfasdfasdf) {
      bot.say("/warp arena");
      ticksToGo = 200;
      asdfasdfasdf = false;
      return;
    } else if (asdfasdf) {
      bot.say("/pay DarkStorm_ 1000");
      try {
        Thread.sleep(500);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      /*try {
      	PlayerInventory inventory = player.getInventory();
      	for(int i = 0; i < 44; i++) {
      		ItemStack item = inventory.getItemAt(i);
      		if(item != null) {
      			inventory.selectItemAt(i);
      			inventory.dropSelectedItem();
      		}
      	}
      } catch(Exception exception) {}*/
      bot.say("\247bai");
      asdfasdf = false;
      return;
    }
    // connectionHandler.disconnect("");
    // return;
    // } else if("".equals(""))
    // return;
    // if(player.getDistanceTo(spawn) < 7 && player.getZ() < 589.5) {
    // player.setZ(player.getZ() + 0.12);
    // bot.updateMovement();
    // } else
    // canSpam = true;

    // if(player.getDistanceTo(spawn) < 10 && player.getY() < 72) {
    // if(player.getZ() < -37.6)
    // player.setZ(player.getZ() + 0.1);
    // else if(player.getX() < 232.4)
    // player.setX(player.getX() + 0.1);
    // else
    // player.setY(player.getY() + 0.1);
    // bot.updateMovement();
    // } else if(player.getZ() > -38 && player.getZ() < -36.6
    // && player.getX() > 232 && player.getX() < 233) {
    // player.setZ(player.getZ() + 0.1);
    // bot.updateMovement();
    // } else

    // if(player.getDistanceToSquared(spawn) > 49)
    // mode = 3;
    // if(mode == 0)
    // mode = player.getZ() > 295 ? 2 : 1;
    // switch(mode) {
    // case -1:
    // canSpam = true;
    // break;
    // case 1:
    // canSpam = false;
    // if(player.getZ() < 296.3) {
    // player.setZ(player.getZ() + 0.1);
    // bot.updateMovement();
    // } else
    // mode = -1;
    // break;
    // case 2:
    // canSpam = false;
    // if(player.getZ() > 286.6) {
    // player.setZ(player.getZ() - 0.1);
    // bot.updateMovement();
    // } else
    // mode = -1;
    // break;
    // default:
    // connectionHandler.disconnect("Bad location!");
    // break;
    // }

    canSpam = true;
  }
  private DarkBotMCSpambot(
      DarkBot darkBot,
      String server,
      String username,
      String password,
      String sessionId,
      String loginProxy,
      String proxy,
      String owner) {
    synchronized (bots) {
      bots.add(this);
      // slotsTaken.incrementAndGet();
      synchronized (slotsTaken) {
        slotsTaken.notifyAll();
      }
    }
    MinecraftBotData.Builder builder = MinecraftBotData.builder();
    // botData.nickname = "";
    // for(int i = 0; i < 10; i++)
    // botData.nickname += alphas[random.nextInt(alphas.length)];
    if (proxy != null && !proxy.isEmpty()) {
      int port = 80;
      ProxyType type = ProxyType.SOCKS;
      if (proxy.contains(":")) {
        String[] parts = proxy.split(":");
        proxy = parts[0];
        port = Integer.parseInt(parts[1]);
        if (parts.length > 2) type = ProxyType.values()[Integer.parseInt(parts[2]) - 1];
      }
      builder.withSocksProxy(new ProxyData(proxy, port, type));
      this.proxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(proxy, port));
    }
    if (loginProxy != null && !loginProxy.isEmpty()) {
      int port = 80;
      if (loginProxy.contains(":")) {
        String[] parts = loginProxy.split(":");
        loginProxy = parts[0];
        port = Integer.parseInt(parts[1]);
      }
      builder.withHttpProxy(new ProxyData(loginProxy, port, ProxyType.HTTP));
      this.loginProxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(loginProxy, port));
    }
    builder.withUsername(username);
    if (sessionId != null) builder.withSessionId(sessionId);
    else builder.withPassword(password);
    if (server != null && !server.isEmpty()) {
      int port = 25565;
      if (server.contains(":")) {
        String[] parts = server.split(":");
        server = parts[0];
        port = Integer.parseInt(parts[1]);
      }
      builder.withServer(server).withPort(port);
    } else throw new IllegalArgumentException("Unknown server!");

    this.owner = owner;
    MinecraftBotData botData = builder.build();
    System.setProperty("socksProxyHost", "");
    System.setProperty("socksProxyPort", "");
    System.out.println("[" + username + "] Connecting...");
    bot = new MinecraftBot(darkBot, botData);
    bot.setMovementDisabled(true);
    connectionHandler = bot.getConnectionHandler();
    Session session = bot.getSession();
    // System.gc();
    System.out.println("[" + username + "] Done! (" + amountJoined.incrementAndGet() + ")");
    bot.getEventManager().registerListener(this);
    bot.getGameHandler().registerListener(this);

    long lastShoutTime = System.currentTimeMillis();
    while (bot.isConnected()) {
      if (die) {
        connectionHandler.sendPacket(new Packet255KickDisconnect("Goodbye"));
        return;
      }
      try {
        Thread.sleep(3000 + random.nextInt(1000));
      } catch (InterruptedException exception) {
        exception.printStackTrace();
      }
      if (!bot.hasSpawned()) continue;
      connectionHandler.sendPacket(new Packet0KeepAlive(random.nextInt()));
      if (spamMessage == null || !canSpam) continue;
      String message = spamMessage;
      if (message.contains("%skill")) message = message.replace("%skill", skills[nextSkill++]);
      if (nextSkill >= skills.length) nextSkill = 0;
      if (message.contains("%bot")) {
        synchronized (bots) {
          message =
              message.replace(
                  "%bot",
                  bots.get(nextBot > bots.size() ? (nextBot = 0) * 0 : nextBot++)
                      .bot
                      .getSession()
                      .getUsername());
        }
      }
      if (message.contains("%spamlist"))
        message = message.replace("%spamlist", spamList[nextSpamList++]);
      if (nextSpamList >= spamList.length) nextSpamList = 0;
      if (message.contains("%rnd")) {
        int length = 1;
        int index = message.indexOf("%rnd") + "%rnd".length();
        int lastIndex;
        for (lastIndex = index; lastIndex < message.length(); lastIndex++)
          if (Character.isDigit(message.charAt(lastIndex))) lastIndex++;
          else break;
        if (lastIndex > message.length()) lastIndex--;
        try {
          System.out.println(index + "," + lastIndex + "," + message.length());
          length = Integer.parseInt(message.substring(index, lastIndex));
        } catch (Exception exception) {
        }

        String randomChars = "";
        for (int i = 0; i < length; i++) randomChars += alphas[random.nextInt(alphas.length)];
        message = message.replace("%rnd", randomChars);
      }
      if (message.contains("%msg"))
        message = "/msg " + msgChars[nextMsgChar++] + " " + message.replace("%msg", "");
      if (message.contains("%ernd")) {
        message = message.replace("%ernd", "");
        int extraMessageLength = 15 + random.nextInt(6);
        message = message.substring(0, Math.min(100 - extraMessageLength, message.length())) + " [";
        extraMessageLength -= 3;
        for (int i = 0; i < extraMessageLength; i++)
          message += alphas[random.nextInt(alphas.length)];
        message += "]";
      } else message = message.substring(0, Math.min(100, message.length()));
      connectionHandler.sendPacket(new Packet3Chat(message));
    }
    synchronized (bots) {
      bots.remove(this);
    }
    amountJoined.decrementAndGet();
    slotsTaken.decrementAndGet();
    synchronized (slotsTaken) {
      slotsTaken.notifyAll();
    }
  }
Exemple #28
0
  private CIJobStatus configureJob(CIJob job, String jobType) throws PhrescoException {
    if (debugEnabled) {
      S_LOGGER.debug("Entering Method CIManagerImpl.createJob(CIJob job)");
    }
    try {
      cli = getCLI(job);
      List<String> argList = new ArrayList<String>();
      argList.add(jobType);
      argList.add(job.getName());

      String jenkinsTemplateDir = Utility.getJenkinsTemplateDir();
      String configFilePath = jenkinsTemplateDir + job.getRepoType() + HYPHEN + CONFIG_XML;
      if (debugEnabled) {
        S_LOGGER.debug("configFilePath ...  " + configFilePath);
      }

      File configFile = new File(configFilePath);
      ConfigProcessor processor = new ConfigProcessor(configFile);
      customizeNodes(processor, job);

      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      if (debugEnabled) {
        S_LOGGER.debug("argList " + argList.toString());
      }
      int result = cli.execute(argList, processor.getConfigAsStream(), System.out, baos);

      String message = "Job created successfully";
      if (result == -1) {
        byte[] byteArray = baos.toByteArray();
        message = new String(byteArray);
      }
      if (debugEnabled) {
        S_LOGGER.debug("message " + message);
      }
      // when svn is selected credential value has to set
      if (SVN.equals(job.getRepoType())) {
        setSvnCredential(job);
      }

      setMailCredential(job);
      return new CIJobStatus(result, message);
    } catch (IOException e) {
      throw new PhrescoException(e);
    } catch (JDOMException e) {
      throw new PhrescoException(e);
    } finally {
      if (cli != null) {
        try {
          cli.close();
        } catch (IOException e) {
          if (debugEnabled) {
            S_LOGGER.error(e.getLocalizedMessage());
          }
        } catch (InterruptedException e) {
          if (debugEnabled) {
            S_LOGGER.error(e.getLocalizedMessage());
          }
        }
      }
    }
  }
Exemple #29
0
  /**
   * @param args
   * @throws Exception
   */
  public static void main(String[] args) throws Exception {
    //		nextMonitor = new Object();
    monitor = new Object();

    try {
      myIP = InetAddress.getLocalHost().getHostAddress();
    } catch (UnknownHostException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    ss = new ServerSocket(serverPort);

    if (args.length == 0) {
      next = new Socket(myIP, serverPort);
    } else if (args.length == 1) {
      next = new Socket(InetAddress.getByName(args[0]), serverPort);
    } else {
      System.out.println("Usage: peer [ip address]");
      System.exit(0);
    }

    prev = ss.accept();
    nextIn = new BufferedReader(new InputStreamReader(next.getInputStream()));
    nextOut = new PrintStream(next.getOutputStream(), true);
    prevIn = new BufferedReader(new InputStreamReader(prev.getInputStream()));
    prevOut = new PrintStream(prev.getOutputStream(), true);

    nextInput = new Thread(new NextInput());
    nextInput.start();
    nextOutput = new Thread(new NextOutput());
    nextOutput.start();
    prevOutput = new Thread(new PrevOutput());
    prevOutput.start();
    connectionHandler = new Thread(new ConnectionHandler());
    connectionHandler.start();
    prevInput = new Thread(new PrevInput());
    prevInput.start();

    BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
    String userInput;
    try {

      mainloop:
      while (!quit) {
        if ((userInput = stdIn.readLine()) != null) {
          if (userInput.toLowerCase().equals("quit")) {
            quit = true;
            break mainloop;
          } else if (Peer.debug && userInput.toLowerCase().equals("debug")) {
            System.out.println("PREV: " + prev.toString());
            System.out.println("NEXT: " + next.toString());
            System.out.println("SocketQueue empty? " + socketQueue.isEmpty());
            System.out.println("ChatQueue empty? " + chatQueue.isEmpty());
            System.out.println("reconnectQueue empty? " + reconnectQueue.isEmpty());
            System.out.println("Hold = " + hold + ", prevDone = " + prevDone + ", quit = " + quit);
          } else if (Peer.debug && userInput.toLowerCase().equals("test")) {
            Peer.prevOut.println("test");
          } else {
            Peer.chatQueue.add(Peer.myIP + ": " + userInput);
          }
        }
      }
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    while (!socketQueue.isEmpty()) {
      Socket s = socketQueue.remove();
      PrevOutput.sendReconnect(s);
    }

    try {
      prevOut.println("Hold");
      Thread.sleep(2000);
    } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    while (!chatQueue.isEmpty()) {
      nextOut.println(chatQueue.remove());
    }

    prevOut.println(next.getInetAddress().getHostAddress());

    prevOut.close();
    prevIn.close();
    prev.close();

    nextOut.close();
    nextIn.close();
    next.close();

    ss.close();
  }
Exemple #30
0
    public void run() {
      String messageString;
      long lastActivity = System.currentTimeMillis();
      while (keeprunning) {
        try {
          if (in.ready()) {
            messageString = in.readLine();

            if (messageString == null) continue;
            Message m = new Message(messageString);

            if (m.getCommand().matches("\\d+"))
              try {
                int intcommand = Integer.parseInt(m.getCommand());
                if (intcommand == Constants.RPL_ENDOFMOTD) {
                  System.err.println("MOTD SEEN, must be connected.");
                  if (connected) joinChannels();
                  connected = true;
                } else if (intcommand == Constants.ERR_NICKNAMEINUSE) {
                  System.err.println("NICKNAMEINUSE");
                  namecount++;
                  BotStats.getInstance().setBotname(botdefaultname + namecount);
                  new Message("", "NICK", BotStats.getInstance().getBotname(), "").send();
                  new Message(
                          "",
                          "USER",
                          BotStats.getInstance().getBotname()
                              + " nowhere.com "
                              + BotStats.getInstance().getServername(),
                          BotStats.getInstance().getClientName()
                              + " v."
                              + BotStats.getInstance().getVersion())
                      .send();
                  System.err.println("Setting nick to:" + botdefaultname + namecount);
                }
              } catch (NumberFormatException nfe) {
                // we ignore this
                System.err.println("Unknown command:" + m.getCommand());
              }

            if (m.getCommand().equals("PING")) {
              outqueue.add(new Message("", "PONG", "", m.getTrailing()));
              if (debug) System.out.println("PUNG at " + new Date());
            } else if (BotStats.getInstance().containsIgnoreName(m.getSender())) {
              if (debug) System.out.println("Ignored: " + m);
            } else {
              inqueue.add(m); // add to inqueue
              if (debug) System.out.println(m.toString());
              // System.out.println("Inbuffer: prefix: " + m.prefix + " params: " + m.params + "
              // trailing:"
              // + m.trailing + " command:" + m.command + " sender: " + m.sender + "\n    "
              // + "isCTCP:" + m.isCTCP + " isPrivate:" + m.isPrivate + " CTCPCommand:" +
              // m.CTCPCommand
              // + " CTCPMessage:" + m.CTCPMessage);
            }

            lastActivity = System.currentTimeMillis();
          } else {
            if (System.currentTimeMillis() - lastActivity > 400000) {
              System.err.println("400 seconds since last activity! Attempting reconnect");
              in.close();
              oh.disconnect();
              keeprunning = false;
              reconnect();
              return;
            }
            sleep(100);
          }
        } catch (IOException ioe) {
          System.out.println("EOF on connection: " + ioe.getMessage());
        } catch (InterruptedException ie) {
          System.out.println("Interrupted: " + ie.getMessage());
        } catch (Exception e) {
          System.err.println("Unexpected exception in InputHandler :");
          e.printStackTrace();
        }
      }
    }