static void nashornCompiledScript(String code) throws ScriptException, NoSuchMethodException {
    ScriptEngineManager factory = new ScriptEngineManager();
    ScriptEngine engine = factory.getEngineByName("nashorn");

    CompiledScript compiled = ((Compilable) engine).compile(code);

    Object result = null;
    ScriptContext context = new SimpleScriptContext();
    Bindings engineScope = context.getBindings(ScriptContext.ENGINE_SCOPE);
    long total = 0;
    for (int i = 0; i < RUNS; ++i) {
      long start = System.nanoTime();
      for (int j = 0; j < BATCH; ++j) {
        engineScope.put("value", "12345678");
        result = compiled.eval(context);
      }
      long stop = System.nanoTime();
      System.out.println(
          "Run "
              + (i * BATCH + 1)
              + "-"
              + ((i + 1) * BATCH)
              + ": "
              + Math.round((stop - start) / BATCH / 1000)
              + " us");
      total += (stop - start);
    }

    System.out.println("Average run: " + Math.round(total / RUNS / BATCH / 1000) + " us");
    System.out.println(
        "Data is " + ((Invocable) engine).invokeMethod(result, "toString").toString());
  }
Ejemplo n.º 2
1
  public static void main(String[] args) {
    // Script Engine instantiation using ServiceProvider - this will
    // look in the classpath for a file
    //  /META-INF/services/javax.script.ScriptEngineFactory
    // where the AbclScriptEngineFactory is registered
    ScriptEngine lispEngine = new ScriptEngineManager().getEngineByExtension("lisp");

    // Alternatively, you can directly instantiate the script engine:

    // ScriptEngineManager scriptManager = new ScriptEngineManager();
    // scriptManager.registerEngineExtension("lisp", new AbclScriptEngineFactory());
    // ScriptEngine lispEngine = scriptManager.getEngineByExtension("lisp");

    // (thanks to Peter Tsenter for suggesting this)

    // Accessing variables
    System.out.println();
    System.out.println("*package* = " + lispEngine.get("*package*"));
    Object someValue = new Object();
    lispEngine.put("someVariable", someValue);
    System.out.println("someVariable = " + lispEngine.get("someVariable"));
    try {
      // Interpretation (also from streams)
      lispEngine.eval("(defun hello (arg) (print (list arg someVariable)) (terpri))");

      // Direct function invocation
      ((Invocable) lispEngine).invokeFunction("hello", "world");

      // Implementing a Java interface in Lisp
      lispEngine.eval("(defun compare-to (&rest args) 42)");
      Comparable c = ((Invocable) lispEngine).getInterface(java.lang.Comparable.class);
      System.out.println("compareTo: " + c.compareTo(null));

      // Compilation!
      lispEngine.eval(
          "(defmacro slow-compiling-macro (arg) (dotimes (i 1000000) (incf i)) `(print ,arg))");

      long millis = System.currentTimeMillis();
      lispEngine.eval("(slow-compiling-macro 42)");
      millis = System.currentTimeMillis() - millis;
      System.out.println("interpretation took " + millis);

      millis = System.currentTimeMillis();
      CompiledScript cs = ((Compilable) lispEngine).compile("(slow-compiling-macro 42)");
      millis = System.currentTimeMillis() - millis;
      System.out.println("compilation took " + millis);

      millis = System.currentTimeMillis();
      cs.eval();
      millis = System.currentTimeMillis() - millis;
      System.out.println("evaluation took " + millis);

      millis = System.currentTimeMillis();
      cs.eval();
      millis = System.currentTimeMillis() - millis;
      System.out.println("evaluation took " + millis);

      // Ecc. ecc.
    } catch (NoSuchMethodException e) {
      e.printStackTrace();
    } catch (ScriptException e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 3
0
  public ScriptExecutor(ScriptExecutionRequest request) {
    this.request = request;

    ScriptEngineManager factory = new ScriptEngineManager();
    engine = factory.getEngineByName(request.format);

    engine.put("output", request.output);

    /** */
    if (request.script == null || request.script.equals("") == true) {

      /** Default root is the the resource folder of the current project. */
      String root = "src/main/resources/library/";
      if (System.getProperty("hbird.scriptlibrary") != null) {
        root = System.getProperty("hbird.scriptlibrary");
        if (root.endsWith("/") == false) {
          root += "/";
        }
      }

      File file = new File(root + request.name + ".js");
      if (file.exists() == false) {
        LOG.error("Failed to find script file '" + file.getAbsolutePath() + "'.");
        LOG.error(
            "Use the runtime system property '-Dhbird.scriptlibrary=[path]' to point to the script library. Script will not be evaluated.");
      } else {
        try {
          request.script = FileUtils.readFileToString(file);
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }
  static void nashornCompiledScriptReturningFunction(String code, String library)
      throws ScriptException, NoSuchMethodException {
    ScriptEngineManager factory = new ScriptEngineManager();
    ScriptEngine engine = factory.getEngineByName("nashorn");

    ScriptContext libraryContext = new SimpleScriptContext();
    ScriptContext privateContext = new SimpleScriptContext();

    ScriptObjectMirror errorFunc =
        (ScriptObjectMirror) ((Compilable) engine).compile(library).eval(libraryContext);
    ScriptObjectMirror func =
        (ScriptObjectMirror) ((Compilable) engine).compile(code).eval(privateContext);
    Object result = null;

    long total = 0;
    for (int i = 0; i < RUNS; ++i) {
      long start = System.nanoTime();
      for (int j = 0; j < BATCH; ++j) {
        result = func.call(null, "12345678", errorFunc);
      }
      long stop = System.nanoTime();
      System.out.println(
          "Run "
              + (i * BATCH + 1)
              + "-"
              + ((i + 1) * BATCH)
              + ": "
              + Math.round((stop - start) / BATCH / 1000)
              + " us");
      total += (stop - start);
    }

    System.out.println("Average run: " + Math.round(total / RUNS / BATCH / 1000) + " us");
    System.out.println("Data is " + result.toString());
  }
  static void nashornInvokeMethod(String code) throws ScriptException, NoSuchMethodException {
    ScriptEngineManager factory = new ScriptEngineManager();
    ScriptEngine engine = factory.getEngineByName("nashorn");

    engine.eval(code);
    Invocable inv = (Invocable) engine;
    JSObject propertiesDict = (JSObject) engine.get("properties");

    Object result = null;
    Object property;
    long total = 0;
    for (int i = 0; i < RUNS; ++i) {
      long start = System.nanoTime();
      for (int j = 0; j < BATCH; ++j) {
        property = propertiesDict.getMember("ssn");
        result = inv.invokeMethod(property, "clean", "12345678");
      }
      long stop = System.nanoTime();
      System.out.println(
          "Run "
              + (i * BATCH + 1)
              + "-"
              + ((i + 1) * BATCH)
              + ": "
              + Math.round((stop - start) / BATCH / 1000)
              + " us");
      total += (stop - start);
    }
    System.out.println("Average run: " + Math.round(total / RUNS / BATCH / 1000) + " us");
    System.out.println(
        "Data is " + ((Invocable) engine).invokeMethod(result, "toString").toString());
  }
  public void run(String arg) {
    ImageWindow iw = WindowManager.getCurrentWindow();
    pw = jutils.getPW4SelCopy(iw);
    String title = pw.getTitle();
    float[][] yvals = pw.getYValues();
    float[][] xvals = pw.getXValues();
    int length = yvals[0].length;
    if (pw.getShowErrors()) errs = pw.getErrors(0, false);
    int[] colors = pw.getColors();
    colors[0] = 0;
    ScriptEngineManager manager = new ScriptEngineManager();
    engine = manager.getEngineByName("js");
    ce = (Compilable) engine;
    // hitcounter=0;

    c2 = 0.0f;
    iterations = 0;
    checkc2 = false;

    double[] stats = new double[3];
    tempx = new float[length];
    tempdata = new float[length];
    System.arraycopy(xvals[0], 0, tempx, 0, length);
    System.arraycopy(yvals[0], 0, tempdata, 0, length);
    pw.addPoints(tempx, new float[tempx.length], false);
    series = pw.getNpts().length - 1;
    double[] params = new double[10];
    int[] fixes = {0, 0, 0, 1, 1, 1, 1, 1, 1, 1};
    init_options(params, fixes);
    if (!init_functions()) {
      return;
    }

    while (showoptions(params, fixes)) {
      NLLSfit_v2 fitclass;
      if (checkc2) {
        fitclass = new NLLSfit_v2(this, 0);
      } else {
        fitclass = new NLLSfit_v2(this, 0.0001, 50, 0.1);
      }
      float[] fit = fitclass.fitdata(params, fixes, constraints, yvals[0], weights, stats, true);
      pw.updateSeries(fit, series, false);
      c2 = (float) stats[1];
      iterations = (int) stats[0];
    }

    IJ.log("Chi Squared = " + (float) stats[1]);
    IJ.log("Iterations = " + (int) stats[0]);
    for (int i = 0; i < 10; i++) {
      IJ.log("P" + (i + 1) + " = " + (float) params[i] + " fixed = " + fixes[i]);
    }
    IJ.log("AIC = " + (float) stats[2]);
    // IJ.log("hits = "+hitcounter);
    set_options(params, fixes);
  }
Ejemplo n.º 7
0
 public static void logInit(boolean force) throws IOException {
   if (!IsLogInitialized || force) {
     LogManager.getLogManager()
         .readConfiguration(
             LibRt.class.getClassLoader().getResourceAsStream("cfg.logging.properties"));
     String logFile = System.getProperty("CfgLog");
     if (logFile != null) {
       LogManager.getLogManager().readConfiguration(new FileInputStream(logFile));
     }
     try {
       LogLvlMax = Integer.parseInt(System.getProperty("LogLvlMax", LogLvlMax + ""));
     } catch (Exception ex) {
     }
     ; // XXX: mostrar mensaje?
   }
 }
  private void initPlayers() {
    File file = new File(File.pathSeparator);
    System.out.println(file.getAbsolutePath());

    OgreXMLParser loader = new OgreXMLParser();
    try {
      model =
          loader.loadModel(
              "src/animated_objects/Cube.mesh.xml",
              "src/animated_objects/chicken.material",
              "src/animated_objects/Cube.skeleton.xml");
      model.updateGeometricState(0, true);
      java.util.Iterator<SceneNode> modelIterator = model.iterator();
      player1 = (Model3DTriMesh) modelIterator.next();
    } catch (Exception e) {
      e.printStackTrace();
      System.exit(1);
    }

    Texture chickenTexture = TextureManager.loadTexture2D("src/animated_objects/green_chicken.jpg");
    chickenTexture.setApplyMode(sage.texture.Texture.ApplyMode.Replace);
    chickenTextureState =
        (TextureState) display.getRenderer().createRenderState(RenderState.RenderStateType.Texture);
    chickenTextureState.setTexture(chickenTexture, 0);
    chickenTextureState.setEnabled(true);
    player1.setRenderState(chickenTextureState);
    player1.updateRenderStates();

    player =
        physicsEngine.addSphereObject(
            physicsEngine.nextUID(), ballMass, player1.getWorldTransform().getValues(), 1.0f);
    player.setBounciness(0.0f);
    player1.setPhysicsObject(player);
    player1.scale(.35f, .35f, .35f);
    addGameWorldObject(player1);
    // player1.translate(133f, 13f, 123f);
    playerInitM = new Matrix3D();
    playerInitM.concatenate((Matrix3D) player1.getLocalTranslation().clone());
    playerInitM.concatenate((Matrix3D) player1.getLocalRotation().clone());
    playerInitM.concatenate((Matrix3D) player1.getLocalScale().clone());

    camera1 = new JOGLCamera(renderer);
    camera1.setPerspectiveFrustum(60, 1, 1, 1000);
    camera1.setViewport(0.0, 1.0, 0.0, 1);
  }
Ejemplo n.º 9
0
 public static void main(String[] args) throws Exception {
   System.out.println("\nTest7\n");
   File file = new File(System.getProperty("test.src", "."), "Test7.js");
   Reader r = new FileReader(file);
   ScriptEngineManager m = new ScriptEngineManager();
   ScriptEngine eng = Helper.getJsEngine(m);
   if (eng == null) {
     System.out.println("Warning: No js engine found; test vacuously passes.");
     return;
   }
   eng.put("filename", file.getAbsolutePath());
   eng.eval(r);
   String str = (String) eng.get("firstLine");
   // do not change first line in Test7.js -- we check it here!
   if (!str.equals("//this is the first line of Test7.js")) {
     throw new RuntimeException("unexpected first line");
   }
 }
Ejemplo n.º 10
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> 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);
  }
Ejemplo n.º 11
0
  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();
    }
  }
Ejemplo n.º 12
0
public class LibRt {
  public static String CfgEncodingDflt =
      "ISO-8859-1"; // U: si no especificamos, un archivo a string se lee con este encoding

  public static final Logger logger = Logger.getLogger("rt");
  public static final String EOL = "\n";
  public static final int BUFF_SZ = 8192;

  public static java.util.Hashtable state =
      new java.util
          .Hashtable(); // U: accesible desde javascript para mantener estado entre llamadas AUNQUE
                        // los scripts se ejecuten de cero en cada thread

  public static boolean IsLogInitialized = false;

  public static void logInit(boolean force) throws IOException {
    if (!IsLogInitialized || force) {
      LogManager.getLogManager()
          .readConfiguration(
              LibRt.class.getClassLoader().getResourceAsStream("cfg.logging.properties"));
      String logFile = System.getProperty("CfgLog");
      if (logFile != null) {
        LogManager.getLogManager().readConfiguration(new FileInputStream(logFile));
      }
      try {
        LogLvlMax = Integer.parseInt(System.getProperty("LogLvlMax", LogLvlMax + ""));
      } catch (Exception ex) {
      }
      ; // XXX: mostrar mensaje?
    }
  }

  // Primitiva de log
  public static int LogLvlMax = 9; // DFLT

  public static void logm(String t, int lvl, String msg, Object o) {
    // System.out.println("LOG:" + t + ":" + lvl + ":" + msg + ":" + (o != null ? ser_json(o) :
    // ""));
    if (lvl <= LogLvlMax) {
      logger.info(t + ":" + lvl + ":" + msg + ":" + (o != null ? ser_json(o) : ""));
    }
  }

  public static void logmex(String t, int lvl, String msg, Object o, Exception ex) {
    StringBuilder sb = new StringBuilder();
    StackTraceElement se[] = ex.getStackTrace();
    for (int i = 0; i < se.length; i++) {
      sb.append(se[i].getMethodName() + "@" + se[i].getFileName() + "@" + se[i].getLineNumber());
      sb.append(" > ");
    }
    logm(t, lvl, msg + " EXCEPTION " + ex + " " + sb.toString(), o);
  }

  // ***************************************************************************
  // S: enc/base64

  public static String enc_base64(String data) throws UnsupportedEncodingException {
    return enc_base64(data.getBytes("UTF-8"));
  }

  public static String enc_base64(byte[] data) throws UnsupportedEncodingException {
    return DatatypeConverter.printBase64Binary(data);
  }

  public static String enc_base64_r_str(String encoded) throws UnsupportedEncodingException {
    return new String(enc_base64_r(encoded), "UTF-8");
  }

  public static byte[] enc_base64_r(String encoded) throws UnsupportedEncodingException {
    return DatatypeConverter.parseBase64Binary(encoded);
  }

  // ***************************************************************************
  // S: ser/json
  static final Gson gson = new Gson(); // A: encapsulamos
  // XXX: mejor usar Jackson? cual usan otros proyectos de EM? Por que?

  public static String ser_json(Object o) {
    String s = "";
    try {
      s = gson.toJson(o);
    } catch (Exception ex) {
      s = o + "";
    }
    return s;
  }

  // ***************************************************************************
  // S: ser/csv

  public static int serRsCsvToFile(
      ResultSet resultset, String[] columnNames, String path, int maxRows, String separator) {
    Writer writer;
    try {
      writer = fileWriter(path);
    } catch (UnsupportedEncodingException e) {
      logm("ERR", 0, "FILE WRITER CSV OUTPUT OPEN unsupported encondig", path);
      return -1;
    } catch (FileNotFoundException e) {
      logm("ERR", 0, "FILE WRITER CSV OUTPUT OPEN file not found", path);
      return -1;
    } catch (IOException e) {
      logm("ERR", 0, "FILE WRITER CSV OUTPUT OPEN file not found", path);
      return -1;
    }
    // A: writer escribe en el archivo especificado
    return serRsCsvToWriter(resultset, columnNames, writer, maxRows, separator);
  }

  public static int serDiccCsvToWriter(String str, String path, int maxRows, String separator) {
    Writer writer;
    try {
      writer = fileWriterAppend(path, false, null);
      logm("DBG", 9, "ABRE WRITER", null);
    } catch (UnsupportedEncodingException e) {
      logm("ERR", 0, "FILE WRITER CSV OUTPUT OPEN unsupported encondig", path);
      return -1;
    } catch (FileNotFoundException e) {
      logm("ERR", 0, "FILE WRITER CSV OUTPUT OPEN file not found", path);
      return -1;
    } catch (IOException e) {
      logm("ERR", 0, "FILE WRITER CSV OUTPUT OPEN file not found", path);
      return -1;
    }
    // A: writer escribe en el archivo especificado
    return serDiccCsvToWriter(str, writer, maxRows, separator);
  }

  public static String[] dbRsColumnNames(ResultSet resultset) throws SQLException {
    java.util.Vector<String> rv = new java.util.Vector<String>();
    if (resultset != null) {
      logm("DBG", 9, "ColumnCount=0 Calculando cantidad columnas desde metadata", null);
      ResultSetMetaData md = resultset.getMetaData();
      int columnCount = md.getColumnCount();
      logm("DBG", 9, "ColumnCount", columnCount);
      for (int i = 1; i <= columnCount; i++) {
        rv.add(md.getColumnName(i).toLowerCase());
      }
    }
    String[] r = rv.toArray(new String[0]);
    logm("DBG", 9, "DB dbRsColumnNames", r);
    return r;
  }

  public static int serRsCsvToWriter(
      ResultSet resultset, String[] columnNames, Writer writer, int maxRows, String separator) {
    int counter = 0;
    if (resultset != null) {
      if (columnNames == null) {
        try {
          logm("NFO", 9, "CSV titulos, obteniendo desde metadata", null);
          columnNames = dbRsColumnNames(resultset);
        } catch (SQLException e) {
          logmex("ERR", 1, "CSV titulos, obteniendo desde metadata", null, e);
          return -1;
        }
      }
      logm("DBG", 7, "CSV titulos", columnNames);
      // A: columnCount tiene el valor especificado o el default

      int columnCount = columnNames.length;
      // Itero el resultset escribiendo el output
      try {
        // XXX:OPCION escape separator si aparece en un valor?

        logm("DBG", 4, "ESCRIBIENDO ARCHIVO", resultset);

        for (int i = 0; i < columnCount - 1; i++) {
          logm("DBG", 9, "ESCRIBE COL: ", columnNames[i]);
          writer.write(columnNames[i]);
          writer.write(separator);
        }

        writer.write(columnNames[columnCount - 1]);
        writer.write(EOL);

        logm("DBG", 4, "SE ESCRIBIO LINEA DE COLUMNAS", null);
        logm("DBG", 4, "COUNTER", counter);
        logm("DBG", 4, "MAXROWS", maxRows);
        // A: escribi los nombres de las columnas

        boolean hasNext = resultset.next();

        logm("DBG", 4, "NEXT", hasNext);

        while ((counter < maxRows || maxRows < 0) && hasNext) {

          logm("DBG", 4, "Escribiendo fila :", counter);

          String buf;
          for (int i = 1; i < columnCount; i++) {

            if ((buf = resultset.getString(i)) != null) {
              writer.write(buf);
            }

            logm("DBG", 9, "STR", buf);

            writer.write(separator);
          }
          if ((buf = resultset.getString(columnCount)) != null) {
            writer.write(buf);
          }

          logm("DBG", 9, "STR", buf);

          writer.write(EOL);
          counter++;
          // XXX:loguear un cartelito ej. cada 1000
          hasNext = resultset.next();
        }

        logm("DBG", 2, "termino de escribir lineas", null);

      } catch (SQLException s) {
        logmex("ERR", 0, "DB leyendo resultset para CSV", null, s);
        return -1;
      } catch (IOException e) {
        logmex("ERR", 0, "FILE WRITER CSV OUTPUT writing", null, e);
        return -1;
      }
    } else {
      logm("NFO", 3, "DB FILE CSV RESULTSET IS NULL, was expected?", null);
    }
    try {
      writer.close();
    } catch (IOException e) {
      logmex("ERR", 0, "FILE WRITER CSV OUTPUT closing", null, e);
      return -1;
    }
    return counter;
  }

  @SuppressWarnings("unchecked")
  public static int serDiccCsvToWriter(String csv, Writer writer, int maxRows, String separator) {
    int counter = 0;

    if (csv != null) {
      try {
        writer.write(csv);
        writer.write(EOL);

      } catch (IOException e) {
        logmex("ERR", 0, "FILE WRITER CSV OUTPUT writing", null, e);
        return -1;
      }
    } else {
      logm("NFO", 3, "DB FILE CSV RESULTSET IS NULL, was expected?", null);
    }

    return counter;
  }

  public static int serDiccGroupByToWriter(
      ResultSet rs,
      Writer writer,
      int maxRows,
      String idPor,
      String[] idAcumulados,
      String campoAcumuladoNombre) {
    int rowsCount = 0;

    try {

      ArrayList<String> acumulado = null;
      String idActual = null;
      StringBuilder reg = null;
      reg = new StringBuilder();
      String value = "";

      if (rs != null) {
        ResultSetMetaData rsm = rs.getMetaData();
        int countCol = rsm.getColumnCount();
        String name = "";
        for (int i = 1; i <= countCol; i++) {
          name = rsm.getColumnName(i);
          reg.append(name.toLowerCase()).append("\t");
        }
        reg.append(campoAcumuladoNombre);

        writer.write(reg.toString() + EOL);

        while (rs.next()) {
          if (idActual == null) {
            reg = new StringBuilder();
            acumulado = new ArrayList<String>();
            idActual = rs.getString(idPor);

            for (int i = 1; i <= countCol; i++) {
              reg.append(rs.getString(i)).append("\t");
            }

            for (String id : idAcumulados) {
              value = rs.getString(id);
              if (!rs.wasNull()) {
                acumulado.add(rs.getString(id));
              }
            }

          } else {

            if (idActual.equals(rs.getString(idPor))) {
              for (String id : idAcumulados) {
                value = rs.getString(id);
                if (!rs.wasNull()) {
                  acumulado.add(rs.getString(id));
                }
              }
            } else {
              if (acumulado.size() > 0) {
                for (String str : acumulado) {
                  reg.append(str).append(",");
                }
                reg.deleteCharAt(reg.length() - 1);
              }
              reg.append(EOL);

              writer.write(reg.toString());
              rowsCount++;
              if (maxRows == rowsCount) {
                break;
              }

              idActual = rs.getString(idPor);
              reg = new StringBuilder();
              acumulado = new ArrayList<String>();

              for (int i = 1; i <= countCol; i++) {
                reg.append(rs.getString(i)).append("\t");
              }

              for (String id : idAcumulados) {
                value = rs.getString(id);
                if (!rs.wasNull()) {
                  acumulado.add(rs.getString(id));
                }
              }
            }
          }
        }

        if (acumulado.size() > 0) {
          for (String str : acumulado) {
            reg.append(str).append(",");
          }
          reg.deleteCharAt(reg.length() - 1);
        }
        reg.append(EOL);

        writer.write(reg.toString());
        rowsCount++;
      }
    } catch (SQLException e) {
      logm("ERR", 1, "Error al escribir registros", e);
    } catch (IOException e) {
      logm("ERR", 1, "Error al escribir registros", e);
    }
    return rowsCount;
  }

  public static void closeWriterAppend(Writer writer) {
    try {
      writer.close();
    } catch (IOException e) {
      logmex("ERR", 0, "FILE WRITER CSV OUTPUT closing", null, e);
    }
  }

  // ***************************************************************************
  // S: db
  public static int dbRsColumnCount(ResultSet rs) throws SQLException {
    return rs.getMetaData().getColumnCount();
  }

  // ***************************************************************************
  // S: digest
  public static MessageDigest digestCalc(String algorithm) throws NoSuchAlgorithmException {
    return MessageDigest.getInstance(algorithm);
  }

  public static String digestHexStr(MessageDigest digestCalc) {
    return (new HexBinaryAdapter()).marshal(digestCalc.digest());
  }

  public static String digest(String data, String algorithm) throws NoSuchAlgorithmException {
    MessageDigest calc = digestCalc(algorithm);
    calc.update(data.getBytes());
    return digestHexStr(calc);
  }

  // ***************************************************************************
  // S: file
  public static Writer fileWriter(String path)
      throws UnsupportedEncodingException, FileNotFoundException, IOException {
    return fileWriter(path, false, null);
  }

  public static Writer fileWriter(String path, boolean zip, MessageDigest digestCalc)
      throws UnsupportedEncodingException, FileNotFoundException, IOException {
    return streamWriter(new FileOutputStream(path), zip, digestCalc);
  }

  public static Writer fileWriterAppend(String path, boolean zip, MessageDigest digestCalc)
      throws UnsupportedEncodingException, FileNotFoundException, IOException {
    return streamWriter(new FileOutputStream(path, true), zip, digestCalc);
  }

  public static OutputStream streamForOutput_file(
      String path, boolean zip, MessageDigest digestCalc)
      throws UnsupportedEncodingException, FileNotFoundException, IOException {
    return streamForOutput(new FileOutputStream(path), zip, digestCalc);
  }

  public static OutputStream streamForOutput(OutputStream os, boolean zip, MessageDigest digestCalc)
      throws UnsupportedEncodingException, FileNotFoundException, IOException {
    OutputStream dos = digestCalc != null ? new DigestOutputStream(os, digestCalc) : os;
    OutputStream zos = zip ? new GZIPOutputStream(dos) : dos;
    return zos;
  }

  public static Writer streamWriter(OutputStream os, boolean zip, MessageDigest digestCalc)
      throws UnsupportedEncodingException, FileNotFoundException, IOException {
    return new BufferedWriter(
        new OutputStreamWriter(streamForOutput(os, zip, digestCalc), "utf-8"));
  }

  public static InputStream streamForInput_file(String path, boolean zip, MessageDigest digestCalc)
      throws UnsupportedEncodingException, FileNotFoundException, IOException {
    return streamForInput(new FileInputStream(path), zip, digestCalc);
  }

  public static Reader fileReader(String path, boolean zip, MessageDigest digestCalc)
      throws UnsupportedEncodingException, FileNotFoundException, IOException {
    return streamReader(new FileInputStream(path), zip, digestCalc);
  }

  public static InputStream streamForInput(InputStream fis, boolean zip, MessageDigest digestCalc)
      throws UnsupportedEncodingException, FileNotFoundException, IOException {
    InputStream dis = digestCalc != null ? new DigestInputStream(fis, digestCalc) : fis;
    InputStream zis = zip ? new GZIPInputStream(dis) : dis;
    return zis;
  }

  public static Reader streamReader(InputStream fis, boolean zip, MessageDigest digestCalc)
      throws UnsupportedEncodingException, FileNotFoundException, IOException {
    return new BufferedReader(
        new InputStreamReader(streamForInput(fis, zip, digestCalc))); // , "utf-8"));
  }

  public static int pipe_stream(InputStream is, OutputStream os, boolean wantsKeepOpen)
      throws IOException { // U: copia de un stream al otro
    int cnt = 0;
    int n;
    byte[] buffer = new byte[BUFF_SZ];
    while ((n = is.read(buffer)) > -1) {
      cnt += n;
      os.write(buffer, 0, n);
    }
    if (!wantsKeepOpen) {
      is.close();
      os.close();
    }
    return cnt;
  }

  public static String get_stream(Reader isr) throws IOException {
    char[] buffer = new char[BUFF_SZ];
    StringBuilder out = new StringBuilder();
    logm("DBG", 9, "STREAM GET", isr + "");
    for (; ; ) {
      int rsz = isr.read(buffer, 0, buffer.length);
      logm("DBG", 9, "STREAM GET READ", rsz);
      if (rsz < 0) break;
      out.append(buffer, 0, rsz);
    }
    String s = out.toString();
    logm("DBG", 9, "STREAM GET RESULT", s);
    return s;
  }

  public static String get_stream(InputStream is) throws IOException {
    return get_stream(is, CfgEncodingDflt);
  }

  public static String get_stream(InputStream is, String encoding) throws IOException {
    if (encoding == null) {
      encoding = CfgEncodingDflt;
    }
    byte[] buffer = new byte[BUFF_SZ];
    StringBuilder out = new StringBuilder();
    logm("DBG", 9, "STREAM GET", is + "");
    for (; ; ) {
      int rsz = is.read(buffer, 0, buffer.length);
      logm("DBG", 9, "STREAM GET READ", rsz);
      if (rsz < 0) break;
      out.append(new String(buffer, 0, rsz, encoding));
    }
    String s = out.toString();
    logm("DBG", 9, "STREAM GET RESULT", s);
    return s;
  }

  public static void set_stream(OutputStream os, String data, String encoding) throws IOException {
    os.write(data.getBytes(encoding));
    os.close();
  }

  public static void set_stream(Writer os, String data) throws IOException {
    os.write(data);
    os.close();
  }

  public static String get_file(
      String path, boolean gzip, MessageDigest digestCalc, String encoding)
      throws UnsupportedEncodingException, IOException {
    try {
      return get_stream(streamForInput_file(path, gzip, digestCalc));
    } catch (FileNotFoundException ex) {
      return "";
    }
  }

  public static String get_resource(String path) throws IOException {
    java.io.InputStream srcs = null;
    try {
      srcs = LibRt.class.getResourceAsStream(path);
      return get_stream(srcs);
    } catch (IOException ex) {
      LibRt.logmex("DBG", 9, "RT GET_RESOURCE", path, ex);
      throw (ex);
    }
  }

  public static String get_resourceOrFile(
      String path, boolean gzip, MessageDigest digestCalc, String encoding)
      throws UnsupportedEncodingException, IOException {
    try {
      return get_resource(path);
    } catch (IOException ex) {
      return get_file(path, gzip, digestCalc, encoding);
    }
  }

  public static void set_file(
      String path, String data, boolean gzip, MessageDigest digestCalc, String encoding)
      throws UnsupportedEncodingException, IOException {
    set_stream(streamForOutput_file(path, gzip, digestCalc), data, CfgEncodingDflt);
  }

  public static String[] get_filelist(String path, boolean nodirs, boolean nofiles) {
    File folder = new File(path);
    if (folder.isDirectory()) {
      File[] listOfFiles = folder.listFiles();
      java.util.Vector<String> r = new java.util.Vector<String>();
      for (int i = 0; listOfFiles != null && i < listOfFiles.length; i++) {
        if ((listOfFiles[i].isFile() && !nofiles) || (listOfFiles[i].isDirectory() && !nodirs)) {
          r.add(listOfFiles[i].getName());
        }
      }
      return r.toArray(new String[0]);
    } else {
      return null; // A: no existe o no es directorio
    }
  }

  public static FileLock lock_file(String path) throws IOException, FileNotFoundException {
    RandomAccessFile file = new RandomAccessFile(path, "rw");
    FileChannel fileChannel = file.getChannel();
    return fileChannel.tryLock();
  }

  public static boolean unlock_file(FileLock fileLock) throws IOException, FileNotFoundException {
    if (fileLock != null) {
      fileLock.release();
      return true;
    }
    return false;
  }

  public static String temp_filePath(String namePattern, String ext)
      throws IOException, FileNotFoundException {
    File temp = File.createTempFile("temp-file-name", ".tmp");
    return temp.getAbsolutePath();
  }

  // ***************************************************************************
  // S File: scp = copiar sobre ssh
  public static void set_file_scp(
      String srcFilePath,
      String dstUrl,
      String dstFilePath,
      String dstUser,
      String dstPass,
      String keyFilePath)
      throws SshException {
    // SEE:
    // http://code.google.com/p/securechannelfacade/source/browse/trunk/src/main/java/org/rev6/scf/SshConnection.java?r=12
    SshConnection sshCx = null;
    String[] nameAndPort = dstUrl.split(":");
    int dstPort = nameAndPort.length > 1 ? Integer.parseInt(nameAndPort[1]) : 22;
    try {
      if (keyFilePath == null) {
        sshCx = new SshConnection(nameAndPort[0], dstUser, dstPass);
        logm(
            "DBG",
            7,
            "NET SSH CONNECT TO {HOST: '"
                + nameAndPort[0]
                + "', PORT:"
                + dstPort
                + ", USER:'******', auth: '"
                + "pass"
                + "'}",
            null);
      } else {
        sshCx = new SshConnection(nameAndPort[0], dstUser, new File(keyFilePath));
        logm(
            "DBG",
            7,
            "NET SSH CONNECT TO {HOST: '"
                + nameAndPort[0]
                + "', PORT:"
                + dstPort
                + ", USER:'******', auth: 'key', keyfile: '"
                + keyFilePath
                + "'}",
            null);
      }

      sshCx.setPort(dstPort);
      sshCx.connect();
      ScpFile scpFile = new ScpFile(new File(srcFilePath), dstFilePath);
      sshCx.executeTask(new ScpUpload(scpFile));
    } finally {
      if (sshCx != null) {
        sshCx.disconnect();
      }
    }
  }

  public static void set_file_scp_pass(
      String srcFilePath, String dstUrl, String dstFilePath, String dstUser, String dstPass)
      throws SshException {
    set_file_scp(srcFilePath, dstUrl, dstFilePath, dstUser, dstPass, null);
  }

  public static void set_file_scp_key(
      String srcFilePath, String dstUrl, String dstFilePath, String dstUser, String keyFilePath)
      throws SshException {
    set_file_scp(srcFilePath, dstUrl, dstFilePath, dstUser, null, keyFilePath);
  }

  // ***************************************************************************
  // S: net/http
  public static HttpURLConnection httpCx(String url, String method, String usr, String pass)
      throws MalformedURLException, IOException, ProtocolException {
    // NB:https requiere HAVA_HOME para encontrar los certificados!
    URL obj = new URL(url);
    HttpURLConnection cx = (HttpURLConnection) obj.openConnection();
    cx.setRequestMethod(method);
    if (usr != "") {
      String basicAuth = "Basic " + new String(enc_base64(usr + ":" + pass));
      cx.setRequestProperty("Authorization", basicAuth);
    }
    // A: parameters set

    return cx;
  }

  public static void httpWrite(HttpURLConnection cx, String data)
      throws IOException, ProtocolException {
    cx.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(cx.getOutputStream());
    wr.writeBytes(data);
    wr.flush();
    wr.close();
  }

  public static String httpRead(HttpURLConnection cx)
      throws UnsupportedEncodingException, IOException {
    // int responseCode = con.getResponseCode();
    return get_stream(cx.getInputStream());
  }

  public static String get_http(String url, String method, String data, String usr, String pass)
      throws IOException, ProtocolException, UnsupportedEncodingException {
    HttpURLConnection cx = httpCx(url, method, usr, pass);
    if (data != null) {
      httpWrite(cx, data);
    }
    return httpRead(cx);
  }

  // ****************************************************************************
  // S: Javascript
  public static LibRtJs JsImpl =
      System.getProperty("jsImpl", "RHINO").equals("JDK") ? new LibRtJsJdk() : new LibRtJsRhino();

  public static LibRtJs jsEval(String js, String srcDesc, LibRtJs jsEnv, String[] args)
      throws Exception {
    logm("DBG", 9, "RT JS EVAL START PATH=" + srcDesc + " SRC", js);
    return JsImpl.jsEval(js, srcDesc, jsEnv, args);
  }

  public static Object jsCall(String funName, LibRtJs jsEnv, Object[] args)
      throws IOException, Exception {
    logm("DBG", 5, "RT JS CALL TRY", funName);
    return JsImpl.jsCall(funName, jsEnv, args);
  }

  public static LibRtJs jsLoad(String path, LibRtJs jsEnv, String[] args)
      throws IOException, Exception {
    logm("DBG", 5, "RT JS LOAD TRY", path);
    return JsImpl.jsLoad(path, jsEnv, args);
  }

  public static LibRtJs jsLoadAlone(
      String path,
      Hashtable<String, Object>
          env) { // U: ejecutar un script en un contexto separado (no comparte variables salvo las
                 // que le pasemos en el hashtable)
    return JsImpl.jsLoadAlone(path, env);
  }

  // ****************************************************************************
  // S: paths

  public static String runtimePath()
      throws java.net.URISyntaxException,
          java.net.MalformedURLException { // U: para cargar librerias y assets, etc.
    // SEE: http://stackoverflow.com/questions/320542/how-to-get-the-path-of-a-running-jar-file
    URL url = LibRt.class.getResource(LibRt.class.getSimpleName() + ".class");
    logm("DBG", 1, "RT runtimePath URL", url);
    URL urlOk = (url.getProtocol() == "jar" ? new URL(url.getPath()) : url);
    logm("DBG", 1, "RT runtimePath URL OK", urlOk);
    return new File(urlOk.toURI()).getParentFile().getPath();
  }

  // ****************************************************************************
  // S: main
  public static void init() throws Exception {
    logInit(false);
  }

  public static void main(String[] args) throws Exception {
    init();
    String mainPath = args.length > 0 ? args[0] : "0inicio.js";
    try {
      jsLoad("librt.js", null, args);
      jsLoad(mainPath, null, args);
    } catch (Exception ex) {
      ex.printStackTrace();
      logmex("ERR", 1, "RT RUNNING SCRIPTS", null, ex);
    }
  }

  private static Class<?> getClassFromJar(String pathToJar, String pkg, String classToGet)
      throws IOException, ClassNotFoundException, SecurityException, InstantiationException,
          IllegalAccessException, NoSuchMethodException, IllegalArgumentException,
          InvocationTargetException {

    JarFile jarFile = new JarFile(pathToJar);
    Enumeration e = jarFile.entries();

    URL[] urls = {new URL("jar:file:" + pathToJar + "!/")};
    ClassLoader cl = URLClassLoader.newInstance(urls);

    Class<?> c = Class.forName(pkg + "." + classToGet, true, cl);

    return c;
  }

  public static void executeMethodClass(
      String pathToJar,
      String pkg,
      String classToGet,
      String methodName,
      String pathToFile,
      long logIdSyncMin,
      long logIdSyncMax)
      throws IOException, ClassNotFoundException, SecurityException, InstantiationException,
          IllegalAccessException, NoSuchMethodException, IllegalArgumentException,
          InvocationTargetException {
    Class<?> c = getClassFromJar(pathToJar, pkg, classToGet);
    Method method = c.getDeclaredMethod(methodName, String.class, long.class, long.class);
    method.invoke(null, pathToFile, logIdSyncMin, logIdSyncMax);
  }
}