Java Code Examples for org.apache.ignite.IgniteCache#put()

The following examples show how to use org.apache.ignite.IgniteCache#put() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ImputingExample.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 *
 */
private static IgniteCache<Integer, Vector> createCache(Ignite ignite) {
    CacheConfiguration<Integer, Vector> cacheConfiguration = new CacheConfiguration<>();

    cacheConfiguration.setName("PERSONS");
    cacheConfiguration.setAffinity(new RendezvousAffinityFunction(false, 2));

    IgniteCache<Integer, Vector> persons = ignite.createCache(cacheConfiguration);

    persons.put(1, new DenseVector(new Serializable[] {"Mike", 10, 1}));
    persons.put(1, new DenseVector(new Serializable[] {"John", 20, 2}));
    persons.put(1, new DenseVector(new Serializable[] {"George", 15, 1}));
    persons.put(1, new DenseVector(new Serializable[] {"Piter", 25, Double.NaN}));
    persons.put(1, new DenseVector(new Serializable[] {"Karl", Double.NaN, 1}));
    persons.put(1, new DenseVector(new Serializable[] {"Gustaw", 20, 2}));
    persons.put(1, new DenseVector(new Serializable[] {"Alex", 20, 2}));

    return persons;
}
 
Example 2
Source File: IgniteCacheConfigVariationsFullApiTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Test
public void testIterator() throws Exception {
    IgniteCache<Integer, Integer> cache = grid(0).cache(cacheName());

    final int KEYS = 1000;

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

    // Try to initialize readers in case when near cache is enabled.
    for (int i = 0; i < gridCount(); i++) {
        cache = grid(i).cache(cacheName());

        for (int k = 0; k < KEYS; k++)
            assertEquals((Object)k, cache.get(k));
    }

    int cnt = 0;

    for (Cache.Entry e : cache)
        cnt++;

    assertEquals(KEYS, cnt);
}
 
Example 3
Source File: IgniteCacheGroupsTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * @param idx Node index.
 * @param ldrs Loaders count.
 * @param ldrIdx Loader index.
 * @param cacheName Cache name.
 * @param data Data.
 * @return Callable for put operation.
 */
private Callable<Void> putOperation(
        final int idx,
        final int ldrs,
        final int ldrIdx,
        final String cacheName,
        final Integer[] data) {
    return new Callable<Void>() {
        @Override public Void call() throws Exception {
            IgniteCache cache = ignite(idx).cache(cacheName);

            for (int j = 0, size = data.length; j < size; j++) {
                if (j % ldrs == ldrIdx)
                    cache.put(j, data[j]);
            }

            return null;
        }
    };
}
 
Example 4
Source File: IgniteCacheCollocatedQuerySelfTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * Correct affinity.
 */
@Test
public void testColocatedQueryWrong() {
    IgniteCache<AffinityUuid,Purchase> c = ignite(0).cache(DEFAULT_CACHE_NAME);

    Random rnd = new GridRandom(SEED);

    for (int i = 0; i < PURCHASES; i++) {
        Purchase p = new Purchase();

        p.productId = rnd.nextInt(PRODUCTS);
        p.price = rnd.nextInt(MAX_PRICE);

        c.put(new AffinityUuid(rnd.nextInt(PRODUCTS)), p); // Random affinity.
    }

    List<List<?>> res1 = query(c, false);
    List<List<?>> res2 = query(c, true);

    X.println("res1: " + res1);
    X.println("res2: " + res2);

    assertFalse(res1.isEmpty());
    assertFalse(res1.equals(res2));
}
 
Example 5
Source File: TxStateChangeEventTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * @param txs Transaction manager.
 * @param cache Ignite cache.
 */
private void checkCommit(IgniteTransactions txs, IgniteCache<Integer, Integer> cache) {
    // create & commit
    try (Transaction tx = txs.withLabel(lb).txStart(
        TransactionConcurrency.PESSIMISTIC, TransactionIsolation.REPEATABLE_READ, timeout, 3)) {
        cache.put(1, 1);

        tx.commit();
    }

    assertTrue(
        creation.get() &&
            commit.get() &&
            !rollback.get() &&
            !suspend.get() &&
            !resume.get());

    clear();
}
 
Example 6
Source File: IgniteStartCacheInTransactionSelfTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Test
public void testGetOrCreateCacheConfiguration() throws Exception {
    final Ignite ignite = grid(0);

    final String key = "key";
    final String val = "val";

    IgniteCache<String, String> cache = ignite.cache(DEFAULT_CACHE_NAME).withAllowAtomicOpsInTx();

    try (Transaction tx = ignite.transactions().txStart(PESSIMISTIC, REPEATABLE_READ)) {
        cache.put(key, val);

        GridTestUtils.assertThrows(log, new Callable<Object>() {
            @Override public Object call() throws Exception {
                ignite.getOrCreateCache(cacheConfiguration("NEW_CACHE"));

                return null;
            }
        }, IgniteException.class, EXPECTED_MSG);

        tx.commit();
    }
}
 
Example 7
Source File: BinaryObjectBuilderAdditionalSelfTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Test
public void testSameBinaryKey() throws Exception {
    IgniteCache<BinaryObject, BinaryObject> replicatedCache =
        jcache(0).withKeepBinary();

    IgniteCache<BinaryObject, BinaryObject> partitionedCache =
        jcache(0, "partitioned").withKeepBinary();

    BinaryObjectBuilder keyBuilder = ignite(0).binary().builder("keyType")
        .setField("F1", "V1");

    BinaryObjectBuilder valBuilder = ignite(0).binary().builder("valueType")
        .setField("F2", "V2")
        .setField("F3", "V3");

    BinaryObject key = keyBuilder.build();
    BinaryObject val = valBuilder.build();

    replicatedCache.put(key, val);
    partitionedCache.put(key, val);

    assertNotNull(replicatedCache.get(key));
    assertNotNull(partitionedCache.get(key));
}
 
Example 8
Source File: CacheMetricsManageTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * Increment cache statistics.
 *
 * @param cache cache.
 */
private void incrementCacheStatistics(IgniteCache<Integer, String> cache) {
    cache.get(1);
    cache.put(1, "one");
    cache.get(1);
    cache.remove(1);
}
 
Example 9
Source File: GridCacheHashMapPutAllWarningsTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Test
public void testTreeMapClearEntries() throws Exception {
    List<String> messages = Collections.synchronizedList(new ArrayList<>());

    testLog = new ListeningTestLogger(false, log());

    testLog.registerListener((s) -> {
        if (s.contains("deadlock"))
            messages.add(s);
    });

    Ignite ignite = startGrid(0);
    startGrid(1);

    IgniteCache<Integer, String> c = ignite.getOrCreateCache(new CacheConfiguration<Integer, String>("entries")
        .setCacheMode(CacheMode.PARTITIONED)
        .setAtomicityMode(CacheAtomicityMode.ATOMIC)
        .setBackups(1));

    for (int i = 0; i < 1000; i++) {
        c.put(i, "foo");
        c.put(i * 2, "bar");
    }

    c.clear();

    assertEquals(0, c.size());

    for (String message : messages) {
        assertFalse(message.contains("Unordered "));

        assertFalse(message.contains("operation on cache"));
    }
}
 
Example 10
Source File: IgniteCacheConfigVariationsFullApiTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception In case of error.
 */
@Test
public void testPeek() throws Exception {
    Ignite ignite = primaryIgnite("key");
    IgniteCache<String, Integer> cache = ignite.cache(cacheName());

    assertNull(cache.localPeek("key"));

    cache.put("key", 1);

    cache.replace("key", 2);

    assertEquals(2, cache.localPeek("key").intValue());
}
 
Example 11
Source File: SqlViewExporterSpiTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/** */
@Test
public void testContinuousQuery() throws Exception {
    IgniteCache<Integer, Integer> cache = ignite0.createCache("cache-1");

    assertTrue(execute(ignite0, "SELECT * FROM SYS.CONTINUOUS_QUERIES").isEmpty());
    assertTrue(execute(ignite1, "SELECT * FROM SYS.CONTINUOUS_QUERIES").isEmpty());

    try (QueryCursor qry = cache.query(new ContinuousQuery<>()
        .setInitialQuery(new ScanQuery<>())
        .setPageSize(100)
        .setTimeInterval(1000)
        .setLocalListener(evts -> {
            // No-op.
        })
        .setRemoteFilterFactory(() -> evt -> true)
    )) {
        for (int i = 0; i < 100; i++)
            cache.put(i, i);

        checkContinuouQueryView(ignite0, true);
        checkContinuouQueryView(ignite1, false);
    }

    assertTrue(execute(ignite0, "SELECT * FROM SYS.CONTINUOUS_QUERIES").isEmpty());
    assertTrue(waitForCondition(() ->
        execute(ignite1, "SELECT * FROM SYS.CONTINUOUS_QUERIES").isEmpty(), getTestTimeout()));
}
 
Example 12
Source File: IgniteCacheContinuousQueryReconnectTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 *
 */
private void putAndCheck(IgniteCache<Object, Object> cache, int diff) {
    cnt.set(0);

    cache.put(1, "1");

    assertEquals(diff, cnt.get());
}
 
Example 13
Source File: RandomForestIntegrationTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/** */
@Test
public void testFit() {
    int size = 100;

    CacheConfiguration<Integer, double[]> trainingSetCacheCfg = new CacheConfiguration<>();
    trainingSetCacheCfg.setAffinity(new RendezvousAffinityFunction(false, 10));
    trainingSetCacheCfg.setName("TRAINING_SET");

    IgniteCache<Integer, double[]> data = ignite.createCache(trainingSetCacheCfg);

    Random rnd = new Random(0);
    for (int i = 0; i < size; i++) {
        double x = rnd.nextDouble() - 0.5;
        data.put(i, new double[] {x, x > 0 ? 1 : 0});
    }

    ArrayList<FeatureMeta> meta = new ArrayList<>();
    meta.add(new FeatureMeta("", 0, false));
    RandomForestRegressionTrainer trainer = new RandomForestRegressionTrainer(meta)
        .withAmountOfTrees(5)
        .withFeaturesCountSelectionStrgy(x -> 2);

    ModelsComposition mdl = trainer.fit(ignite, data, new DoubleArrayVectorizer<Integer>().labeled(1));

    assertTrue(mdl.getPredictionsAggregator() instanceof MeanValuePredictionsAggregator);
    assertEquals(5, mdl.getModels().size());
}
 
Example 14
Source File: IgniteDialect.java    From hibernate-ogm-ignite with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void insertOrUpdateTuple(EntityKey key, TuplePointer tuplePointer, TupleContext tupleContext) throws TupleAlreadyExistsException {
	IgniteCache<Object, BinaryObject> entityCache = provider.getEntityCache( key.getMetadata() );
	Tuple tuple = tuplePointer.getTuple();

	Object keyObject = null;
	BinaryObjectBuilder builder = null;
	IgniteTupleSnapshot tupleSnapshot = (IgniteTupleSnapshot) tuple.getSnapshot();
	keyObject = tupleSnapshot.getCacheKey();
	if ( tuple.getSnapshotType() == SnapshotType.UPDATE ) {
		builder = provider.createBinaryObjectBuilder( tupleSnapshot.getCacheValue() );
	}
	else {
		builder = provider.createBinaryObjectBuilder( provider.getEntityTypeName( key.getMetadata().getTable() ) );
	}
	for ( String columnName : tuple.getColumnNames() ) {
		Object value = tuple.get( columnName );
		if ( value != null ) {
			builder.setField( StringHelper.realColumnName( columnName ), value );
		}
		else {
			builder.removeField( StringHelper.realColumnName( columnName ) );
		}
	}
	BinaryObject valueObject = builder.build();
	entityCache.put( keyObject, valueObject );
	tuplePointer.setTuple( new Tuple( new IgniteTupleSnapshot( keyObject, valueObject, key.getMetadata() ), SnapshotType.UPDATE ) );
}
 
Example 15
Source File: AffinityKeyNameAndValueFieldNameConflictTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * @throws Exception If failed.
 */
private void checkQuery() throws Exception {
    startGrid(2);

    Ignite g = grid(2);

    IgniteCache<Object, Object> personCache = g.cache(PERSON_CACHE);

    personCache.put(keyProducer.apply(1, "o1"), new Person("p1"));

    SqlFieldsQuery query = new SqlFieldsQuery("select * from \"" + PERSON_CACHE + "\"." + Person.class.getSimpleName() + " it where it.name=?");

    List<List<?>> result = personCache.query(query.setArgs(keyFieldSpecified ? "o1" : "p1")).getAll();

    assertEquals(1, result.size());

    stopAllGrids();
}
 
Example 16
Source File: CacheMvccConfigurationValidationTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@SuppressWarnings("ThrowableNotThrown")
@Test
public void testNodeRestartWithCacheModeChangedMvccToTx() throws Exception {
    cleanPersistenceDir();

    //Enable persistence.
    DataStorageConfiguration storageCfg = new DataStorageConfiguration();
    DataRegionConfiguration regionCfg = new DataRegionConfiguration();
    regionCfg.setPersistenceEnabled(true);
    regionCfg.setPageEvictionMode(RANDOM_LRU);
    storageCfg.setDefaultDataRegionConfiguration(regionCfg);
    IgniteConfiguration cfg = getConfiguration("testGrid");
    cfg.setDataStorageConfiguration(storageCfg);
    cfg.setConsistentId(cfg.getIgniteInstanceName());

    Ignite node = startGrid(cfg);

    node.cluster().active(true);

    CacheConfiguration ccfg1 = new CacheConfiguration("test1").setAtomicityMode(TRANSACTIONAL_SNAPSHOT);

    IgniteCache cache = node.createCache(ccfg1);

    cache.put(1, 1);
    cache.put(1, 2);
    cache.put(2, 2);

    stopGrid(cfg.getIgniteInstanceName());

    CacheConfiguration ccfg2 = new CacheConfiguration().setName(ccfg1.getName())
        .setAtomicityMode(TRANSACTIONAL);

    IgniteConfiguration cfg2 = getConfiguration("testGrid")
        .setConsistentId(cfg.getIgniteInstanceName())
        .setCacheConfiguration(ccfg2)
        .setDataStorageConfiguration(storageCfg);

    GridTestUtils.assertThrows(log, new Callable<Void>() {
        @Override public Void call() throws Exception {
            startGrid(cfg2);

            return null;
        }
    }, IgniteCheckedException.class, "Cannot start cache. Statically configured atomicity mode");
}
 
Example 17
Source File: IgniteCachePeekModesAbstractTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * @param nodeIdx Node index.
 * @throws Exception If failed.
 */
private void checkAffinityPeek(int nodeIdx) throws Exception {
    IgniteCache<Integer, String> cache0 = jcache(nodeIdx);

    final String val = "1";

    Integer key = null;

    try {
        if (cacheMode() == REPLICATED) {
            key = backupKey(cache0);

            cache0.put(key, val);

            assertEquals(val, cache0.localPeek(key, ALL));
            assertEquals(val, cache0.localPeek(key, BACKUP));
            assertNull(cache0.localPeek(key, NEAR));
            assertNull(cache0.localPeek(key, PRIMARY));
        }
        else {
            key = nearKey(cache0);

            cache0.put(key, val);

            if (hasNearCache()) {
                assertEquals(val, cache0.localPeek(key, NEAR));
                assertEquals(val, cache0.localPeek(key, ALL));
            }
            else {
                assertNull(cache0.localPeek(key, NEAR));
                assertNull(cache0.localPeek(key, ALL));
            }

            assertNull(cache0.localPeek(key, PRIMARY));
            assertNull(cache0.localPeek(key, BACKUP));
        }

        Affinity<Integer> aff = ignite(0).affinity(DEFAULT_CACHE_NAME);

        for (int i = 0; i < gridCount(); i++) {
            if (i == nodeIdx)
                continue;

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

            assertNull(cache.localPeek(key, NEAR));

            if (aff.isPrimary(ignite(i).cluster().localNode(), key)) {
                assertEquals(val, cache.localPeek(key, PRIMARY));
                assertEquals(val, cache.localPeek(key, ALL));
                assertNull(cache.localPeek(key, BACKUP));
                assertNull(cache.localPeek(key, NEAR));
            }
            else if (aff.isBackup(ignite(i).cluster().localNode(), key)) {
                assertEquals(val, cache.localPeek(key, BACKUP));
                assertEquals(val, cache.localPeek(key, ALL));
                assertNull(cache.localPeek(key, PRIMARY));
                assertNull(cache.localPeek(key, NEAR));
            }
            else {
                assertNull(cache.localPeek(key, ALL));
                assertNull(cache.localPeek(key, PRIMARY));
                assertNull(cache.localPeek(key, BACKUP));
                assertNull(cache.localPeek(key, NEAR));
            }
        }
    }
    finally {
        if (key != null)
            cache0.remove(key);
    }
}
 
Example 18
Source File: IgniteCacheGroupsTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * @param cache Cache.
 */
private void cachePutGetContains(IgniteCache cache) {
    Random rnd = ThreadLocalRandom.current();

    Integer key = rnd.nextInt();
    Integer val = rnd.nextInt();

    cache.put(key, val);

    Object val0 = cache.get(key);

    assertEquals(val, val0);

    assertTrue(cache.containsKey(key));

    Integer key2 = rnd.nextInt();

    while (key2.equals(key))
        key2 = rnd.nextInt();

    assertFalse(cache.containsKey(key2));

    tearDown(cache);
}
 
Example 19
Source File: IgniteCacheQueryNodeRestartSelfTest2.java    From ignite with Apache License 2.0 3 votes vote down vote up
/**
 *
 */
private void fillCaches() {
    IgniteCache<Integer, Company> co = grid(0).cache("co");

    for (int i = 0; i < COMPANY_CNT; i++)
        co.put(i, new Company(i));

    IgniteCache<Integer, Product> pr = grid(0).cache("pr");

    Random rnd = new GridRandom();

    for (int i = 0; i < PRODUCT_CNT; i++)
        pr.put(i, new Product(i, rnd.nextInt(COMPANY_CNT)));

    IgniteCache<Integer, Person> pe = grid(0).cache("pe");

    for (int i = 0; i < PERS_CNT; i++)
        pe.put(i, new Person(i));

    IgniteCache<AffinityKey<Integer>, Purchase> pu = grid(0).cache("pu");

    for (int i = 0; i < PURCHASE_CNT; i++) {
        int persId = rnd.nextInt(PERS_CNT);
        int prodId = rnd.nextInt(PRODUCT_CNT);

        pu.put(new AffinityKey<>(i, persId), new Purchase(persId, prodId));
    }
}
 
Example 20
Source File: IgniteDynamicCacheFilterTest.java    From ignite with Apache License 2.0 2 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Test
public void testCofiguredCacheFilter() throws Exception {
    attrVal = "A";

    Ignite ignite0 = startGrid(0);

    IgniteCache<Integer, Integer> cache0 = ignite0.cache(DEFAULT_CACHE_NAME);

    assertNotNull(cache0);

    cache0.put(1, 1);

    attrVal = null;

    Ignite ignite1 = startGrid(1);

    IgniteCache<Integer, Integer> cache1 = ignite1.cache(DEFAULT_CACHE_NAME);

    assertNotNull(cache1);

    attrVal = "B";

    Ignite ignite2 = startGrid(2);

    IgniteCache<Integer, Integer> cache2 = ignite2.cache(DEFAULT_CACHE_NAME);

    assertNotNull(cache2);

    attrVal = "A";

    Ignite ignite3 = startGrid(3);

    IgniteCache<Integer, Integer> cache3 = ignite3.cache(DEFAULT_CACHE_NAME);

    assertNotNull(cache3);

    assertNotNull(cache0.localPeek(1));
    assertNotNull(cache3.localPeek(1));

    assertNull(cache1.localPeek(1));
    assertNull(cache2.localPeek(1));
}