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

The following examples show how to use org.apache.ignite.IgniteCache#withKeepBinary() . 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: IgniteDatastoreProvider.java    From hibernate-ogm-ignite with GNU Lesser General Public License v2.1 6 votes vote down vote up
private <K, V> IgniteCache<K, V> getCache(String entityCacheName, boolean keepBinary) {
	IgniteCache<K, V> cache = null;
	try {
		cache = cacheManager.cache( entityCacheName );
	}
	catch (IllegalStateException ex) {
		if ( Ignition.state( gridName ) == IgniteState.STOPPED ) {
			log.stoppedIgnite();
			restart();
			cache = cacheManager.cache( entityCacheName );
		}
		else {
			throw ex;
		}

	}
	if ( cache == null ) {
		throw log.cacheNotFound( entityCacheName );
	}
	if ( keepBinary ) {
		cache = cache.withKeepBinary();
	}
	return cache;
}
 
Example 2
Source File: CacheGetEntryAbstractTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * @param cache Cache.
 * @param i Key.
 * @param oneEntry If {@code true} then single entry is tested.
 */
private void checkBinaryRemoved(IgniteCache<Integer, TestValue> cache, int i, boolean oneEntry) {
    IgniteCache<Integer, BinaryObject> cacheB = cache.withKeepBinary();

    if (oneEntry) {
        CacheEntry<Integer, BinaryObject> e = cacheB.getEntry(i);

        assertNull(e);
    }
    else {
        Set<Integer> set = new HashSet<>();

        for (int j = 0; j < 10; j++)
            set.add(i + j);

        Collection<CacheEntry<Integer, BinaryObject>> es = cacheB.getEntries(set);

        assertTrue(es.isEmpty());
    }
}
 
Example 3
Source File: CacheClientBinaryPutGetExample.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * Execute individual put and get, getting value in binary format, without de-serializing it.
 *
 * @param cache Cache.
 */
private static void putGetBinary(IgniteCache<Integer, Organization> cache) {
    // Create new Organization binary 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 binary objects.
    IgniteCache<Integer, BinaryObject> binaryCache = cache.withKeepBinary();

    // Get recently created organization as a binary object.
    BinaryObject po = binaryCache.get(1);

    // Get organization's name from binary 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 binary object: " + name);
}
 
Example 4
Source File: IgniteDatastoreProvider.java    From hibernate-ogm-ignite with GNU Lesser General Public License v2.1 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public List<T> call() throws Exception {
	IgniteCache<Object, BinaryObject> cache = ignite.cache( cacheName );
	if ( cache == null ) {
		throw new IgniteException( "Cache '" + cacheName + "' not found" );
	}
	cache = cache.withKeepBinary();
	return (List<T>) cache.query( query ).getAll();
}
 
Example 5
Source File: GridCacheQueryTransformerSelfTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Test
public void testKeepBinary() throws Exception {
    IgniteCache<Integer, Value> cache = grid().createCache("test-cache");

    try {
        for (int i = 0; i < 50; i++)
            cache.put(i, new Value("str" + i, i * 100));

        IgniteCache<Integer, BinaryObject> binaryCache = cache.withKeepBinary();

        IgniteClosure<Cache.Entry<Integer, BinaryObject>, Integer> transformer =
            new IgniteClosure<Cache.Entry<Integer, BinaryObject>, Integer>() {
                @Override public Integer apply(Cache.Entry<Integer, BinaryObject> e) {
                    return e.getValue().field("idx");
                }
            };

        List<Integer> res = binaryCache.query(new ScanQuery<Integer, BinaryObject>(), transformer).getAll();

        assertEquals(50, res.size());

        Collections.sort(res);

        for (int i = 0; i < 50; i++)
            assertEquals(i * 100, res.get(i).intValue());
    }
    finally {
        cache.destroy();
    }
}
 
Example 6
Source File: GridCacheQueryTransformerSelfTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Test
public void testKeepBinaryFiltered() throws Exception {
    IgniteCache<Integer, Value> cache = grid().createCache("test-cache");

    try {
        for (int i = 0; i < 50; i++)
            cache.put(i, new Value("str" + i, i * 100));

        IgniteCache<Integer, BinaryObject> binaryCache = cache.withKeepBinary();

        IgniteBiPredicate<Integer, BinaryObject> filter = new IgniteBiPredicate<Integer, BinaryObject>() {
            @Override public boolean apply(Integer k, BinaryObject v) {
                return v.<Integer>field("idx") % 1000 == 0;
            }
        };

        IgniteClosure<Cache.Entry<Integer, BinaryObject>, Integer> transformer =
            new IgniteClosure<Cache.Entry<Integer, BinaryObject>, Integer>() {
                @Override public Integer apply(Cache.Entry<Integer, BinaryObject> e) {
                    return e.getValue().field("idx");
                }
            };

        List<Integer> res = binaryCache.query(new ScanQuery<>(filter), transformer).getAll();

        assertEquals(5, res.size());

        Collections.sort(res);

        for (int i = 0; i < 5; i++)
            assertEquals(i * 1000, res.get(i).intValue());
    }
    finally {
        cache.destroy();
    }
}
 
Example 7
Source File: CacheClientBinaryPutGetExample.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * Execute bulk {@code putAll(...)} and {@code getAll(...)} operations,
 * getting values in binary format, without de-serializing it.
 *
 * @param cache Cache.
 */
private static void putGetAllBinary(IgniteCache<Integer, Organization> cache) {
    // Create new Organization binary objects to store in cache.
    Organization org1 = new Organization(
        "Microsoft", // Name.
        new Address("1096 Eddy Street, San Francisco, CA", 94109), // Address.
        OrganizationType.PRIVATE, // Type.
        new Timestamp(System.currentTimeMillis())); // Last update time.

    Organization org2 = new Organization(
        "Red Cross", // Name.
        new Address("184 Fidler Drive, San Antonio, TX", 78205), // Address.
        OrganizationType.NON_PROFIT, // Type.
        new Timestamp(System.currentTimeMillis())); // Last update time.

    Map<Integer, Organization> map = new HashMap<>();

    map.put(1, org1);
    map.put(2, org2);

    // Put created data entries to cache.
    cache.putAll(map);

    // Get cache that will get values as binary objects.
    IgniteCache<Integer, BinaryObject> binaryCache = cache.withKeepBinary();

    // Get recently created organizations as binary objects.
    Map<Integer, BinaryObject> poMap = binaryCache.getAll(map.keySet());

    Collection<String> names = new ArrayList<>();

    // Get organizations' names from binary objects (note that
    // objects don't need to be fully deserialized).
    for (BinaryObject po : poMap.values())
        names.add(po.<String>field("name"));

    System.out.println();
    System.out.println(">>> Retrieved organization names from binary objects: " + names);
}
 
Example 8
Source File: CacheContinuousWithTransformerReplicatedSelfTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * @param addEvtFilter Add event filter to ContinuousQueryWithTransformer flag.
 * @param expTransCnt Expected transformed event count.
 * @param keepBinary Keep binary flag.
 * @param async Flag to use transformed event listener with {@link IgniteAsyncCallback}.
 * @throws Exception If failed.
 */
private void runContinuousQueryWithTransformer(boolean addEvtFilter, int expTransCnt, boolean keepBinary,
    boolean async)
    throws Exception {
    Ignite ignite = gridToRunQuery();

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

    if (keepBinary)
        cache = cache.withKeepBinary();

    populateData(cache, JOHN_CONNOR);

    CountDownLatch transUpdCntLatch = new CountDownLatch(expTransCnt);

    AtomicInteger transCnt = new AtomicInteger(0);

    EventListener<String> transLsnr = async ?
        new LocalEventListenerAsync(transCnt, transUpdCntLatch) :
        new LocalEventListener(transCnt, transUpdCntLatch);

    Factory<? extends CacheEntryEventFilter> rmtFilterFactory = null;

    if (addEvtFilter)
        rmtFilterFactory = FactoryBuilder.factoryOf(new RemoteCacheEntryEventFilter());

    Factory<? extends IgniteClosure> factory = FactoryBuilder.factoryOf(new RemoteTransformer(keepBinary));

    ContinuousQueryWithTransformer<Integer, Employee, String> qry = new ContinuousQueryWithTransformer<>();

    qry.setInitialQuery(new ScanQuery<Integer, Employee>());
    qry.setRemoteFilterFactory((Factory<? extends CacheEntryEventFilter<Integer, Employee>>)rmtFilterFactory);
    qry.setRemoteTransformerFactory(
        (Factory<? extends IgniteClosure<CacheEntryEvent<? extends Integer, ? extends Employee>, String>>)factory);
    qry.setLocalListener(transLsnr);

    try (QueryCursor<Cache.Entry<Integer, Employee>> cur = cache.query(qry)) {
        for (Cache.Entry<Integer, Employee> e : cur) {
            assertNotNull(e);

            if (keepBinary) {
                assertTrue(((BinaryObject)e.getValue())
                    .field("name").toString().startsWith(JOHN_CONNOR));
            }
            else {
                assertTrue(e.getValue().name.startsWith(JOHN_CONNOR));
            }
        }

        populateData(cache, SARAH_CONNOR);

        assertTrue("Receive all expected events",
            transUpdCntLatch.await(DFLT_LATCH_TIMEOUT, MILLISECONDS));
        assertEquals("Count of updated records equal to expected", expTransCnt, transCnt.get());

    }
}
 
Example 9
Source File: IgniteCacheBinaryEntryProcessorSelfTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * @param cacheMode Cache mode to test.
 * @param atomicityMode Atomicity mode to test.
 * @throws Exception
 */
private void checkInvokeBinaryObject(CacheMode cacheMode, CacheAtomicityMode atomicityMode) throws Exception {
    Ignite client = ignite(SRV_CNT);

    IgniteCache<Integer, TestValue> clientCache = client.createCache(cacheConfiguration(cacheMode, atomicityMode));

    try {
        IgniteBinary binary = client.binary();

        for (int i = 0; i < 100; i++) {
            clientCache.put(i, new TestValue(i, "value-" + i));

            BinaryObjectBuilder bldr = binary.builder("NoClass");

            bldr.setField("val", i);
            bldr.setField("strVal", "value-" + i);

            clientCache.withKeepBinary().put(-(i + 1), bldr.build());
        }

        IgniteCache<Integer, BinaryObject> binaryClientCache = clientCache.withKeepBinary();

        for (int i = 0; i < 100; i++) {
            binaryClientCache.invoke(i, new TestEntryProcessor());
            binaryClientCache.invoke(-(i + 1), new TestEntryProcessor());
        }

        for (int g = 0; g < NODES; g++) {
            IgniteCache<Integer, TestValue> nodeCache = ignite(g).cache(DEFAULT_CACHE_NAME);
            IgniteCache<Integer, BinaryObject> nodeBinaryCache = nodeCache.withKeepBinary();

            for (int i = 0; i < 100; i++) {
                TestValue updated = nodeCache.get(i);

                assertEquals((Integer)(i + 1), updated.value());
                assertEquals("updated-" + i, updated.stringValue());

                BinaryObject updatedBinary = nodeBinaryCache.get(i);
                assertEquals(new Integer(i + 1), updatedBinary.field("val"));
                assertEquals("updated-" + i, updatedBinary.field("strVal"));

                updatedBinary = nodeBinaryCache.get(-(i + 1));
                assertEquals(new Integer(i + 1), updatedBinary.field("val"));
                assertEquals("updated-" + i, updatedBinary.field("strVal"));
            }
        }
    }
    finally {
        client.destroyCache(DEFAULT_CACHE_NAME);
    }
}
 
Example 10
Source File: GridCacheBinaryAtomicEntryProcessorDeploymentSelfTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * @throws Exception Exception.
 */
private void doTestGet(boolean withKeepBinary) throws Exception {
    try {
        startGrid(0);

        startClientGrid(1);

        Class valCls = grid(1).configuration().getClassLoader().loadClass(TEST_VALUE);

        assertTrue(grid(1).configuration().isClientMode());
        assertFalse(grid(0).configuration().isClientMode());

        IgniteCache cache1 = grid(1).cache(DEFAULT_CACHE_NAME);
        IgniteCache cache0 = grid(0).cache(DEFAULT_CACHE_NAME);

        if (withKeepBinary) {
            cache1 = cache1.withKeepBinary();
            cache0 = cache0.withKeepBinary();
        }

        cache1.put("key", valCls.newInstance());

        if (withKeepBinary) {
            BinaryObject obj = (BinaryObject)(cache0.get("key"));

            try {
                obj.deserialize();

                fail("Exception did not happened.");
            }
            catch (BinaryInvalidTypeException ignored) {
                // No-op.
            }
        }
        else
            try {
                cache0.get("key");

                fail("Exception did not happened.");
            }
            catch (CacheException ex) {
                assertTrue(X.hasCause(ex, BinaryInvalidTypeException.class));
            }
    }
    finally {
        stopAllGrids();
    }
}