Beispiel #1
0
  /*
   * Launches against the agent
   */
  public void testSimpleLauncher() throws Exception {
    Project project = workspace.getProject("p1");
    Run bndrun = new Run(workspace, project.getBase(), project.getFile("one.bndrun"));
    bndrun.setProperty("-runpath", "biz.aQute.remote.launcher");
    bndrun.setProperty("-runbundles", "bsn-1,bsn-2");
    bndrun.setProperty("-runremote", "test");

    final RemoteProjectLauncherPlugin pl =
        (RemoteProjectLauncherPlugin) bndrun.getProjectLauncher();
    pl.prepare();
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicInteger exitCode = new AtomicInteger(-1);

    List<? extends RunSession> sessions = pl.getRunSessions();
    assertEquals(1, sessions.size());

    final RunSession session = sessions.get(0);

    Thread t =
        new Thread("test-launch") {
          public void run() {
            try {
              exitCode.set(session.launch());
            } catch (Exception e) {
              e.printStackTrace();
            } finally {
              latch.countDown();
            }
          }
        };
    t.start();
    Thread.sleep(500);

    for (Bundle b : context.getBundles()) {
      System.out.println(b.getLocation());
    }
    assertEquals(4, context.getBundles().length);
    String p1 = t1.getAbsolutePath();
    System.out.println(p1);

    assertNotNull(context.getBundle(p1));
    assertNotNull(context.getBundle(t2.getAbsolutePath()));

    pl.cancel();
    latch.await();

    assertEquals(-3, exitCode.get());

    bndrun.close();
  }
 void put(final URI uri, ArtifactData data) throws Exception {
   reporter.trace("put %s %s", uri, data);
   File tmp = createTempFile(repoDir, "mtp", ".whatever");
   tmp.deleteOnExit();
   try {
     copy(uri.toURL(), tmp);
     byte[] sha = SHA1.digest(tmp).digest();
     reporter.trace("SHA %s %s", uri, Hex.toHexString(sha));
     ArtifactData existing = get(sha);
     if (existing != null) {
       reporter.trace("existing");
       xcopy(existing, data);
       return;
     }
     File meta = new File(repoDir, Hex.toHexString(sha) + ".json");
     File file = new File(repoDir, Hex.toHexString(sha));
     rename(tmp, file);
     reporter.trace("file %s", file);
     data.file = file.getAbsolutePath();
     data.sha = sha;
     data.busy = false;
     CommandData cmddata = parseCommandData(data);
     if (cmddata.bsn != null) {
       data.name = cmddata.bsn + "-" + cmddata.version;
     } else data.name = Strings.display(cmddata.title, cmddata.bsn, cmddata.name, uri);
     codec.enc().to(meta).put(data);
     reporter.trace("TD = " + data);
   } finally {
     tmp.delete();
     reporter.trace("puted %s %s", uri, data);
   }
 }
Beispiel #3
0
  @Override
  protected void setUp() throws Exception {
    tmp = IO.getFile("generated/tmp");
    tmp.mkdirs();
    IO.copy(IO.getFile("testdata/ws"), tmp);
    workspace = Workspace.getWorkspace(tmp);
    workspace.refresh();

    InfoRepository repo = workspace.getPlugin(InfoRepository.class);
    t1 = create("bsn-1", new Version(1, 0, 0));
    t2 = create("bsn-2", new Version(1, 0, 0));

    repo.put(new FileInputStream(t1), null);
    repo.put(new FileInputStream(t2), null);
    t1 = repo.get("bsn-1", new Version(1, 0, 0), null);
    t2 = repo.get("bsn-2", new Version(1, 0, 0), null);
    repo.put(new FileInputStream(IO.getFile("generated/biz.aQute.remote.launcher.jar")), null);

    workspace.getPlugins().add(repo);

    File storage = IO.getFile("generated/storage-1");
    storage.mkdirs();

    configuration = new HashMap<String, Object>();
    configuration.put(
        Constants.FRAMEWORK_STORAGE_CLEAN, Constants.FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT);
    configuration.put(Constants.FRAMEWORK_STORAGE, storage.getAbsolutePath());

    configuration.put(
        Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, "org.osgi.framework.launch;version=1.2");

    framework = new org.apache.felix.framework.FrameworkFactory().newFramework(configuration);
    framework.init();
    framework.start();
    context = framework.getBundleContext();
    location = "reference:" + IO.getFile("generated/biz.aQute.remote.agent.jar").toURI().toString();
    agent = context.installBundle(location);
    agent.start();

    thread =
        new Thread() {
          @Override
          public void run() {
            try {
              Main.main(
                  new String[] {
                    "-s", "generated/storage", "-c", "generated/cache", "-p", "1090", "-et"
                  });
            } catch (Exception e) {
              e.printStackTrace();
            }
          }
        };
    thread.setDaemon(true);
    thread.start();

    super.setUp();
  }
Beispiel #4
0
  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    String filePickerResult = "";
    if (data != null && resultCode == RESULT_OK) {
      try {
        ContentResolver cr = getContentResolver();
        Uri uri = data.getData();
        Cursor cursor =
            GeckoApp.mAppContext
                .getContentResolver()
                .query(uri, new String[] {OpenableColumns.DISPLAY_NAME}, null, null, null);
        String name = null;
        if (cursor != null) {
          try {
            if (cursor.moveToNext()) {
              name = cursor.getString(0);
            }
          } finally {
            cursor.close();
          }
        }
        String fileName = "tmp_";
        String fileExt = null;
        int period;
        if (name == null || (period = name.lastIndexOf('.')) == -1) {
          String mimeType = cr.getType(uri);
          fileExt = "." + GeckoAppShell.getExtensionFromMimeType(mimeType);
        } else {
          fileExt = name.substring(period);
          fileName = name.substring(0, period);
        }
        File file = File.createTempFile(fileName, fileExt, sGREDir);

        FileOutputStream fos = new FileOutputStream(file);
        InputStream is = cr.openInputStream(uri);
        byte[] buf = new byte[4096];
        int len = is.read(buf);
        while (len != -1) {
          fos.write(buf, 0, len);
          len = is.read(buf);
        }
        fos.close();
        filePickerResult = file.getAbsolutePath();
      } catch (Exception e) {
        Log.e(LOG_FILE_NAME, "showing file picker", e);
      }
    }
    try {
      mFilePickerResult.put(filePickerResult);
    } catch (InterruptedException e) {
      Log.i(LOG_FILE_NAME, "error returning file picker result", e);
    }
  }
  /**
   * @param data
   * @param target
   * @throws Exception
   * @throws IOException
   */
  public String createService(ServiceData data) throws Exception, IOException {

    File sdir = new File(serviceDir, data.name);
    if (!sdir.exists() && !sdir.mkdirs()) {
      throw new IOException("Could not create directory " + data.sdir);
    }
    data.sdir = sdir.getAbsolutePath();

    File lock = new File(data.sdir, LOCK);
    data.lock = lock.getAbsolutePath();

    if (data.work == null) data.work = new File(data.sdir, "work").getAbsolutePath();
    if (data.user == null) data.user = platform.user();

    if (data.user == null) data.user = "******";

    new File(data.work).mkdir();

    if (data.log == null) data.log = new File(data.sdir, "log").getAbsolutePath();

    // TODO
    // if (Data.validate(data) != null)
    // return "Invalid service data: " + Data.validate(data);

    if (service == null)
      throw new RuntimeException(
          "Missing biz.aQute.jpm.service in repo, should have been installed by init, try reiniting");

    data.serviceLib = service.getAbsolutePath();

    platform.chown(data.user, true, new File(data.sdir));

    String s = platform.createService(data, null, false);
    if (s == null) storeData(new File(data.sdir, "data"), data);
    return s;
  }
  /**
   * @param data
   * @param target
   * @throws Exception
   * @throws IOException
   */
  public String createCommand(CommandData data, boolean force) throws Exception, IOException {

    // TODO
    // if (Data.validate(data) != null)
    // return "Invalid command data: " + Data.validate(data);

    Map<String, String> map = null;
    if (data.trace) {
      map = new HashMap<String, String>();
      map.put("java.security.manager", "aQute.jpm.service.TraceSecurityManager");
      reporter.trace("tracing");
    }
    String s = platform.createCommand(data, map, force, service.getAbsolutePath());
    if (s == null) storeData(new File(commandDir, data.name), data);
    return s;
  }
  /**
   * Starts new grid node.
   *
   * @param gridName name of new node.
   * @param springCfg file with spring configuration to use for this node.
   * @return a grid instance local to new node {@link GridGain#start(GridConfiguration)}.
   * @throws Exception if node run failed.
   */
  protected Grid startNode(String gridName, File springCfg) throws Exception {
    assert springCfg != null;

    ListableBeanFactory springCtx =
        new FileSystemXmlApplicationContext("file:///" + springCfg.getAbsolutePath());

    Map cfgMap = springCtx.getBeansOfType(GridConfiguration.class);

    assert cfgMap != null;
    assert !cfgMap.isEmpty();

    GridConfiguration cfg = (GridConfiguration) cfgMap.values().iterator().next();

    cfg.setGridName(gridName + "-" + getNextNodeNum());

    return G.start(cfg);
  }
Beispiel #8
0
  /**
   * Returns the adapter type for the given file. Will first use the adapter selector function if it
   * was specified in init.js, otherwise will use the static type (either set in _init file, as a
   * server-wide override in 10gen.properties, or default of DIRECT_10GEN)
   *
   * @param file to produce type for
   * @return adapter type for the specified file
   */
  public AdapterType getAdapterType(File file) {

    // Q : I think this is the right thing to do
    if (inScopeSetup()) {
      return AdapterType.DIRECT_10GEN;
    }

    /*
     * cheap hack - prevent any _init.* file from getting run as anythign but DIRECT_10GEN
     */

    if (file != null && file.getName().indexOf("_init.") != -1) {
      return AdapterType.DIRECT_10GEN;
    }

    if (_adapterSelector == null) {
      return _staticAdapterType;
    }

    /*
     *  only let the app select type if file is part of application (i.e.
     *  don't do it for corejs, core modules, etc...
     */

    String fp = file.getAbsolutePath();
    String fullRoot = _rootFile.getAbsolutePath(); // there must be a nicer way to do this?

    if (!fp.startsWith(fullRoot)) {
      return AdapterType.DIRECT_10GEN;
    }

    Object o = _adapterSelector.call(_initScope, new JSString(fp.substring(fullRoot.length())));

    if (o == null) {
      return _staticAdapterType;
    }

    if (!(o instanceof JSString)) {
      log("Error : adapter selector not returning string.  Ignoring and using static adapter type");
      return _staticAdapterType;
    }

    AdapterType t = getAdapterTypeFromString(o.toString());

    return (t == null ? _staticAdapterType : t);
  }
  public ArtifactData get(byte[] sha) throws Exception {
    String name = Hex.toHexString(sha);
    File data = IO.getFile(repoDir, name + ".json");
    reporter.trace("artifact data file %s", data);
    if (data.isFile()) { // Bin + metadata
      ArtifactData artifact = codec.dec().from(data).get(ArtifactData.class);
      artifact.file = IO.getFile(repoDir, name).getAbsolutePath();
      return artifact;
    }
    File bin = IO.getFile(repoDir, name);
    if (bin.exists()) { // Only bin
      ArtifactData artifact = new ArtifactData();
      artifact.file = bin.getAbsolutePath();
      artifact.sha = sha;
      return artifact;
    }

    return null;
  }
Beispiel #10
0
  protected void handleCommand(String command) {
    if (command.contains("__")) {
      namespace = command.split("__")[0];
      command = command.substring(command.indexOf("__") + 2);
    }

    if (echo) {
      if (Thread.currentThread().getName().toLowerCase().indexOf("main") < 0)
        println(" [" + Thread.currentThread().getName() + "] " + command);
      else println(command);
    }
    if (command == null || command.startsWith("//")) return;
    command = command.trim();
    if (command == null || command.length() == 0) {
      return;
    }
    String first = command;
    int spaceIndex = command.indexOf(' ');
    String[] argsSplit = command.split(" ");
    String[] args = new String[argsSplit.length];
    for (int i = 0; i < argsSplit.length; i++) {
      args[i] = argsSplit[i].trim();
    }
    if (spaceIndex != -1) {
      first = args[0];
    }
    if (command.startsWith("help")) {
      handleHelp(command);
    } else if (first.startsWith("#") && first.length() > 1) {
      int repeat = Integer.parseInt(first.substring(1));
      long t0 = Clock.currentTimeMillis();
      for (int i = 0; i < repeat; i++) {
        handleCommand(command.substring(first.length()).replaceAll("\\$i", "" + i));
      }
      println("ops/s = " + repeat * 1000 / (Clock.currentTimeMillis() - t0));
      return;
    } else if (first.startsWith("&") && first.length() > 1) {
      final int fork = Integer.parseInt(first.substring(1));
      ExecutorService pool = Executors.newFixedThreadPool(fork);
      final String threadCommand = command.substring(first.length());
      for (int i = 0; i < fork; i++) {
        final int threadID = i;
        pool.submit(
            new Runnable() {
              public void run() {
                String command = threadCommand;
                String[] threadArgs = command.replaceAll("\\$t", "" + threadID).trim().split(" ");
                // TODO &t #4 m.putmany x k
                if ("m.putmany".equals(threadArgs[0]) || "m.removemany".equals(threadArgs[0])) {
                  if (threadArgs.length < 4) {
                    command += " " + Integer.parseInt(threadArgs[1]) * threadID;
                  }
                }
                handleCommand(command);
              }
            });
      }
      pool.shutdown();
      try {
        pool.awaitTermination(60 * 60, TimeUnit.SECONDS); // wait 1h
      } catch (Exception e) {
        e.printStackTrace();
      }
    } else if (first.startsWith("@")) {
      if (first.length() == 1) {
        println("usage: @<file-name>");
        return;
      }
      File f = new File(first.substring(1));
      println("Executing script file " + f.getAbsolutePath());
      if (f.exists()) {
        try {
          BufferedReader br = new BufferedReader(new FileReader(f));
          String l = br.readLine();
          while (l != null) {
            handleCommand(l);
            l = br.readLine();
          }
          br.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      } else {
        println("File not found! " + f.getAbsolutePath());
      }
    } else if (command.indexOf(';') != -1) {
      StringTokenizer st = new StringTokenizer(command, ";");
      while (st.hasMoreTokens()) {
        handleCommand(st.nextToken());
      }
      return;
    } else if ("silent".equals(first)) {
      silent = Boolean.parseBoolean(args[1]);
    } else if ("shutdown".equals(first)) {
      hazelcast.getLifecycleService().shutdown();
    } else if ("echo".equals(first)) {
      echo = Boolean.parseBoolean(args[1]);
      println("echo: " + echo);
    } else if ("ns".equals(first)) {
      if (args.length > 1) {
        namespace = args[1];
        println("namespace: " + namespace);
        //                init();
      }
    } else if ("whoami".equals(first)) {
      println(hazelcast.getCluster().getLocalMember());
    } else if ("who".equals(first)) {
      println(hazelcast.getCluster());
    } else if ("jvm".equals(first)) {
      System.gc();
      println("Memory max: " + Runtime.getRuntime().maxMemory() / 1024 / 1024 + "M");
      println(
          "Memory free: "
              + Runtime.getRuntime().freeMemory() / 1024 / 1024
              + "M "
              + (int) (Runtime.getRuntime().freeMemory() * 100 / Runtime.getRuntime().maxMemory())
              + "%");
      long total = Runtime.getRuntime().totalMemory();
      long free = Runtime.getRuntime().freeMemory();
      println("Used Memory:" + ((total - free) / 1024 / 1024) + "MB");
      println("# procs: " + Runtime.getRuntime().availableProcessors());
      println(
          "OS info: "
              + ManagementFactory.getOperatingSystemMXBean().getArch()
              + " "
              + ManagementFactory.getOperatingSystemMXBean().getName()
              + " "
              + ManagementFactory.getOperatingSystemMXBean().getVersion());
      println(
          "JVM: "
              + ManagementFactory.getRuntimeMXBean().getVmVendor()
              + " "
              + ManagementFactory.getRuntimeMXBean().getVmName()
              + " "
              + ManagementFactory.getRuntimeMXBean().getVmVersion());
    } else if (first.indexOf("ock") != -1 && first.indexOf(".") == -1) {
      handleLock(args);
    } else if (first.indexOf(".size") != -1) {
      handleSize(args);
    } else if (first.indexOf(".clear") != -1) {
      handleClear(args);
    } else if (first.indexOf(".destroy") != -1) {
      handleDestroy(args);
    } else if (first.indexOf(".iterator") != -1) {
      handleIterator(args);
    } else if (first.indexOf(".contains") != -1) {
      handleContains(args);
    } else if (first.indexOf(".stats") != -1) {
      handStats(args);
    } else if ("t.publish".equals(first)) {
      handleTopicPublish(args);
    } else if ("q.offer".equals(first)) {
      handleQOffer(args);
    } else if ("q.take".equals(first)) {
      handleQTake(args);
    } else if ("q.poll".equals(first)) {
      handleQPoll(args);
    } else if ("q.peek".equals(first)) {
      handleQPeek(args);
    } else if ("q.capacity".equals(first)) {
      handleQCapacity(args);
    } else if ("q.offermany".equals(first)) {
      handleQOfferMany(args);
    } else if ("q.pollmany".equals(first)) {
      handleQPollMany(args);
    } else if ("s.add".equals(first)) {
      handleSetAdd(args);
    } else if ("s.remove".equals(first)) {
      handleSetRemove(args);
    } else if ("s.addmany".equals(first)) {
      handleSetAddMany(args);
    } else if ("s.removemany".equals(first)) {
      handleSetRemoveMany(args);
    } else if (first.equals("m.replace")) {
      handleMapReplace(args);
    } else if (first.equalsIgnoreCase("m.putIfAbsent")) {
      handleMapPutIfAbsent(args);
    } else if (first.equals("m.putAsync")) {
      handleMapPutAsync(args);
    } else if (first.equals("m.getAsync")) {
      handleMapGetAsync(args);
    } else if (first.equals("m.put")) {
      handleMapPut(args);
    } else if (first.equals("m.get")) {
      handleMapGet(args);
    } else if (first.equalsIgnoreCase("m.getMapEntry")) {
      handleMapGetMapEntry(args);
    } else if (first.equals("m.remove")) {
      handleMapRemove(args);
    } else if (first.equals("m.evict")) {
      handleMapEvict(args);
    } else if (first.equals("m.putmany") || first.equalsIgnoreCase("m.putAll")) {
      handleMapPutMany(args);
    } else if (first.equals("m.getmany")) {
      handleMapGetMany(args);
    } else if (first.equals("m.removemany")) {
      handleMapRemoveMany(args);
    } else if (command.equalsIgnoreCase("m.localKeys")) {
      handleMapLocalKeys();
    } else if (command.equals("m.keys")) {
      handleMapKeys();
    } else if (command.equals("m.values")) {
      handleMapValues();
    } else if (command.equals("m.entries")) {
      handleMapEntries();
    } else if (first.equals("m.lock")) {
      handleMapLock(args);
    } else if (first.equalsIgnoreCase("m.tryLock")) {
      handleMapTryLock(args);
    } else if (first.equals("m.unlock")) {
      handleMapUnlock(args);
    } else if (first.indexOf(".addListener") != -1) {
      handleAddListener(args);
    } else if (first.equals("m.removeMapListener")) {
      handleRemoveListener(args);
    } else if (first.equals("m.unlock")) {
      handleMapUnlock(args);
    } else if (first.equals("l.add")) {
      handleListAdd(args);
    } else if (first.equals("l.set")) {
      handleListSet(args);
    } else if ("l.addmany".equals(first)) {
      handleListAddMany(args);
    } else if (first.equals("l.remove")) {
      handleListRemove(args);
    } else if (first.equals("l.contains")) {
      handleListContains(args);
    } else if ("a.get".equals(first)) {
      handleAtomicNumberGet(args);
    } else if ("a.set".equals(first)) {
      handleAtomicNumberSet(args);
    } else if ("a.inc".equals(first)) {
      handleAtomicNumberInc(args);
    } else if ("a.dec".equals(first)) {
      handleAtomicNumberDec(args);
      //        } else if (first.equals("execute")) {
      //            execute(args);
    } else if (first.equals("partitions")) {
      handlePartitions(args);
      //        } else if (first.equals("txn")) {
      //            hazelcast.getTransaction().begin();
      //        } else if (first.equals("commit")) {
      //            hazelcast.getTransaction().commit();
      //        } else if (first.equals("rollback")) {
      //            hazelcast.getTransaction().rollback();
      //        } else if (first.equalsIgnoreCase("executeOnKey")) {
      //            executeOnKey(args);
      //        } else if (first.equalsIgnoreCase("executeOnMember")) {
      //            executeOnMember(args);
      //        } else if (first.equalsIgnoreCase("executeOnMembers")) {
      //            executeOnMembers(args);
      //        } else if (first.equalsIgnoreCase("longOther") ||
      // first.equalsIgnoreCase("executeLongOther")) {
      //            executeLongTaskOnOtherMember(args);
      //        } else if (first.equalsIgnoreCase("long") || first.equalsIgnoreCase("executeLong"))
      // {
      //            executeLong(args);
    } else if (first.equalsIgnoreCase("instances")) {
      handleInstances(args);
    } else if (first.equalsIgnoreCase("quit") || first.equalsIgnoreCase("exit")) {
      System.exit(0);
    } else {
      println("type 'help' for help");
    }
  }