/**
   * Checks that gets work for implicit txs.
   *
   * @param cache Cache to test.
   * @throws Exception If failed.
   */
  private void checkExplicitTx(Ignite ignite, IgniteCache<String, String> cache) throws Exception {
    IgniteCache<String, String> asyncCache = cache.withAsync();

    Transaction tx = ignite.transactions().txStart();

    try {
      assertNull(cache.get("key1"));

      tx.commit();
    } finally {
      tx.close();
    }

    tx = ignite.transactions().txStart();

    try {
      asyncCache.get("key2");

      assertNull(asyncCache.future().get());

      tx.commit();
    } finally {
      tx.close();
    }

    tx = ignite.transactions().txStart();

    try {
      assertTrue(cache.getAll(F.asSet("key3", "key4")).isEmpty());

      tx.commit();
    } finally {
      tx.close();
    }

    tx = ignite.transactions().txStart();

    try {
      asyncCache.getAll(F.asSet("key5", "key6"));

      assertTrue(((Map) asyncCache.future().get()).isEmpty());

      tx.commit();
    } finally {
      tx.close();
    }

    tx = ignite.transactions().txStart();

    try {
      cache.put("key7", "key7");

      cache.remove("key7");

      assertNull(cache.get("key7"));

      tx.commit();
    } finally {
      tx.close();
    }

    checkEmpty(cache);
  }
Ejemplo n.º 2
0
  /**
   * @param ignite Ignite.
   * @param range Time range in milliseconds.
   */
  private static void populateCacheEmployee(Ignite ignite, long range) {
    if (log.isDebugEnabled()) log.debug("DEMO: Start employees population with data...");

    IgniteCache<Integer, Country> cacheCountry = ignite.cache(COUNTRY_CACHE_NAME);

    for (int i = 0, n = 1; i < CNTR_CNT; i++, n++)
      cacheCountry.put(i, new Country(i, "Country #" + n, n * 10000000));

    IgniteCache<Integer, Department> cacheDepartment = ignite.cache(DEPARTMENT_CACHE_NAME);

    IgniteCache<Integer, Employee> cacheEmployee = ignite.cache(EMPLOYEE_CACHE_NAME);

    for (int i = 0, n = 1; i < DEP_CNT; i++, n++) {
      cacheDepartment.put(i, new Department(n, rnd.nextInt(CNTR_CNT), "Department #" + n));

      double r = rnd.nextDouble();

      cacheEmployee.put(
          i,
          new Employee(
              i,
              rnd.nextInt(DEP_CNT),
              null,
              "First name manager #" + n,
              "Last name manager #" + n,
              "Email manager #" + n,
              "Phone number manager #" + n,
              new java.sql.Date((long) (r * range)),
              "Job manager #" + n,
              1000 + round(r * 4000, 2)));
    }

    for (int i = 0, n = 1; i < EMPL_CNT; i++, n++) {
      Integer depId = rnd.nextInt(DEP_CNT);

      double r = rnd.nextDouble();

      cacheEmployee.put(
          i,
          new Employee(
              i,
              depId,
              depId,
              "First name employee #" + n,
              "Last name employee #" + n,
              "Email employee #" + n,
              "Phone number employee #" + n,
              new java.sql.Date((long) (r * range)),
              "Job employee #" + n,
              500 + round(r * 2000, 2)));
    }

    if (log.isDebugEnabled()) log.debug("DEMO: Finished employees population.");
  }
Ejemplo n.º 3
0
  /** @param ignite Ignite. */
  private static void populateCacheCar(Ignite ignite) {
    if (log.isDebugEnabled()) log.debug("DEMO: Start cars population...");

    IgniteCache<Integer, Parking> cacheParking = ignite.cache(PARKING_CACHE_NAME);

    for (int i = 0, n = 1; i < PARK_CNT; i++, n++)
      cacheParking.put(i, new Parking(i, "Parking #" + n, n * 10));

    IgniteCache<Integer, Car> cacheCar = ignite.cache(CAR_CACHE_NAME);

    for (int i = 0, n = 1; i < CAR_CNT; i++, n++)
      cacheCar.put(i, new Car(i, rnd.nextInt(PARK_CNT), "Car #" + n));

    if (log.isDebugEnabled()) log.debug("DEMO: Finished cars population.");
  }
  /**
   * Tests offset and limit clauses for query.
   *
   * @throws Exception If failed.
   */
  public void testOffsetLimit() throws Exception {
    IgniteCache<Integer, Integer> c =
        ignite(0).getOrCreateCache(cacheConfig("ints", true, Integer.class, Integer.class));

    try {
      List<Integer> res = new ArrayList<>();

      Random rnd = new GridRandom();

      for (int i = 0; i < 10; i++) {
        int val = rnd.nextInt(100);

        c.put(i, val);
        res.add(val);
      }

      Collections.sort(res);

      String qry = "select _val from Integer order by _val ";

      assertEqualsCollections(res, columnQuery(c, qry));
      assertEqualsCollections(res.subList(0, 0), columnQuery(c, qry + "limit ?", 0));
      assertEqualsCollections(res.subList(0, 3), columnQuery(c, qry + "limit ?", 3));
      assertEqualsCollections(res.subList(0, 9), columnQuery(c, qry + "limit ? offset ?", 9, 0));
      assertEqualsCollections(res.subList(3, 7), columnQuery(c, qry + "limit ? offset ?", 4, 3));
      assertEqualsCollections(res.subList(7, 9), columnQuery(c, qry + "limit ? offset ?", 2, 7));
      assertEqualsCollections(res.subList(8, 10), columnQuery(c, qry + "limit ? offset ?", 2, 8));
      assertEqualsCollections(res.subList(9, 10), columnQuery(c, qry + "limit ? offset ?", 1, 9));
      assertEqualsCollections(res.subList(10, 10), columnQuery(c, qry + "limit ? offset ?", 1, 10));
      assertEqualsCollections(
          res.subList(9, 10), columnQuery(c, qry + "limit ? offset abs(-(4 + ?))", 1, 5));
    } finally {
      c.destroy();
    }
  }
  /**
   * Execute individual put and get, getting value in portable format, without de-serializing it.
   *
   * @param cache Cache.
   */
  private static void putGetPortable(IgniteCache<Integer, Organization> cache) {
    // Create new Organization portable object to store in cache.
    Organization org =
        new Organization(
            "Microsoft", // Name.
            new Address("1096 Eddy Street, San Francisco, CA", 94109), // Address.
            OrganizationType.PRIVATE, // Type.
            new Timestamp(System.currentTimeMillis())); // Last update time.

    // Put created data entry to cache.
    cache.put(1, org);

    // Get cache that will get values as portable objects.
    IgniteCache<Integer, PortableObject> portableCache = cache.withKeepPortable();

    // Get recently created organization as a portable object.
    PortableObject po = portableCache.get(1);

    // Get organization's name from portable object (note that
    // object doesn't need to be fully deserialized).
    String name = po.field("name");

    System.out.println();
    System.out.println(">>> Retrieved organization name from portable object: " + name);
  }
Ejemplo n.º 6
0
  /** {@inheritDoc} */
  @Override
  protected void beforeTestsStarted() throws Exception {
    startGridsMultiThreaded(3);

    IgniteCache<Integer, TestObject> cache = grid(0).cache(null);

    assert cache != null;

    TestObject o = createObjectWithData(1);

    cache.put(1, o);
    cache.put(2, new TestObject(2));
    cache.put(3, new TestObject(3));

    Class.forName("org.apache.ignite.IgniteJdbcDriver");
  }
  /** @throws Exception In case of error. */
  public void testPutWithExpiration() throws Exception {
    IgniteCache<String, String> cache1 = ignite1.cache(null);
    IgniteCache<String, String> cache2 = ignite2.cache(null);
    IgniteCache<String, String> cache3 = ignite3.cache(null);

    cache1.put("key", "val");

    Transaction tx = ignite1.transactions().txStart();

    long ttl = 500;

    cache1
        .withExpiryPolicy(new TouchedExpiryPolicy(new Duration(MILLISECONDS, ttl)))
        .put("key", "val");

    assert cache1.get("key") != null;

    tx.commit();

    info("Going to sleep for: " + (ttl + 1000));

    // Allow for expiration.
    Thread.sleep(ttl + 1000);

    String v1 = cache1.get("key");
    String v2 = cache2.get("key");
    String v3 = cache3.get("key");

    assert v1 == null : "V1 should be null: " + v1;
    assert v2 == null : "V2 should be null: " + v2;
    assert v3 == null : "V3 should be null: " + v3;
  }
  /** @throws Exception If failed. */
  public void testObjectArgument() throws Exception {
    IgniteCache<TestKey, Person> cache = ignite(0).cache(null);

    for (int i = 0; i < 100; i++) cache.put(new TestKey(i), new Person("name-" + i));

    SqlQuery<TestKey, Person> qry = new SqlQuery<>(Person.class, "where _key=?");

    IgniteBinary binary = ignite(0).binary();

    for (int i = 0; i < 100; i++) {
      Object key = new TestKey(i);

      if (i % 2 == 0) key = binary.toBinary(key);

      qry.setArgs(key);

      List<Cache.Entry<TestKey, Person>> res = cache.query(qry).getAll();

      assertEquals(1, res.size());

      Person p = res.get(0).getValue();

      assertEquals("name-" + i, p.name);
    }
  }
  /** @throws Exception If failed. */
  public void testScanQueryReconnect() throws Exception {
    Ignite cln = grid(serverCount());

    assertTrue(cln.cluster().localNode().isClient());

    final Ignite srv = clientRouter(cln);

    final IgniteCache<Integer, Person> clnCache = cln.getOrCreateCache(QUERY_CACHE);

    final IgniteCache<Integer, Person> srvCache = srv.getOrCreateCache(QUERY_CACHE);

    for (int i = 0; i < 10_000; i++) clnCache.put(i, new Person(i, "name-" + i, "surname-" + i));

    final ScanQuery<Integer, Person> scanQry = new ScanQuery<>();

    scanQry.setPageSize(1);

    scanQry.setFilter(
        new IgniteBiPredicate<Integer, Person>() {
          @Override
          public boolean apply(Integer integer, Person person) {
            return true;
          }
        });

    QueryCursor<Cache.Entry<Integer, Person>> qryCursor = clnCache.query(scanQry);

    reconnectClientNode(
        cln,
        srv,
        new Runnable() {
          @Override
          public void run() {
            srvCache.put(10_001, new Person(10_001, "name", "surname"));

            try {
              clnCache.query(scanQry);

              fail();
            } catch (CacheException e) {
              check(e);
            }
          }
        });

    try {
      qryCursor.getAll();

      fail();
    } catch (CacheException e) {
      checkAndWait(e);
    }

    qryCursor = clnCache.query(scanQry);

    assertEquals(10_001, qryCursor.getAll().size());
  }
  /** @throws Exception If failed. */
  public void testQueryReconnect() throws Exception {
    Ignite cln = grid(serverCount());

    assertTrue(cln.cluster().localNode().isClient());

    final Ignite srv = clientRouter(cln);

    final IgniteCache<Integer, Person> clnCache = cln.getOrCreateCache(QUERY_CACHE);

    final IgniteCache<Integer, Person> srvCache = srv.getOrCreateCache(QUERY_CACHE);

    clnCache.put(1, new Person(1, "name1", "surname1"));
    clnCache.put(2, new Person(2, "name2", "surname2"));
    clnCache.put(3, new Person(3, "name3", "surname3"));

    final SqlQuery<Integer, Person> qry = new SqlQuery<>(Person.class, "_key <> 0");

    qry.setPageSize(1);

    QueryCursor<Cache.Entry<Integer, Person>> cur = clnCache.query(qry);

    reconnectClientNode(
        cln,
        srv,
        new Runnable() {
          @Override
          public void run() {
            srvCache.put(4, new Person(4, "name4", "surname4"));

            try {
              clnCache.query(qry);

              fail();
            } catch (CacheException e) {
              check(e);
            }
          }
        });

    List<Cache.Entry<Integer, Person>> res = cur.getAll();

    assertNotNull(res);
    assertEquals(4, res.size());
  }
 @Override
 public void execute(ServiceContext ctx) throws Exception {
   log.info("Service execute!");
   Integer a = cache.get("a");
   if (a == null) {
     a = 0;
   }
   while (!ctx.isCancelled()) {
     Thread.sleep(1000);
     log.info("Service executing something important...");
     cache.put("a", a++);
   }
 }
  /**
   * INternal routine for ATOMIC cache testing.
   *
   * @param caches Caches.
   * @throws Exception If failed.
   */
  private void testAtomic0(IgniteCache<Integer, Object>[] caches) throws Exception {
    byte[] val = wrap(1);

    for (IgniteCache<Integer, Object> cache : caches) {
      cache.put(KEY_1, val);

      for (IgniteCache<Integer, Object> cacheInner : caches)
        assertArrayEquals(val, (byte[]) cacheInner.get(KEY_1));

      cache.remove(KEY_1);

      assertNull(cache.get(KEY_1));
    }
  }
  /** {@inheritDoc} */
  @Override
  public void testClear() throws Exception {
    IgniteCache<String, Integer> nearCache = jcache();
    IgniteCache<String, Integer> primary = fullCache();

    Collection<String> keys = primaryKeysForCache(primary, 3);

    Map<String, Integer> vals = new HashMap<>();

    int i = 0;

    for (String key : keys) {
      nearCache.put(key, i);

      vals.put(key, i);

      i++;
    }

    i = 0;

    for (String key : keys)
      assertEquals((Integer) i++, nearCache.localPeek(key, CachePeekMode.ONHEAP));

    nearCache.clear();

    for (String key : keys) assertNull(nearCache.localPeek(key, CachePeekMode.ONHEAP));

    for (Map.Entry<String, Integer> entry : vals.entrySet())
      nearCache.put(entry.getKey(), entry.getValue());

    i = 0;

    for (String key : keys)
      assertEquals((Integer) i++, nearCache.localPeek(key, CachePeekMode.ONHEAP));
  }
  /** @throws Exception If failed. */
  private void checkPut(CacheAtomicityMode atomicityMode) throws Exception {
    this.atomicityMode = atomicityMode;

    try {
      IgniteCache<IncorrectCacheKey, String> cache = grid(0).cache(null);

      cache.put(new IncorrectCacheKey(0), "test_value");

      fail("Key without hashCode()/equals() was successfully inserted to cache.");
    } catch (IllegalArgumentException e) {
      info("Catched expected exception: " + e.getMessage());

      assertTrue(
          e.getMessage().startsWith("Cache key must override hashCode() and equals() methods"));
    }
  }
  /**
   * Execute individual put and get.
   *
   * @param cache Cache.
   */
  private static void putGet(IgniteCache<Integer, Organization> cache) {
    // Create new Organization portable object to store in cache.
    Organization org =
        new Organization(
            "Microsoft", // Name.
            new Address("1096 Eddy Street, San Francisco, CA", 94109), // Address.
            OrganizationType.PRIVATE, // Type.
            new Timestamp(System.currentTimeMillis())); // Last update time.

    // Put created data entry to cache.
    cache.put(1, org);

    // Get recently created organization as a strongly-typed fully de-serialized instance.
    Organization orgFromCache = cache.get(1);

    System.out.println();
    System.out.println(">>> Retrieved organization instance from cache: " + orgFromCache);
  }
  /** @throws Exception If failed. */
  public void testGroupIndexOperations() throws Exception {
    IgniteCache<Integer, GroupIndexTestValue> c =
        ignite(0)
            .getOrCreateCache(cacheConfig("grp", false, Integer.class, GroupIndexTestValue.class));

    try {
      // Check group index usage.
      String qry = "select 1 from GroupIndexTestValue ";

      String plan = columnQuery(c, "explain " + qry + "where a = 1 and b > 0").get(0).toString();

      info("Plan: " + plan);

      assertTrue(plan.contains("grpIdx"));

      // Sorted list
      List<GroupIndexTestValue> list =
          F.asList(
              new GroupIndexTestValue(0, 0),
              new GroupIndexTestValue(0, 5),
              new GroupIndexTestValue(1, 1),
              new GroupIndexTestValue(1, 3),
              new GroupIndexTestValue(2, -1),
              new GroupIndexTestValue(2, 2));

      // Fill cache.
      for (int i = 0; i < list.size(); i++) c.put(i, list.get(i));

      // Check results.
      assertEquals(1, columnQuery(c, qry + "where a = 1 and b = 1").size());
      assertEquals(2, columnQuery(c, qry + "where a = 1 and b < 4").size());
      assertEquals(2, columnQuery(c, qry + "where a = 1 and b <= 3").size());
      assertEquals(1, columnQuery(c, qry + "where a = 1 and b < 3").size());
      assertEquals(2, columnQuery(c, qry + "where a = 1 and b > 0").size());
      assertEquals(1, columnQuery(c, qry + "where a = 1 and b > 1").size());
      assertEquals(2, columnQuery(c, qry + "where a = 1 and b >= 1").size());
      assertEquals(4, columnQuery(c, qry + "where a > 0 and b > 0").size());
      assertEquals(4, columnQuery(c, qry + "where a > 0 and b >= 1").size());
      assertEquals(3, columnQuery(c, qry + "where a > 0 and b > 1").size());
    } finally {
      c.destroy();
    }
  }
  /** {@inheritDoc} */
  @Override
  public void testEvictExpired() throws Exception {
    if (isMultiJvm()) fail("https://issues.apache.org/jira/browse/IGNITE-1113");

    IgniteCache<String, Integer> cache = jcache();

    String key = primaryKeysForCache(cache, 1).get(0);

    cache.put(key, 1);

    assertEquals((Integer) 1, cache.get(key));

    long ttl = 500;

    grid(0)
        .cache(null)
        .withExpiryPolicy(new TouchedExpiryPolicy(new Duration(MILLISECONDS, ttl)))
        .put(key, 1);

    Thread.sleep(ttl + 100);

    // Expired entry should not be swapped.
    cache.localEvict(Collections.singleton(key));

    assertNull(cache.localPeek(key, CachePeekMode.ONHEAP));

    cache.localPromote(Collections.singleton(key));

    assertNull(cache.localPeek(key, CachePeekMode.ONHEAP));

    assertTrue(cache.localSize() == 0);

    load(cache, key, true);

    Affinity<String> aff = ignite(0).affinity(null);

    for (int i = 0; i < gridCount(); i++) {
      if (aff.isPrimaryOrBackup(grid(i).cluster().localNode(), key))
        assertEquals((Integer) 1, peek(jcache(i), key));
    }
  }
  /**
   * Checks that gets work for implicit txs.
   *
   * @param cache Cache to test.
   * @throws Exception If failed.
   */
  private void checkImplicitTx(IgniteCache<String, String> cache) throws Exception {
    assertNull(cache.get("key1"));

    IgniteCache<String, String> asyncCache = cache.withAsync();

    asyncCache.get("key2");

    assertNull(asyncCache.future().get());

    assertTrue(cache.getAll(F.asSet("key3", "key4")).isEmpty());

    asyncCache.getAll(F.asSet("key5", "key6"));

    assertTrue(((Map) asyncCache.future().get()).isEmpty());

    cache.put("key7", "key7");
    cache.remove("key7", "key7");
    assertNull(cache.get("key7"));

    checkEmpty(cache);
  }
  /**
   * @param g Grid.
   * @throws Exception If failed.
   */
  private void checkNodes(Ignite g) throws Exception {
    IgniteCache<String, String> cache = g.cache("test");

    for (char c = 'a'; c <= 'z'; c++) {
      String key = Character.toString(c);

      cache.put(key, "val-" + key);

      String v1 = cache.get(key);
      String v2 = cache.get(key); // Get second time.

      info("v1: " + v1);
      info("v2: " + v2);

      assertNotNull(v1);
      assertNotNull(v2);

      if (affinity(cache).mapKeyToNode(key).isLocal()) assertSame(v1, v2);
      else assertEquals(v1, v2);
    }
  }
  /** @throws Exception If test fails. */
  public void testBasicOpsAsync() throws Exception {
    CountDownLatch latch = new CountDownLatch(3);

    CacheEventListener lsnr = new CacheEventListener(latch);

    try {
      IgniteCache<String, String> cache1 = ignite1.cache(null);
      IgniteCache<String, String> cache1Async = cache1.withAsync();
      IgniteCache<String, String> cache2 = ignite2.cache(null);
      IgniteCache<String, String> cache2Async = cache2.withAsync();
      IgniteCache<String, String> cache3 = ignite3.cache(null);
      IgniteCache<String, String> cache3Async = cache3.withAsync();

      ignite1.events().localListen(lsnr, EVT_CACHE_OBJECT_PUT, EVT_CACHE_OBJECT_REMOVED);
      ignite2.events().localListen(lsnr, EVT_CACHE_OBJECT_PUT, EVT_CACHE_OBJECT_REMOVED);
      ignite3.events().localListen(lsnr, EVT_CACHE_OBJECT_PUT, EVT_CACHE_OBJECT_REMOVED);

      cache1Async.get("async1");

      IgniteFuture<String> f1 = cache1Async.future();

      assert f1.get() == null;

      cache1Async.put("async1", "asyncval1");

      cache1Async.future().get();

      cache1Async.get("async1");

      f1 = cache1Async.future();

      String v1 = f1.get();

      assert v1 != null;
      assert "asyncval1".equals(v1);

      assert latch.await(5, SECONDS);

      cache2Async.get("async1");

      IgniteFuture<String> f2 = cache2Async.future();

      cache3Async.get("async1");

      IgniteFuture<String> f3 = cache3Async.future();

      String v2 = f2.get();
      String v3 = f3.get();

      assert v2 != null;
      assert v3 != null;

      assert "asyncval1".equals(v2);
      assert "asyncval1".equals(v3);

      lsnr.setLatch(latch = new CountDownLatch(3));

      cache2Async.getAndRemove("async1");

      f2 = cache2Async.future();

      assert "asyncval1".equals(f2.get());

      assert latch.await(5, SECONDS);

      cache1Async.get("async1");

      f1 = cache1Async.future();

      cache2Async.get("async1");

      f2 = cache2Async.future();

      cache3Async.get("async1");

      f3 = cache3Async.future();

      v1 = f1.get();
      v2 = f2.get();
      v3 = f3.get();

      info("Removed v1: " + v1);
      info("Removed v2: " + v2);
      info("Removed v3: " + v3);

      assert v1 == null;
      assert v2 == null;
      assert v3 == null;
    } finally {
      ignite1.events().stopLocalListen(lsnr);
      ignite2.events().stopLocalListen(lsnr);
      ignite3.events().stopLocalListen(lsnr);
    }
  }
  /**
   * @param setPart If {@code true} sets partition for scan query.
   * @throws Exception If failed.
   */
  private void scanQueryReconnectInProgress(boolean setPart) throws Exception {
    Ignite cln = grid(serverCount());

    assertTrue(cln.cluster().localNode().isClient());

    final Ignite srv = clientRouter(cln);

    final IgniteCache<Integer, Person> clnCache = cln.getOrCreateCache(QUERY_CACHE);

    clnCache.put(1, new Person(1, "name1", "surname1"));
    clnCache.put(2, new Person(2, "name2", "surname2"));
    clnCache.put(3, new Person(3, "name3", "surname3"));

    final ScanQuery<Integer, Person> scanQry = new ScanQuery<>();

    scanQry.setPageSize(1);

    scanQry.setFilter(
        new IgniteBiPredicate<Integer, Person>() {
          @Override
          public boolean apply(Integer integer, Person person) {
            return true;
          }
        });

    if (setPart) scanQry.setPartition(1);

    blockMessage(GridCacheQueryResponse.class);

    final IgniteInternalFuture<Object> fut =
        GridTestUtils.runAsync(
            new Callable<Object>() {
              @Override
              public Object call() throws Exception {
                try {
                  QueryCursor<Cache.Entry<Integer, Person>> qryCursor = clnCache.query(scanQry);

                  qryCursor.getAll();
                } catch (CacheException e) {
                  checkAndWait(e);

                  return true;
                }

                return false;
              }
            });

    // Check that client waiting operation.
    GridTestUtils.assertThrows(
        log,
        new Callable<Object>() {
          @Override
          public Object call() throws Exception {
            return fut.get(200);
          }
        },
        IgniteFutureTimeoutCheckedException.class,
        null);

    assertNotDone(fut);

    unblockMessage();

    reconnectClientNode(cln, srv, null);

    assertTrue((Boolean) fut.get(2, SECONDS));

    QueryCursor<Cache.Entry<Integer, Person>> qryCursor2 = clnCache.query(scanQry);

    assertEquals(setPart ? 1 : 3, qryCursor2.getAll().size());
  }
  /** @throws IgniteCheckedException If test fails. */
  public void testOptimisticTransaction() throws Exception {
    CountDownLatch latch = new CountDownLatch(9);

    IgnitePredicate<Event> lsnr = new CacheEventListener(latch);

    try {
      IgniteCache<String, String> cache1 = ignite1.cache(null);
      IgniteCache<String, String> cache2 = ignite2.cache(null);
      IgniteCache<String, String> cache3 = ignite3.cache(null);

      ignite1.events().localListen(lsnr, EVT_CACHE_OBJECT_PUT, EVT_CACHE_OBJECT_REMOVED);
      ignite2.events().localListen(lsnr, EVT_CACHE_OBJECT_PUT, EVT_CACHE_OBJECT_REMOVED);
      ignite3.events().localListen(lsnr, EVT_CACHE_OBJECT_PUT, EVT_CACHE_OBJECT_REMOVED);

      Transaction tx = ignite1.transactions().txStart(OPTIMISTIC, READ_COMMITTED, 0, 0);

      try {
        cache1.put("tx1", "val1");
        cache1.put("tx2", "val2");
        cache1.put("tx3", "val3");

        assert cache2.get("tx1") == null;
        assert cache2.get("tx2") == null;
        assert cache2.get("tx3") == null;

        assert cache3.get("tx1") == null;
        assert cache3.get("tx2") == null;
        assert cache3.get("tx3") == null;

        tx.commit();
      } catch (CacheException e) {
        tx.rollback();

        throw e;
      }

      assert latch.await(5, SECONDS);

      String b1 = cache2.get("tx1");
      String b2 = cache2.get("tx2");
      String b3 = cache2.get("tx3");

      String c1 = cache3.get("tx1");
      String c2 = cache3.get("tx2");
      String c3 = cache3.get("tx3");

      assert b1 != null : "Invalid value: " + b1;
      assert b2 != null : "Invalid value: " + b2;
      assert b3 != null : "Invalid value: " + b3;

      assert c1 != null : "Invalid value: " + c1;
      assert c2 != null : "Invalid value: " + c2;
      assert c3 != null : "Invalid value: " + c3;

      assert "val1".equals(b1);
      assert "val2".equals(b2);
      assert "val3".equals(b3);

      assert "val1".equals(c1);
      assert "val2".equals(c2);
      assert "val3".equals(c3);
    } finally {
      ignite1.events().stopLocalListen(lsnr);
      ignite2.events().stopLocalListen(lsnr);
      ignite3.events().stopLocalListen(lsnr);
    }
  }
  /** @throws Exception If failed. */
  public void testReconnectQueryInProgress() throws Exception {
    Ignite cln = grid(serverCount());

    assertTrue(cln.cluster().localNode().isClient());

    final Ignite srv = clientRouter(cln);

    final IgniteCache<Integer, Person> clnCache = cln.getOrCreateCache(QUERY_CACHE);

    clnCache.put(1, new Person(1, "name1", "surname1"));
    clnCache.put(2, new Person(2, "name2", "surname2"));
    clnCache.put(3, new Person(3, "name3", "surname3"));

    blockMessage(GridQueryNextPageResponse.class);

    final SqlQuery<Integer, Person> qry = new SqlQuery<>(Person.class, "_key <> 0");

    qry.setPageSize(1);

    final QueryCursor<Cache.Entry<Integer, Person>> cur1 = clnCache.query(qry);

    final IgniteInternalFuture<Object> fut =
        GridTestUtils.runAsync(
            new Callable<Object>() {
              @Override
              public Object call() throws Exception {
                try {
                  cur1.getAll();
                } catch (CacheException e) {
                  checkAndWait(e);

                  return true;
                }

                return false;
              }
            });

    // Check that client waiting operation.
    GridTestUtils.assertThrows(
        log,
        new Callable<Object>() {
          @Override
          public Object call() throws Exception {
            return fut.get(200);
          }
        },
        IgniteFutureTimeoutCheckedException.class,
        null);

    assertNotDone(fut);

    unblockMessage();

    reconnectClientNode(cln, srv, null);

    assertTrue((Boolean) fut.get(2, SECONDS));

    QueryCursor<Cache.Entry<Integer, Person>> cur2 = clnCache.query(qry);

    assertEquals(3, cur2.getAll().size());
  }
  /** @throws Exception If error occur. */
  public void testBasicOps() throws Exception {
    CountDownLatch latch = new CountDownLatch(3);

    CacheEventListener lsnr = new CacheEventListener(latch);

    try {
      IgniteCache<String, String> cache1 = ignite1.cache(null);
      IgniteCache<String, String> cache2 = ignite2.cache(null);
      IgniteCache<String, String> cache3 = ignite3.cache(null);

      ignite1.events().localListen(lsnr, EVT_CACHE_OBJECT_PUT, EVT_CACHE_OBJECT_REMOVED);
      ignite2.events().localListen(lsnr, EVT_CACHE_OBJECT_PUT, EVT_CACHE_OBJECT_REMOVED);
      ignite3.events().localListen(lsnr, EVT_CACHE_OBJECT_PUT, EVT_CACHE_OBJECT_REMOVED);

      assert !cache1.containsKey("1");
      assert !cache2.containsKey("1");
      assert !cache3.containsKey("1");

      info("First put");

      cache1.put("1", "a");

      info("Start latch wait 1");

      assert latch.await(5, SECONDS);

      info("Stop latch wait 1");

      assert cache1.containsKey("1");
      assert cache2.containsKey("1");
      assert cache3.containsKey("1");

      latch = new CountDownLatch(6);

      lsnr.setLatch(latch);

      cache2.put("1", "b");
      cache3.put("1", "c");

      info("Start latch wait 2");

      assert latch.await(5, SECONDS);

      info("Stop latch wait 2");

      assert cache1.containsKey("1");
      assert cache2.containsKey("1");
      assert cache3.containsKey("1");

      latch = new CountDownLatch(3);

      lsnr.setLatch(latch);

      cache1.remove("1");

      info("Start latch wait 3");

      assert latch.await(5, SECONDS);

      info("Stop latch wait 3");

      assert !cache1.containsKey("1");
      assert !cache2.containsKey("1");
      assert !cache3.containsKey("1");
    } finally {
      ignite1.events().stopLocalListen(lsnr);
      ignite2.events().stopLocalListen(lsnr);
      ignite3.events().stopLocalListen(lsnr);
    }
  }
Ejemplo n.º 25
0
 @Override
 public void put(K key, V value, Handler<AsyncResult<Void>> handler) {
   execute(cache -> cache.put(key, value), handler);
 }
Ejemplo n.º 26
0
 @Override
 public void put(K key, V value, long timeout, Handler<AsyncResult<Void>> handler) {
   executeWithTimeout(cache -> cache.put(key, value), handler, timeout);
 }
  /**
   * JUnit.
   *
   * @throws Exception If failed.
   */
  @SuppressWarnings({"TooBroadScope"})
  public void testRestarts() throws Exception {
    int duration = 60 * 1000;
    int qryThreadNum = 10;
    final long nodeLifeTime = 2 * 1000;
    final int logFreq = 20;

    final IgniteCache<Integer, Integer> cache = grid(0).cache(null);

    assert cache != null;

    for (int i = 0; i < KEY_CNT; i++) cache.put(i, i);

    assertEquals(KEY_CNT, cache.localSize());

    final AtomicInteger qryCnt = new AtomicInteger();

    final AtomicBoolean done = new AtomicBoolean();

    IgniteInternalFuture<?> fut1 =
        multithreadedAsync(
            new CAX() {
              @Override
              public void applyx() throws IgniteCheckedException {
                while (!done.get()) {
                  Collection<Cache.Entry<Integer, Integer>> res =
                      cache.query(new SqlQuery(Integer.class, "_val >= 0")).getAll();

                  assertFalse(res.isEmpty());

                  int c = qryCnt.incrementAndGet();

                  if (c % logFreq == 0) info("Executed queries: " + c);
                }
              }
            },
            qryThreadNum);

    final AtomicInteger restartCnt = new AtomicInteger();

    CollectingEventListener lsnr = new CollectingEventListener();

    for (int i = 0; i < GRID_CNT; i++)
      grid(i).events().localListen(lsnr, EventType.EVT_CACHE_REBALANCE_STOPPED);

    IgniteInternalFuture<?> fut2 =
        multithreadedAsync(
            new Callable<Object>() {
              @SuppressWarnings({"BusyWait"})
              @Override
              public Object call() throws Exception {
                while (!done.get()) {
                  int idx = GRID_CNT;

                  startGrid(idx);

                  Thread.sleep(nodeLifeTime);

                  stopGrid(idx);

                  int c = restartCnt.incrementAndGet();

                  if (c % logFreq == 0) info("Node restarts: " + c);
                }

                return true;
              }
            },
            1);

    Thread.sleep(duration);

    done.set(true);

    fut1.get();
    fut2.get();

    info("Awaiting rebalance events [restartCnt=" + restartCnt.get() + ']');

    boolean success = lsnr.awaitEvents(GRID_CNT * 2 * restartCnt.get(), 15000);

    for (int i = 0; i < GRID_CNT; i++)
      grid(i).events().stopLocalListen(lsnr, EventType.EVT_CACHE_REBALANCE_STOPPED);

    assert success;
  }