Пример #1
0
  @Test
  public void testSubmitToMemberRunnable() throws InterruptedException {
    final int k = simpleTestNodeCount;
    TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(k);
    final HazelcastInstance[] instances = factory.newInstances(new Config());
    final AtomicInteger count = new AtomicInteger(0);
    final CountDownLatch latch = new CountDownLatch(k);
    final ExecutionCallback callback =
        new ExecutionCallback() {
          public void onResponse(Object response) {
            if (response == null) {
              count.incrementAndGet();
            }
            latch.countDown();
          }

          public void onFailure(Throwable t) {}
        };
    for (int i = 0; i < k; i++) {
      final HazelcastInstance instance = instances[i];
      final IExecutorService service = instance.getExecutorService("testSubmitToMemberRunnable");
      final String script =
          "if(!hazelcast.getCluster().getLocalMember().equals(member)) "
              + "hazelcast.getAtomicLong('testSubmitToMemberRunnable').incrementAndGet();";
      final HashMap map = new HashMap();
      map.put("member", instance.getCluster().getLocalMember());
      service.submitToMember(
          new ScriptRunnable(script, map), instance.getCluster().getLocalMember(), callback);
    }
    latch.await(10, TimeUnit.SECONDS);
    assertEquals(0, instances[0].getAtomicLong("testSubmitToMemberRunnable").get());
    assertEquals(k, count.get());
  }
Пример #2
0
  @Test
  public void testSubmitToKeyOwnerCallable() throws Exception {
    final int k = simpleTestNodeCount;
    TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(k);
    final HazelcastInstance[] instances = factory.newInstances(new Config());
    final AtomicInteger count = new AtomicInteger(0);
    final CountDownLatch latch = new CountDownLatch(k / 2);
    final ExecutionCallback callback =
        new ExecutionCallback() {
          public void onResponse(Object response) {
            if ((Boolean) response) count.incrementAndGet();
            latch.countDown();
          }

          public void onFailure(Throwable t) {}
        };
    for (int i = 0; i < k; i++) {
      final HazelcastInstance instance = instances[i];
      final IExecutorService service = instance.getExecutorService("testSubmitToKeyOwnerCallable");
      final String script = "hazelcast.getCluster().getLocalMember().equals(member)";
      final HashMap map = new HashMap();
      final Member localMember = instance.getCluster().getLocalMember();
      map.put("member", localMember);
      int key = 0;
      while (!localMember.equals(instance.getPartitionService().getPartition(++key).getOwner())) ;
      if (i % 2 == 0) {
        final Future f = service.submitToKeyOwner(new ScriptCallable(script, map), key);
        assertTrue((Boolean) f.get(5, TimeUnit.SECONDS));
      } else {
        service.submitToKeyOwner(new ScriptCallable(script, map), key, callback);
      }
    }
    assertTrue(latch.await(30, TimeUnit.SECONDS));
    assertEquals(k / 2, count.get());
  }
Пример #3
0
  @Test
  public void hazelcastInstanceAwareAndLocal() throws Exception {
    final Config config = new Config();
    config.addExecutorConfig(new ExecutorConfig("test", 1));
    final HazelcastInstance instance = createHazelcastInstance(config);
    IExecutorService executor = instance.getExecutorService("test");

    HazelcastInstanceAwareRunnable task = new HazelcastInstanceAwareRunnable();
    executor.submit(task).get();
    assertTrue("The setHazelcastInstance should have been called", task.initializeCalled);
  }
 @Test
 public void testSqlPredicate() {
   HazelcastInstance h = getHazelcastInstance();
   HazelcastClient hClient = getHazelcastClient();
   IMap<Integer, Employee> map = hClient.getMap("testSqlPredicate");
   for (int i = 0; i < 100; i++) {
     h.getMap("testSqlPredicate").put(i, new Employee("" + i, i, i % 2 == 0, i));
   }
   Set<Entry<Integer, Employee>> set = map.entrySet(new SqlPredicate("active AND age < 30"));
   for (Entry<Integer, Employee> entry : set) {
     System.out.println(entry.getValue());
     assertTrue(entry.getValue().age < 30);
     assertTrue(entry.getValue().active);
   }
 }
Пример #5
0
 @SuppressWarnings("LockAcquiredButNotSafelyReleased")
 protected void handleLock(String[] args) {
   String lockStr = args[0];
   String key = args[1];
   Lock lock = hazelcast.getLock(key);
   if (lockStr.equalsIgnoreCase("lock")) {
     lock.lock();
     println("true");
   } else if (lockStr.equalsIgnoreCase("unlock")) {
     lock.unlock();
     println("true");
   } else if (lockStr.equalsIgnoreCase("trylock")) {
     String timeout = args.length > 2 ? args[2] : null;
     if (timeout == null) {
       println(lock.tryLock());
     } else {
       long time = Long.valueOf(timeout);
       try {
         println(lock.tryLock(time, TimeUnit.SECONDS));
       } catch (InterruptedException e) {
         e.printStackTrace();
       }
     }
   }
 }
 @Test
 public void testDisablingSystemLogs() throws Exception {
   Config config = new Config();
   config.setProperty(GroupProperties.PROP_SYSTEM_LOG_ENABLED, "true");
   config.getGroupConfig().setName("testDisablingSystemLogs");
   HazelcastInstance instance = Hazelcast.newHazelcastInstance(config);
   HazelcastInstance instance2 = Hazelcast.newHazelcastInstance(config);
   instance.getMap("map").put("key", "value");
   Node node = TestUtil.getNode(instance);
   assertTrue(node.getSystemLogService().getLogBundle().size() > 0);
   Hazelcast.shutdownAll();
   config.setProperty(GroupProperties.PROP_SYSTEM_LOG_ENABLED, "false");
   instance = Hazelcast.newHazelcastInstance(config);
   instance2 = Hazelcast.newHazelcastInstance(config);
   instance.getMap("map").put("key2", "value2");
   assertTrue(node.getSystemLogService().getLogBundle().size() == 0);
 }
Пример #7
0
  @Test
  public void testManagedContextAndLocal() throws Exception {
    final Config config = new Config();
    config.addExecutorConfig(new ExecutorConfig("test", 1));
    config.setManagedContext(
        new ManagedContext() {
          @Override
          public Object initialize(Object obj) {
            if (obj instanceof RunnableWithManagedContext) {
              RunnableWithManagedContext task = (RunnableWithManagedContext) obj;
              task.initializeCalled = true;
            }
            return obj;
          }
        });

    final HazelcastInstance instance = createHazelcastInstance(config);
    IExecutorService executor = instance.getExecutorService("test");

    RunnableWithManagedContext task = new RunnableWithManagedContext();
    executor.submit(task).get();
    assertTrue(
        "The task should have been initialized by the ManagedContext", task.initializeCalled);
  }
Пример #8
0
 protected void handlePartitions(String[] args) {
   Set<Partition> partitions = hazelcast.getPartitionService().getPartitions();
   Map<Member, Integer> partitionCounts = new HashMap<Member, Integer>();
   for (Partition partition : partitions) {
     Member owner = partition.getOwner();
     if (owner != null) {
       Integer count = partitionCounts.get(owner);
       int newCount = 1;
       if (count != null) {
         newCount = count + 1;
       }
       partitionCounts.put(owner, newCount);
     }
     println(partition);
   }
   Set<Map.Entry<Member, Integer>> entries = partitionCounts.entrySet();
   for (Map.Entry<Member, Integer> entry : entries) {
     println(entry.getKey() + ":" + entry.getValue());
   }
 }
Пример #9
0
 public IAtomicLong getAtomicNumber() {
   atomicNumber = hazelcast.getAtomicLong(namespace);
   return atomicNumber;
 }
Пример #10
0
 private IExecutorService createSingleNodeExecutorService(String name, int poolSize) {
   final Config config = new Config();
   config.addExecutorConfig(new ExecutorConfig(name, poolSize));
   final HazelcastInstance instance = createHazelcastInstance(config);
   return instance.getExecutorService(name);
 }
Пример #11
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");
    }
  }
Пример #12
0
 @Override
 public void setHazelcastInstance(HazelcastInstance hazelcastInstance) {
   localMember = hazelcastInstance.getCluster().getLocalMember();
 }
Пример #13
0
 protected void handleInstances(String[] args) {
   Collection<DistributedObject> distributedObjects = hazelcast.getDistributedObjects();
   for (DistributedObject distributedObject : distributedObjects) {
     println(distributedObject);
   }
 }
Пример #14
0
 public String call() throws Exception {
   Future future = instance.getExecutorService("NestedExecutorTask").submit(new BasicTestTask());
   return (String) future.get();
 }
Пример #15
0
 public IList<Object> getList() {
   //        if (list == null) {
   list = hazelcast.getList(namespace);
   //        }
   return list;
 }
Пример #16
0
 public ISet<Object> getSet() {
   //        if (set == null) {
   set = hazelcast.getSet(namespace);
   //        }
   return set;
 }
Пример #17
0
 public IQueue<Object> getQueue() {
   //        if (queue == null) {
   queue = hazelcast.getQueue(namespace);
   //        }
   return queue;
 }
Пример #18
0
 public IMap<Object, Object> getMap() {
   //        if (map == null) {
   map = hazelcast.getMap(namespace);
   //        }
   return map;
 }
Пример #19
0
 public ITopic<Object> getTopic() {
   //        if (topic == null) {
   topic = hazelcast.getTopic(namespace);
   //        }
   return topic;
 }