org.apache.ignite.IgniteCache

Here are the examples of the java api org.apache.ignite.IgniteCache taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

168 Examples 7

19 Source : CacheListIgnite.java
with Mozilla Public License 2.0
from xjc-opensource

/**
 * @author ben
 * @replacedle: basic
 * @Description:
 */
public clreplaced CacheListIgnite<T> extends BaseCacheList<T> {

    private IgniteCache<String, T> msgList;

    public void setMsgList(IgniteCache<String, ?> msgList) {
    }

    public CacheListIgnite(String cacheName, Ignite ignite) {
        super(cacheName);
        CacheConfiguration<String, T> cacheConfiguration = new CacheConfiguration<String, T>();
        cacheConfiguration.setDataRegionName("persistence-data-region").setCacheMode(CacheMode.LOCAL).setName(getCacheName());
        this.msgList = (IgniteCache<String, T>) ignite.getOrCreateCache(cacheConfiguration);
    }

    @Override
    public boolean put(String key, T value) {
        msgList.put(key, value);
        return true;
    }

    @Override
    public T get(String key) {
        if (msgList.containsKey(key)) {
            return msgList.get(key);
        } else {
            return null;
        }
    }

    @Override
    public T remove(String key) {
        return msgList.getAndRemove(key);
    }

    @Override
    public long size() {
        return msgList.size();
    }

    @Override
    public boolean exists(String key) {
        return msgList.containsKey(key);
    }
}

19 Source : IgniteDatastoreProvider.java
with GNU Lesser General Public License v2.1
from hibernate

private <K, V> IgniteCache<K, V> getCache(String enreplacedyCacheName, boolean keepBinary) {
    IgniteCache<K, V> cache = null;
    try {
        cache = cacheManager.cache(enreplacedyCacheName);
    } catch (IllegalStateException ex) {
        if (Ignition.state(gridName) == IgniteState.STOPPED) {
            log.stoppedIgnite();
            restart();
            cache = cacheManager.cache(enreplacedyCacheName);
        } else {
            throw ex;
        }
    }
    if (cache == null) {
        throw log.cacheNotFound(enreplacedyCacheName);
    }
    if (keepBinary) {
        cache = cache.withKeepBinary();
    }
    return cache;
}

19 Source : IgniteDatastoreProvider.java
with GNU Lesser General Public License v2.1
from hibernate

/**
 * Converting enreplacedy key to cache key
 *
 * @param key enreplacedy key
 * @return string key
 */
public Object createKeyObject(EnreplacedyKey key) {
    Object result = null;
    if (key.getColumnValues().length == 1) {
        IgniteCache<Object, BinaryObject> enreplacedyCache = getEnreplacedyCache(key.getMetadata());
        CacheConfiguration cacheConfig = enreplacedyCache.getConfiguration(CacheConfiguration.clreplaced);
        result = toValidKeyObject(key.getColumnValues()[0], cacheConfig.getKeyType());
    } else {
        BinaryObjectBuilder builder = createBinaryObjectBuilder(findKeyType(key.getMetadata()));
        for (int i = 0; i < key.getColumnNames().length; i++) {
            builder.setField(StringHelper.stringAfterPoint(key.getColumnNames()[i]), key.getColumnValues()[i]);
        }
        result = builder.build();
    }
    return result;
}

19 Source : IgniteDialect.java
with GNU Lesser General Public License v2.1
from hibernate

@Override
public Tuple createTuple(EnreplacedyKey key, OperationContext operationContext) {
    IgniteCache<Object, BinaryObject> enreplacedyCache = provider.getEnreplacedyCache(key.getMetadata());
    if (enreplacedyCache == null) {
        throw log.cacheNotFound(key.getMetadata().getTable());
    }
    Object id = provider.createKeyObject(key);
    return new Tuple(new IgniteTupleSnapshot(id, null, key.getMetadata()), SnapshotType.INSERT);
}

19 Source : IgniteNodeCacheProxy.java
with Apache License 2.0
from apache

/**
 * Implementation of {@link IgniteCacheProxy} that provides access to Ignite cache through {@link IgniteCache} instance.
 */
public clreplaced IgniteNodeCacheProxy<K, V> implements IgniteCacheProxy<K, V> {

    /**
     * {@link IgniteCache} instance to which operations are delegated.
     */
    private final IgniteCache<K, V> cache;

    /**
     */
    public IgniteNodeCacheProxy(IgniteCache<K, V> cache) {
        this.cache = cache;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public V get(K key) throws ClientException {
        return cache.get(key);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void put(K key, V val) throws ClientException {
        cache.put(key, val);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public int size(CachePeekMode... peekModes) throws ClientException {
        return cache.size(peekModes);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Map<K, V> getAll(Set<? extends K> keys) throws ClientException {
        return cache.getAll(keys);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void putAll(Map<? extends K, ? extends V> map) throws ClientException {
        cache.putAll(map);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean remove(K key) throws ClientException {
        return cache.remove(key);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void removeAll(Set<? extends K> keys) throws ClientException {
        cache.removeAll(keys);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void clear() throws ClientException {
        cache.clear();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public IgniteCacheProxy<K, V> withExpiryPolicy(ExpiryPolicy expirePlc) {
        return new IgniteNodeCacheProxy<>(cache.withExpiryPolicy(expirePlc));
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public <R> QueryCursor<R> query(Query<R> qry) {
        return cache.query(qry);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean containsKey(K key) {
        return cache.containsKey(key);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @NotNull
    public Iterator<Cache.Entry<K, V>> iterator() {
        return cache.<Cache.Entry<K, V>>query(new ScanQuery<>()).getAll().iterator();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String getName() {
        return cache.getName();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public IgniteCacheProxy<K, V> withSkipStore() {
        return new IgniteNodeCacheProxy<>(cache.withSkipStore());
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public V getAndPutIfAbsent(K key, V val) {
        return cache.getAndPutIfAbsent(key, val);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void removeAll() {
        cache.removeAll();
    }

    /**
     * @return {@link IgniteCache} instance to which operations are delegated.
     */
    @Override
    public IgniteCache<K, V> delegate() {
        return cache;
    }
}

18 Source : TruncateSelectionTask.java
with Apache License 2.0
from techbysample

private Chromosome getChromosome(Long key) {
    IgniteCache<Long, Chromosome> cache = ignite.cache(GAGridConstants.POPULATION_CACHE);
    StringBuffer sbSqlClause = new StringBuffer();
    sbSqlClause.append("_key IN (");
    sbSqlClause.append(key);
    sbSqlClause.append(")");
    Chromosome chromosome = null;
    SqlQuery sql = new SqlQuery(Chromosome.clreplaced, sbSqlClause.toString());
    try (QueryCursor<Entry<Long, Chromosome>> cursor = cache.query(sql)) {
        for (Entry<Long, Chromosome> e : cursor) chromosome = (e.getValue());
    }
    return chromosome;
}

18 Source : IgniteAlertsStore.java
with Apache License 2.0
from Romeh

@Override
public void deleteAlertEntry(String alertId) {
    final IgniteCache<String, AlertEntry> alertsCache = getAlertsCache();
    alertsCache.remove(alertId);
}

18 Source : IgniteWriteJournal.java
with Apache License 2.0
from Romeh

private Void AsyncReplayMessages(String persistenceId, long fromSequenceNr, long toSequenceNr, long max, Consumer<PersistentRepr> replayCallback) {
    if (log.isDebugEnabled()) {
        log.debug("doAsyncReplayMessages with params persistenceId: '{}' :fromSequenceNr {} :toSequenceNr {} :max {}", persistenceId, fromSequenceNr, toSequenceNr, max);
    }
    final IgniteCache<Long, BinaryObject> journalBinary = cache.withKeepBinary();
    try (QueryCursor<Cache.Entry<Long, BinaryObject>> query = journalBinary.query(new SqlQuery<Long, BinaryObject>(JournalItem.clreplaced, "sequenceNr >= ? AND sequenceNr <= ? AND persistenceId=?").setArgs(fromSequenceNr, toSequenceNr, persistenceId))) {
        replyMsgs(persistenceId, max, replayCallback, query);
    }
    return null;
}

18 Source : IgniteDialect.java
with GNU Lesser General Public License v2.1
from hibernate

@Override
public void removeTuple(EnreplacedyKey key, TupleContext tupleContext) {
    IgniteCache<Object, BinaryObject> enreplacedyCache = provider.getEnreplacedyCache(key.getMetadata());
    enreplacedyCache.remove(provider.createKeyObject(key));
}

18 Source : IgniteDistributedLock.java
with GNU General Public License v2.0
from futurewei-cloud

public clreplaced IgniteDistributedLock implements IDistributedLock {

    private static final Logger logger = LoggerFactory.getLogger();

    private final String name;

    private IgniteCache<String, String> cache;

    private int tryInterval;

    public IgniteDistributedLock(Ignite ignite, String name, int tryInterval, int expireTime) {
        this.name = name;
        try {
            CacheConfiguration<String, String> cfg = new CacheConfiguration<>();
            cfg.setName(name);
            cfg.setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(new Duration(TimeUnit.SECONDS, expireTime)));
            cache = ignite.getOrCreateCache(cfg);
            this.tryInterval = tryInterval;
        } catch (ClientException e) {
            logger.log(Level.WARNING, "Create distributed lock cache failed:" + e.getMessage());
        } catch (Exception e) {
            logger.log(Level.WARNING, "Unexpected failure:" + e.getMessage());
        }
        replacedert.notNull(ignite, "Create distributed lock failed");
    }

    @Override
    public void lock(String lockKey) throws DistributedLockException {
        boolean locked = false;
        String lockKeyWithPrefix = getRealKey(lockKey);
        try {
            while (!locked) {
                locked = cache.putIfAbsent(lockKeyWithPrefix, "lock");
                if (!locked) {
                    Thread.sleep(this.tryInterval);
                }
            }
        } catch (Exception e) {
            logger.log(Level.WARNING, "Ignite lock error:" + e.getMessage());
            throw new DistributedLockException(e.getMessage());
        }
    }

    @Override
    public Boolean tryLock(String lockKey) {
        String lockKeyWithPrefix = getRealKey(lockKey);
        try {
            return cache.putIfAbsent(lockKeyWithPrefix, "lock");
        } catch (Exception e) {
            logger.log(Level.WARNING, "Ignite lock error:" + e.getMessage());
            return false;
        }
    }

    @Override
    public String getLockPrefix() {
        return this.name;
    }

    @Override
    public void unlock(String lockKey) throws DistributedLockException {
        String lockKeyWithPrefix = getRealKey(lockKey);
        try {
            cache.remove(lockKeyWithPrefix);
        } catch (Exception e) {
            logger.log(Level.WARNING, "Ignite unlock error:" + e.getMessage());
            throw new DistributedLockException(e.getMessage());
        }
    }
}

18 Source : IgniteDbCache.java
with GNU General Public License v2.0
from futurewei-cloud

public clreplaced IgniteDbCache<K, V> implements IgniteICache<K, V> {

    private static final Logger logger = LoggerFactory.getLogger();

    private static final int RESULT_THRESHOLD_SIZE = 100000;

    private IgniteCache<K, V> cache;

    private final IgniteTransaction transaction;

    public IgniteDbCache(Ignite ignite, String name) {
        try {
            this.cache = ignite.getOrCreateCache(name);
        } catch (javax.cache.CacheException e) {
            logger.log(Level.WARNING, "Create cache for client " + name + " failed:" + e.getMessage());
        } catch (Exception e) {
            logger.log(Level.WARNING, "Unexpected failure:" + e.getMessage());
        }
        replacedert.notNull(cache, "Create cache for client " + name + "failed");
        this.transaction = new IgniteTransaction(ignite);
    }

    public IgniteDbCache(Ignite client, String name, ExpiryPolicy ep) {
        try {
            this.cache = client.getOrCreateCache(name);
            this.cache = this.cache.withExpiryPolicy(ep);
        } catch (javax.cache.CacheException e) {
            logger.log(Level.WARNING, "Create cache for client " + name + " failed:" + e.getMessage());
        } catch (Exception e) {
            logger.log(Level.WARNING, "Unexpected failure:" + e.getMessage());
        }
        replacedert.notNull(this.cache, "Create cache for client " + name + "failed");
        this.transaction = new IgniteTransaction(client);
    }

    @Override
    public V get(K key) throws CacheException {
        try {
            return cache.get(key);
        } catch (TransactionException e) {
            logger.log(Level.WARNING, "IgniteCache get operation error:" + e.getMessage());
            throw new CacheException(e.getMessage());
        }
    }

    @Override
    public void put(K key, V value) throws CacheException {
        try {
            cache.put(key, value);
        } catch (TransactionException e) {
            logger.log(Level.WARNING, "IgniteCache put operation error:" + e.getMessage());
            throw new CacheException(e.getMessage());
        }
    }

    @Override
    public Boolean putIfAbsent(K var1, V var2) throws CacheException {
        return cache.putIfAbsent(var1, var2);
    }

    @Override
    public boolean containsKey(K key) throws CacheException {
        try {
            return cache.containsKey(key);
        } catch (TransactionException e) {
            logger.log(Level.WARNING, "IgniteCache containsKey operation error:" + e.getMessage());
            throw new CacheException(e.getMessage());
        }
    }

    @Override
    public Map<K, V> getAll(Set<K> keys) throws CacheException {
        return cache.getAll(keys);
    }

    @Override
    public Map<K, V> getAll() throws CacheException {
        Query<Cache.Entry<K, V>> qry = new ScanQuery<>();
        QueryCursor<Cache.Entry<K, V>> cur = cache.query(qry);
        return cur.getAll().stream().collect(Collectors.toMap(Cache.Entry::getKey, Cache.Entry::getValue));
    }

    @Override
    public void putAll(Map<? extends K, ? extends V> items) throws CacheException {
        try {
            cache.putAll(items);
        } catch (IgniteException e) {
            logger.log(Level.WARNING, "IgniteCache putAll operation error:" + e.getMessage());
            throw new CacheException(e.getMessage());
        }
    }

    @Override
    public boolean remove(K key) throws CacheException {
        try {
            return cache.remove(key);
        } catch (IgniteException e) {
            logger.log(Level.WARNING, "IgniteCache remove operation error:" + e.getMessage());
            throw new CacheException(e.getMessage());
        }
    }

    @Override
    public V get(Map<String, Object[]> filterParams) throws CacheException {
        IgniteBiPredicate<String, BinaryObject> predicate = MapPredicate.getInstance(filterParams);
        return get(predicate);
    }

    @Override
    public <E1, E2> V get(IgniteBiPredicate<E1, E2> igniteBiPredicate) throws CacheException {
        QueryCursor<Cache.Entry<E1, E2>> cursor = cache.withKeepBinary().query(ScanQueryBuilder.newScanQuery(igniteBiPredicate));
        List<Cache.Entry<E1, E2>> result = cursor.getAll();
        if (result.size() > 1) {
            throw new CacheException("more than one rows found!");
        }
        if (result.isEmpty()) {
            return null;
        }
        E2 obj = result.get(0).getValue();
        if (obj instanceof BinaryObject) {
            BinaryObject binaryObject = (BinaryObject) obj;
            return binaryObject.deserialize();
        } else {
            throw new CacheException("no support for object type:" + obj.getClreplaced().getName());
        }
    }

    @Override
    public <E1, E2> Map<K, V> getAll(Map<String, Object[]> filterParams) throws CacheException {
        IgniteBiPredicate<String, BinaryObject> predicate = MapPredicate.getInstance(filterParams);
        return getAll(predicate);
    }

    @Override
    public <E1, E2> Map<K, V> getAll(IgniteBiPredicate<E1, E2> igniteBiPredicate) throws CacheException {
        QueryCursor<Cache.Entry<E1, E2>> cursor = cache.withKeepBinary().query(ScanQueryBuilder.newScanQuery(igniteBiPredicate));
        List<Cache.Entry<E1, E2>> result = cursor.getAll();
        if (result.size() >= RESULT_THRESHOLD_SIZE) {
            throw new CacheException("too many rows found!");
        }
        Map<K, V> values = new HashMap<>(result.size());
        for (Cache.Entry<E1, E2> entry : result) {
            E2 obj = entry.getValue();
            if (obj instanceof BinaryObject) {
                BinaryObject binaryObject = (BinaryObject) obj;
                values.put((K) entry.getKey(), binaryObject.deserialize());
            } else {
                throw new CacheException("no support for object type:" + obj.getClreplaced().getName());
            }
        }
        return values;
    }

    @Override
    public long size() {
        return cache.size(CachePeekMode.ALL);
    }

    @Override
    public Transaction getTransaction() {
        return transaction;
    }
}

18 Source : BinaryObjectUtil.java
with Apache License 2.0
from cording

/**
 * 获取ddl定义的表的valueType值
 */
public String getValueType(String cacheName) {
    IgniteCache<Object, BinaryObject> cache = ignite.cache(cacheName.toLowerCase()).withKeepBinary();
    List<QueryEnreplacedy> list = (ArrayList) cache.getConfiguration(CacheConfiguration.clreplaced).getQueryEnreplacedies();
    if (list.size() == 1) {
        return list.get(0).findValueType();
    } else {
        throw new RuntimeException(String.format("cache[%s] not find value type\n", cacheName));
    }
}

18 Source : BinaryObjectUtil.java
with Apache License 2.0
from cording

/**
 * 获取ddl定义的表的keyType值
 */
public String getKeyType(String cacheName) {
    IgniteCache<Object, BinaryObject> cache = ignite.cache(cacheName.toLowerCase()).withKeepBinary();
    List<QueryEnreplacedy> list = (ArrayList) cache.getConfiguration(CacheConfiguration.clreplaced).getQueryEnreplacedies();
    if (list.size() == 1) {
        return list.get(0).findKeyType();
    } else {
        throw new RuntimeException(String.format("cache[%s] not find key type\n", cacheName));
    }
}

18 Source : AffinityMappedController.java
with Apache License 2.0
from cording

/**
 * 并置查询
 */
private void sqlQueryWithJoin() {
    IgniteCache<PersonKey, Person> cache = ignite.cache("CollocatedPersons");
    // ignite.cluster().forRemotes().ignite().cache("CollocatedPersons").lock(1);
    /**
     * 关联的缓存需要指定模式名(缓存名)
     *  例如下面这个sql关联Organization的时候需要加上Organizations作为前缀
     *  而Person的缓存Persons会作为默认模式名,所以不需要额外指定
     */
    String joinSql = "from Person, \"Organizations\".Organization as org " + "where Person.orgId = org.id " + "and lower(org.name) = lower(?)";
    print("Following people are 'ApacheIgnite' employees: ", cache.query(new SqlQuery<PersonKey, Person>(Person.clreplaced, joinSql).setArgs("ApacheIgnite")).getAll());
    print("Following people are 'Other' employees: ", cache.query(new SqlQuery<PersonKey, Person>(Person.clreplaced, joinSql).setArgs("Other")).getAll());
}

18 Source : SpringCacheTest.java
with Apache License 2.0
from apache

/**
 * Tests for {@link SpringCache}
 */
public clreplaced SpringCacheTest extends GridCommonAbstractTest {

    /**
     */
    private static Ignite ignite;

    /**
     * Wrapped cache.
     */
    private IgniteCache nativeCache;

    /**
     * Working cache.
     */
    private SpringCache springCache;

    /**
     */
    private String cacheName;

    /**
     * {@inheritDoc}
     */
    @Override
    protected void beforeTestsStarted() throws Exception {
        super.beforeTestsStarted();
        ignite = startGrid();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void afterTestsStopped() throws Exception {
        G.stop(true);
    }

    /**
     * {@inheritDoc}
     */
    @SuppressWarnings("unchecked")
    @Override
    protected void beforeTest() throws Exception {
        super.beforeTest();
        cacheName = String.valueOf(System.currentTimeMillis());
        nativeCache = ignite.getOrCreateCache(cacheName);
        springCache = new SpringCache(new IgniteNodeCacheProxy<>(nativeCache), null);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void afterTest() throws Exception {
        super.afterTest();
        ignite.destroyCache(cacheName);
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testGetName() throws Exception {
        replacedertEquals(cacheName, springCache.getName());
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testGetNativeCache() throws Exception {
        replacedertEquals(nativeCache, springCache.getNativeCache());
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testGetByKey() throws Exception {
        String key = "key";
        String value = "value";
        springCache.put(key, value);
        replacedertEquals(value, springCache.get(key).get());
        replacedertNull(springCache.get("wrongKey"));
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testGetByKeyType() throws Exception {
        String key = "key";
        String value = "value";
        springCache.put(key, value);
        replacedertEquals(value, springCache.get(key, String.clreplaced));
        try {
            springCache.get(key, Integer.clreplaced);
            fail("Missing exception");
        } catch (Exception e) {
            replacedertTrue(e.getMessage().startsWith("Cached value is not of required type [cacheName=" + cacheName));
        }
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testPut() throws Exception {
        String key = "key";
        replacedertNull(springCache.get(key));
        String value = "value";
        springCache.put(key, value);
        replacedertEquals(value, springCache.get(key).get());
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testPutIfAbsent() throws Exception {
        String key = "key";
        String expected = "value";
        replacedertNull(springCache.putIfAbsent(key, expected));
        replacedertEquals(expected, springCache.putIfAbsent(key, "wrongValue").get());
        replacedertEquals(expected, springCache.get(key).get());
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testEvict() throws Exception {
        String key = "key";
        replacedertNull(springCache.get(key));
        springCache.put(key, "value");
        replacedertNotNull(springCache.get(key));
        springCache.evict(key);
        replacedertNull(springCache.get(key));
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testClear() throws Exception {
        String key;
        springCache.put((key = "key1"), "value1");
        replacedertNotNull(springCache.get(key));
        springCache.put((key = "key2"), "value2");
        replacedertNotNull(springCache.get(key));
        springCache.put((key = "key3"), "value3");
        replacedertNotNull(springCache.get(key));
        springCache.clear();
        replacedertNull(springCache.get("key1"));
        replacedertNull(springCache.get("key2"));
        replacedertNull(springCache.get("key3"));
    }
}

18 Source : IgniteJmsStreamerTest.java
with Apache License 2.0
from apache

/**
 */
private void replacedertAllCacheEntriesLoaded() {
    // Get the cache and check that the entries are present
    IgniteCache<String, String> cache = grid().cache(DEFAULT_CACHE_NAME);
    for (Map.Entry<String, String> entry : TEST_DATA.entrySet()) replacedertEquals(entry.getValue(), cache.get(entry.getKey()));
}

17 Source : ITGetIgniteCache.java
with Apache License 2.0
from wangrenlei

@AfterClreplaced
public static void teardown() {
    runner = null;
    IgniteCache<String, byte[]> cache = getIgniteCache.getIgniteCache();
    if (cache != null)
        cache.destroy();
    getIgniteCache = null;
}

17 Source : GAGrid.java
with Apache License 2.0
from techbysample

/**
 * Calculate average fitness value
 *
 * @return Double
 */
private Double calculateAverageFitness() {
    double avgFitnessScore = 0;
    IgniteCache<Long, Gene> cache = ignite.cache(GAGridConstants.POPULATION_CACHE);
    // Execute query to get names of all employees.
    SqlFieldsQuery sql = new SqlFieldsQuery("select AVG(FITNESSSCORE) from Chromosome");
    // Iterate over the result set.
    try (QueryCursor<List<?>> cursor = cache.query(sql)) {
        for (List<?> row : cursor) avgFitnessScore = (Double) row.get(0);
    }
    return avgFitnessScore;
}

17 Source : TextQueryExample.java
with GNU General Public License v3.0
from srecon

/**
 * Example for TEXT queries using LUCENE-based indexing of people's job name.
 */
private static void textQuery() {
    IgniteCache<Integer, Company> cache = Ignition.ignite().cache(COMPANY_CACHE_NAME);
    // Query for all companies which has a text "John".
    TextQuery<Integer, Company> john = new TextQuery<>(Company.clreplaced, "John");
    // Query for all companies which has a text "primavera".
    TextQuery<Integer, Company> primavera = new TextQuery<>(Company.clreplaced, "beauty saloon");
    log("==So many companies with information about 'John'==", cache.query(john).getAll());
    log("==A company which name with ' beauty salon'==", cache.query(primavera).getAll());
}

17 Source : AsyncBankServiceImpl.java
with GNU General Public License v3.0
from srecon

/**
 * Created by mikl on 26.10.16.
 */
public clreplaced AsyncBankServiceImpl implements AsyncBankService, Service {

    @IgniteInstanceResource
    private Ignite ignite;

    IgniteCache<AccountCacheKey, AccountCacheData> accountCache;

    private String zeroMqBrokerAddress;

    public AsyncBankServiceImpl(String zeroMqBrokerAddress) {
        this.zeroMqBrokerAddress = zeroMqBrokerAddress;
    }

    @Override
    public void cancel(ServiceContext serviceContext) {
    }

    @Override
    public void init(ServiceContext serviceContext) throws Exception {
        accountCache = ignite.getOrCreateCache(BankDataGenerator.ACCOUNT_CACHE);
    }

    @Override
    public void execute(ServiceContext serviceContext) throws Exception {
        ObjectMapper objectMapper = new ObjectMapper();
        Context context = ZMQ.context(1);
        // Socket to talk to server
        Socket responder = context.socket(ZMQ.REP);
        responder.connect(zeroMqBrokerAddress);
        ZMQ.PollItem[] items = { new ZMQ.PollItem(responder, ZMQ.Poller.POLLIN) };
        while (!Thread.currentThread().isInterrupted() && !serviceContext.isCancelled()) {
            // Wait for next request from client
            int rc = ZMQ.poll(items, 1000);
            if (rc == -1) {
                continue;
            }
            if (items[0].isReadable()) {
                String reqStr = responder.recvStr(0);
                System.out.printf("Received request: [%s]\n", reqStr);
                ValidateRequest req = objectMapper.readValue(reqStr, ValidateRequest.clreplaced);
                ValidateResponse result = validateOperation(req.getAccount(), req.getSum());
                System.out.printf("send response request: [%s]\n", result);
                responder.send(objectMapper.writeValuereplacedtring(result));
            }
        }
        System.out.println("Stop async read!");
        // We never get here but clean up anyhow
        responder.close();
        context.term();
    }

    private ValidateResponse validateOperation(String account, BigDecimal sum) {
        AccountKey key = new AccountKey(account);
        Lock lock = accountCache.lock(key);
        try {
            lock.lock();
            AccountData accountData = (AccountData) accountCache.get(key);
            if (accountData == null) {
                return ValidateResponse.error("Account not found!");
            }
            // clean today operations
            if (!accountData.getToday().equals(LocalDate.now())) {
                accountData.setTodayOperationSum(new BigDecimal(0));
                accountData.setToday(LocalDate.now());
                accountCache.put(key, accountData);
            }
            BigDecimal newOperationSum = accountData.getTodayOperationSum().add(sum);
            if (newOperationSum.compareTo(accountData.getDailyLimit()) > 0) {
                return ValidateResponse.DENIED;
            } else {
                accountData.setTodayOperationSum(newOperationSum);
                accountCache.put(key, accountData);
                return ValidateResponse.OK;
            }
        } finally {
            lock.unlock();
        }
    }
}

17 Source : IgniteTestHelper.java
with GNU Lesser General Public License v2.1
from hibernate

@Override
public long getNumberOfreplacedociations(SessionFactory sessionFactory, replacedociationStorageType type) {
    int replacedcociationCount = 0;
    Set<IgniteCache<Object, BinaryObject>> processedCaches = Collections.newSetFromMap(new IdenreplacedyHashMap<IgniteCache<Object, BinaryObject>, Boolean>());
    for (CollectionPersister collectionPersister : ((SessionFactoryImplementor) sessionFactory).getCollectionPersisters().values()) {
        replacedociationKeyMetadata replacedociationKeyMetadata = ((OgmCollectionPersister) collectionPersister).getreplacedociationKeyMetadata();
        IgniteCache<Object, BinaryObject> replacedociationCache = getreplacedociationCache(sessionFactory, replacedociationKeyMetadata);
        if (!processedCaches.contains(replacedociationCache)) {
            replacedcociationCount += replacedociationCache.size();
            processedCaches.add(replacedociationCache);
        }
    }
    return replacedcociationCount;
}

17 Source : IgniteDatastoreProvider.java
with GNU Lesser General Public License v2.1
from hibernate

/**
 * Finds key type name for cache for enreplacedies with composite id
 * @param keyMetadata
 * @return
 */
private String findKeyType(EnreplacedyKeyMetadata keyMetadata) {
    String result = compositeIdTypes.get(keyMetadata.getTable());
    if (result == null) {
        String cacheType = getEnreplacedyTypeName(keyMetadata.getTable());
        IgniteCache<Object, BinaryObject> cache = getEnreplacedyCache(keyMetadata);
        CacheConfiguration cacheConfig = cache.getConfiguration(CacheConfiguration.clreplaced);
        if (cacheConfig.getQueryEnreplacedies() != null) {
            for (QueryEnreplacedy qe : (Collection<QueryEnreplacedy>) cacheConfig.getQueryEnreplacedies()) {
                if (qe.getValueType() != null && cacheType.equalsIgnoreCase(qe.getValueType())) {
                    result = qe.getKeyType();
                    break;
                }
            }
        }
        if (result == null) {
            if (cacheConfig.getKeyType() != null) {
                result = cacheConfig.getKeyType().getSimpleName();
            }
            if (result == null) {
                // if nothing found we use id field name
                result = StringHelper.stringBeforePoint(keyMetadata.getColumnNames()[0]);
                result = capitalize(result);
            }
        }
        compositeIdTypes.put(keyMetadata.getTable(), result);
    }
    return result;
}

17 Source : IgniteDialect.java
with GNU Lesser General Public License v2.1
from hibernate

@Override
public Tuple getTuple(EnreplacedyKey key, OperationContext operationContext) {
    IgniteCache<Object, BinaryObject> enreplacedyCache = provider.getEnreplacedyCache(key.getMetadata());
    Object id = provider.createKeyObject(key);
    BinaryObject bo = enreplacedyCache.get(id);
    if (bo != null) {
        return new Tuple(new IgniteTupleSnapshot(id, bo, key.getMetadata()), SnapshotType.UPDATE);
    } else {
        return null;
    }
}

17 Source : SqlDataProcessing.java
with Apache License 2.0
from dmagda

/**
 * @param args
 */
public static void main(String[] args) {
    Ignition.setClientMode(true);
    try (Ignite ignite = Ignition.start("config/ignite-config.xml")) {
        IgniteCache cityCache = ignite.cache(CITY_CACHE_NAME);
        IgniteCache countryCache = ignite.cache(COUNTRY_CACHE_NAME);
        IgniteCache languageCache = ignite.cache(COUNTRY_LANGUAGE_CACHE_NAME);
        getMostPopulatedCities(countryCache);
        getTopCitiesInThreeCountries(countryCache);
        getCityDetails(cityCache, 5);
    }
}

17 Source : KeyValueDataProcessing.java
with Apache License 2.0
from dmagda

/**
 * @param args
 */
public static void main(String[] args) {
    Ignition.setClientMode(true);
    try (Ignite ignite = Ignition.start("config/ignite-config.xml")) {
        IgniteCache<CityKey, City> cityCache = ignite.cache(CITY_CACHE_NAME);
        accessCityCache(cityCache);
        migrateBetweenCities(ignite, cityCache);
    }
}

17 Source : KeyValueBinaryDataProcessing.java
with Apache License 2.0
from dmagda

/**
 * @param args
 */
public static void main(String[] args) {
    Ignition.setClientMode(true);
    try (Ignite ignite = Ignition.start("config/ignite-config.xml")) {
        IgniteCache<BinaryObject, BinaryObject> cityCacheBinary = ignite.cache(CITY_CACHE_NAME).withKeepBinary();
        accessCityCache(ignite, cityCacheBinary);
        migrateBetweenCities(ignite, cityCacheBinary);
    }
}

17 Source : CollocatedController.java
with Apache License 2.0
from cording

private String init() {
    if (init.get()) {
        return "already execute init.";
    }
    // 定义三个缓存
    CacheConfiguration<Long, X> xcf = new CacheConfiguration<Long, X>("X").setCacheMode(CacheMode.PARreplacedIONED).setIndexedTypes(Long.clreplaced, X.clreplaced);
    CacheConfiguration<AffinityKey<Long>, Y> ycf = new CacheConfiguration<AffinityKey<Long>, Y>("Y").setCacheMode(CacheMode.PARreplacedIONED).setIndexedTypes(Affinity.clreplaced, Y.clreplaced);
    CacheConfiguration<AffinityKey<Long>, Z> zcf = new CacheConfiguration<AffinityKey<Long>, Z>("Z").setCacheMode(CacheMode.PARreplacedIONED).setIndexedTypes(Affinity.clreplaced, Z.clreplaced);
    ignite.destroyCache("X");
    ignite.destroyCache("Y");
    ignite.destroyCache("Z");
    ignite.getOrCreateCache(xcf);
    ignite.getOrCreateCache(ycf);
    ignite.getOrCreateCache(zcf);
    IgniteCache<Long, X> xc = ignite.cache("X");
    IgniteCache<AffinityKey<Long>, Y> yc = ignite.cache("Y");
    IgniteCache<AffinityKey<Long>, Z> zc = ignite.cache("Z");
    // 加载数据
    Y y;
    Z z;
    for (long i = 0; i < 100; i++) {
        xc.put(i, new X(i, String.valueOf(i)));
        y = new Y(i, String.valueOf(i), i);
        yc.put(y.key(), y);
        z = new Z(i, String.valueOf(i), i);
        zc.put(z.key(), z);
    }
    init.set(true);
    return "all executed.";
}

17 Source : AffinityMappedController.java
with Apache License 2.0
from cording

/**
 * 非并置查询
 */
private void sqlQueryWithDistributedJoin() {
    IgniteCache<Long, Person> cache = ignite.cache("Persons");
    String joinSql = "from Person, \"Organizations\".Organization as org " + "where Person.orgId = org.id " + "and lower(org.name) = lower(?)";
    SqlQuery<Long, Person> qry = new SqlQuery<>(Person.clreplaced, joinSql);
    /**
     * 启用非并置的分布式关联
     * 查询映射的节点就会从远程节点通过发送广播或者单播请求的方式获取缺失的数据(本地不存在的数据)
     */
    qry.setDistributedJoins(true);
    print("Following people are 'ApacheIgnite' employees (distributed join): ", cache.query(qry.setArgs("ApacheIgnite")).getAll());
    print("Following people are 'Other' employees (distributed join): ", cache.query(qry.setArgs("Other")).getAll());
}

17 Source : AffinityKeyController.java
with Apache License 2.0
from cording

/**
 * 并置查询
 */
private void sqlQueryWithJoin() {
    IgniteCache<AffinityKey<Long>, Person> cache = ignite.cache("CollocatedPersons");
    // ignite.cluster().forRemotes().ignite().cache("CollocatedPersons").lock(1);
    /**
     * 关联的缓存需要指定模式名(缓存名)
     *  例如下面这个sql关联Organization的时候需要加上Organizations作为前缀
     *  而Person的缓存Persons会作为默认模式名,所以不需要额外指定
     */
    String joinSql = "from Person, \"Organizations\".Organization as org " + "where Person.orgId = org.id " + "and Person.salary = ?" + "and lower(org.name) = lower(?)";
    int i = IntStream.range(1, 101).skip((int) (100 * Math.random())).findFirst().getAsInt();
    long stime = System.nanoTime();
    List<Cache.Entry<AffinityKey<Long>, Person>> result = cache.query(new SqlQuery<AffinityKey<Long>, Person>(Person.clreplaced, joinSql).setArgs(1000 * i, "ApacheIgnite")).getAll();
    // print("Following people are 'ApacheIgnite' employees: ",
    // cache.query(new SqlQuery<AffinityKey<Long>, Person>(Person.clreplaced, joinSql).
    // setArgs("ApacheIgnite")).getAll());
    System.out.format("testWithAfty cost time [%s].\n", (System.nanoTime() - stime) / 1000000.00);
    print("Following people are 'ApacheIgnite' employees: ", result);
// print("Following people are 'Other' employees: ",
// cache.query(new SqlQuery<AffinityKey<Long>, Person>(Person.clreplaced, joinSql).
// setArgs("Other")).getAll());
}

17 Source : IgniteZeroMqStreamerTest.java
with Apache License 2.0
from apache

/**
 * Execute ZeroMQ streamer and checking cache content after streaming finished.
 * Set singleTupleExtractor via {@link ZeroMqStringSingleTupleExtractor} in streamer.
 *
 * @param streamer ZeroMQ streamer.
 * @param clientSocket ZeroMQ socket type.
 * @param topic Topic name for PUB-SUB.
 * @throws Exception Test exception.
 */
private void executeStreamer(IgniteZeroMqStreamer streamer, int clientSocket, byte[] topic) throws Exception {
    streamer.setSingleTupleExtractor(new ZeroMqStringSingleTupleExtractor());
    IgniteCache<Integer, String> cache = grid().cache(DEFAULT_CACHE_NAME);
    CacheListener listener = subscribeToPutEvents();
    streamer.start();
    replacedertEquals(0, cache.size(CachePeekMode.PRIMARY));
    startZeroMqClient(clientSocket, topic);
    CountDownLatch latch = listener.getLatch();
    latch.await();
    unsubscribeToPutEvents(listener);
    // Last element.
    int testId = CACHE_ENTRY_COUNT - 1;
    String cachedValue = cache.get(testId);
    // ZeroMQ message successfully put to cache.
    replacedertTrue(cachedValue != null && cachedValue.endsWith(String.valueOf(testId)));
    replacedertTrue(cache.size() == CACHE_ENTRY_COUNT);
    cache.clear();
}

17 Source : IgniteTwitterStreamerTest.java
with Apache License 2.0
from apache

/**
 * @param streamer Twitter streamer.
 * @throws InterruptedException Test exception.
 * @throws TwitterException Test exception.
 */
private void executeStreamer(TwitterStreamer streamer) throws InterruptedException, TwitterException {
    // Checking streaming.
    CacheListener lsnr = subscribeToPutEvents();
    streamer.start();
    try {
        streamer.start();
        fail("Successful start of already started Twitter Streamer");
    } catch (IgniteException ignored) {
    // No-op.
    }
    CountDownLatch latch = lsnr.getLatch();
    // Enough tweets was handled in 10 seconds. Limited by test's timeout.
    latch.await();
    unsubscribeToPutEvents(lsnr);
    streamer.stop();
    try {
        streamer.stop();
        fail("Successful stop of already stopped Twitter Streamer");
    } catch (IgniteException ignored) {
    // No-op.
    }
    // Checking cache content after streaming finished.
    Status status = TwitterObjectFactory.createStatus(tweet);
    IgniteCache<Long, String> cache = grid().cache(DEFAULT_CACHE_NAME);
    String cachedVal = cache.get(status.getId());
    // Tweet successfully put to cache.
    replacedertTrue(cachedVal != null && cachedVal.equals(status.getText()));
    // Same tweets does not produce duplicate entries.
    replacedertEquals(1, cache.size());
}

17 Source : IgniteSpringDataConnectionConfigurationTest.java
with Apache License 2.0
from apache

/**
 * Checks that repository created based on specified Spring application configuration is properly initialized and
 * got access to the Ignite cluster.
 */
private void checkRepositoryConfiguration(Clreplaced<?> cfgCls) {
    try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext()) {
        ctx.register(cfgCls);
        ctx.refresh();
        PersonRepository repo = ctx.getBean(PersonRepository.clreplaced);
        IgniteCache<Integer, Person> cache = grid(SRV_NAME).cache(CACHE_NAME);
        replacedertEquals(0, repo.count());
        replacedertEquals(0, cache.size());
        int key = 0;
        repo.save(key, new Person("Domenico", "Scarlatti"));
        replacedertEquals(1, repo.count());
        replacedertNotNull(cache.get(key));
    }
}

17 Source : IgniteNodeProxy.java
with Apache License 2.0
from apache

/**
 * {@inheritDoc}
 */
@Override
public <K, V> IgniteCacheProxy<K, V> cache(String name) {
    IgniteCache<K, V> cache = ignite.cache(name);
    return cache == null ? null : new IgniteNodeCacheProxy<>(cache);
}

17 Source : IgniteSpringDataConnectionConfigurationTest.java
with Apache License 2.0
from apache

/**
 * Checks that repository created based on specified Spring application configuration is properly initialized and
 * got access to the Ignite cluster.
 */
private void checkRepositoryConfiguration(Clreplaced<?> cfgCls, Clreplaced<? extends IgniteRepository<Object, Serializable>> repoCls) {
    try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext()) {
        ctx.register(cfgCls);
        ctx.refresh();
        IgniteRepository<Object, Serializable> repo = ctx.getBean(repoCls);
        IgniteCache<Object, Serializable> cache = grid(SRV_NAME).cache(CACHE_NAME);
        replacedertEquals(0, repo.count());
        replacedertEquals(0, cache.size());
        int key = 0;
        repo.save(key, "1");
        replacedertEquals(1, repo.count());
        replacedertNotNull(cache.get(key));
    }
}

17 Source : SpringCacheManager.java
with Apache License 2.0
from apache

/**
 * {@inheritDoc}
 */
@Override
protected SpringCache createCache(String name) {
    CacheConfiguration<Object, Object> cacheCfg = dynamicCacheCfg != null ? new CacheConfiguration<>(dynamicCacheCfg) : new CacheConfiguration<>();
    NearCacheConfiguration<Object, Object> nearCacheCfg = dynamicNearCacheCfg != null ? new NearCacheConfiguration<>(dynamicNearCacheCfg) : null;
    cacheCfg.setName(name);
    IgniteCache<Object, Object> cache = nearCacheCfg != null ? ignite.getOrCreateCache(cacheCfg, nearCacheCfg) : ignite.getOrCreateCache(cacheCfg);
    return new SpringCache(new IgniteNodeCacheProxy<>(cache), this);
}

17 Source : PubSubStreamerSelfTest.java
with Apache License 2.0
from apache

@Before
public void beforeTest() throws InterruptedException {
    this.ignite = Ignition.start(GRID_CONF_FILE);
    IgniteCache<Integer, String> igniteCache = ignite.getOrCreateCache(defaultCacheConfiguration());
}

17 Source : IgniteMqttStreamerTest.java
with Apache License 2.0
from apache

/**
 * @param cnt Count.
 */
private void replacedertCacheEntriesLoaded(int cnt) {
    // get the cache and check that the entries are present
    IgniteCache<Integer, String> cache = grid().cache(DEFAULT_CACHE_NAME);
    // for each key from 0 to count from the TEST_DATA (ordered by key), check that the entry is present in cache
    for (Integer key : new ArrayList<>(new TreeSet<>(TEST_DATA.keySet())).subList(0, cnt)) replacedertEquals(TEST_DATA.get(key), cache.get(key));
    // replacedert that the cache exactly the specified amount of elements
    replacedertEquals(cnt, cache.size(CachePeekMode.ALL));
    // remove the event listener
    grid().events(grid().cluster().forCacheNodes(DEFAULT_CACHE_NAME)).stopRemoteListen(remoteLsnr);
}

16 Source : GAGridUtils.java
with Apache License 2.0
from techbysample

/**
 * Retrieve genes in order
 *
 * @param ignite
 * @param chromosome
 * @return List<Gene>
 */
public static List<Gene> getGenesInOrderForChromosome(Ignite ignite, Chromosome chromosome) {
    List<Gene> genes = new ArrayList();
    IgniteCache<Long, Gene> cache = ignite.cache(GAGridConstants.GENE_CACHE);
    long[] primaryKeys = chromosome.getGenes();
    for (int k = 0; k < primaryKeys.length; k++) {
        StringBuffer sbSqlClause = new StringBuffer();
        sbSqlClause.append("_key IN ");
        sbSqlClause.append("(");
        sbSqlClause.append(primaryKeys[k]);
        sbSqlClause.append(")");
        SqlQuery sql = new SqlQuery(Gene.clreplaced, sbSqlClause.toString());
        try (QueryCursor<Entry<Long, Gene>> cursor = cache.query(sql)) {
            for (Entry<Long, Gene> e : cursor) genes.add(e.getValue());
        }
    }
    return genes;
}

16 Source : GAGridUtils.java
with Apache License 2.0
from techbysample

/**
 *  Retrieve chromosomes
 *
 * @param ignite
 * @param query
 * @return
 */
public static List<Chromosome> getChromosomes(Ignite ignite, String query) {
    List<Chromosome> chromosomes = new ArrayList();
    IgniteCache<Long, Chromosome> populationCache = ignite.getOrCreateCache(PopulationCacheConfig.populationCache());
    SqlQuery sql = new SqlQuery(Chromosome.clreplaced, query);
    try (QueryCursor<Entry<Long, Chromosome>> cursor = populationCache.query(sql)) {
        for (Entry<Long, Chromosome> e : cursor) chromosomes.add(e.getValue());
    }
    return chromosomes;
}

16 Source : GAGrid.java
with Apache License 2.0
from techbysample

/**
 * method replacedumes ChromosomeCriteria is set.
 *
 * @param k
 *            - gene index in Chromosome.
 * @return
 */
private long selectGeneByChromsomeCriteria(int k) {
    List<Gene> genes = new ArrayList();
    StringBuffer sbSqlClause = new StringBuffer("_val like '");
    sbSqlClause.append("%");
    sbSqlClause.append(config.getChromosomeCritiera().getCriteria().get(k));
    sbSqlClause.append("%'");
    IgniteCache<Long, Gene> cache = ignite.cache(GAGridConstants.GENE_CACHE);
    SqlQuery sql = new SqlQuery(Gene.clreplaced, sbSqlClause.toString());
    try (QueryCursor<Entry<Long, Gene>> cursor = cache.query(sql)) {
        for (Entry<Long, Gene> e : cursor) genes.add(e.getValue());
    }
    int idx = selectRandomIndex(genes.size());
    Gene gene = genes.get(idx);
    return gene.id();
}

16 Source : SqlQueryEmployees.java
with GNU General Public License v3.0
from srecon

/**
 * Output all employees those salary bigger than their direct manager (SQL-based fields queries and inner select).
 */
private static void sqlQueryEmployeesWithSalHigherManager() {
    IgniteCache<EmployeeKey, Employee> cache = Ignition.ignite().cache(EMPLOYEE_CACHE_NAME);
    // all employees those salary bigger than their direct manager.
    SqlFieldsQuery qry = new SqlFieldsQuery("select e.ename ,e.sal,m.ename,m.sal from Employee e, (select ename,empno,sal from Employee) m " + "where e.mgr = m.empno and e.sal > m.sal");
    log("==All employees those salary bigger than their direct manager==");
    logDecorated("||Employee||Emp.Salary||Manager||Mgr.Salary||", cache.query(qry).getAll());
}

16 Source : SqlQueryEmployees.java
with GNU General Public License v3.0
from srecon

/**
 * Example for SQL-based fields queries that return only required fields instead of whole key-value pairs.
 */
private static void groupByQuery() {
    IgniteCache<?, ?> cache = Ignition.ignite().cache(EMPLOYEE_CACHE_NAME);
    // Create query to get salary averages grouped by department name.
    // We don't need to perform any extra manual steps here, because
    // Employee data is colocated based on department IDs.
    SqlFieldsQuery qry = new SqlFieldsQuery("select avg(e.sal), d.dname " + "from Employee e, \"" + DEPARTMENT_CACHE_NAME + "\".Department d " + "where e.deptno = d.deptno " + "group by d.dname " + "having avg(e.sal) > ?");
    // Execute query to get collection of rows.
    logDecorated("==Average salaries per Department (group-by query)==", cache.query(qry.setArgs(500)).getAll());
}

16 Source : SqlQueryEmployees.java
with GNU General Public License v3.0
from srecon

/**
 * Example for SQL queries based on all employees working for a specific department.
 */
private static void sqlQueryWithJoin() {
    IgniteCache<EmployeeKey, Employee> cache = Ignition.ignite().cache(EMPLOYEE_CACHE_NAME);
    // Create query which joins on 2 types to select people for a specific department.
    SqlQuery<EmployeeKey, Employee> qry = new SqlQuery<>(Employee.clreplaced, "from Employee, \"" + DEPARTMENT_CACHE_NAME + "\".Department " + "where Employee.deptno = Department.deptno " + "and lower(Department.dname) = lower(?)");
    // Execute queries for find employees for different departments.
    logDecorated("==Following department 'Accounting' have employees (SQL join)==", cache.query(qry.setArgs("Accounting")).getAll());
    logDecorated("==Following department 'Sales' have employees (SQL join)==", cache.query(qry.setArgs("Sales")).getAll());
}

16 Source : BankServiceImpl.java
with GNU General Public License v3.0
from srecon

/**
 * Created by mikl on 26.10.16.
 */
public clreplaced BankServiceImpl implements BankService, Service {

    @ServiceResource(serviceName = LogService.NAME)
    private LogService logService;

    @IgniteInstanceResource
    private Ignite ignite;

    IgniteCache<AccountCacheKey, AccountCacheData> accountCache;

    @Override
    public boolean validateOperation(String account, BigDecimal sum) throws AccountNotFoundException, LogServiceException {
        AccountKey key = new AccountKey(account);
        Lock lock = accountCache.lock(key);
        try {
            lock.lock();
            AccountData accountData = (AccountData) accountCache.get(key);
            if (accountData == null) {
                throw new AccountNotFoundException(account);
            }
            // clean today operations
            if (!accountData.getToday().equals(LocalDate.now())) {
                accountData.setTodayOperationSum(new BigDecimal(0));
                accountData.setToday(LocalDate.now());
                accountCache.put(key, accountData);
            }
            BigDecimal newOperationSum = accountData.getTodayOperationSum().add(sum);
            if (newOperationSum.compareTo(accountData.getDailyLimit()) > 0) {
                logService.logOperation(account, false);
                return false;
            } else {
                accountData.setTodayOperationSum(newOperationSum);
                accountCache.put(key, accountData);
                logService.logOperation(account, true);
                return true;
            }
        } finally {
            lock.unlock();
        }
    }

    @Override
    public void cancel(ServiceContext serviceContext) {
    }

    @Override
    public void init(ServiceContext serviceContext) throws Exception {
        accountCache = ignite.getOrCreateCache(BankDataGenerator.ACCOUNT_CACHE);
    }

    @Override
    public void execute(ServiceContext serviceContext) throws Exception {
    }
}

16 Source : IgniteAlertsStore.java
with Apache License 2.0
from Romeh

@Override
public void updateAlertEntry(String serviceId, String serviceCode, AlertEntry alertEntry) {
    final IgniteCache<String, AlertEntry> alertsCache = getAlertsCache();
    // update the alert entry via cache invoke for atomicity
    alertsCache.invoke(alertEntry.getAlertId(), (mutableEntry, objects) -> {
        if (mutableEntry.exists() && mutableEntry.getValue() != null) {
            logger.debug("updating alert entry into the cache store invoke: {},{}", serviceId, serviceCode);
            mutableEntry.setValue(alertEntry);
        } else {
            throw new ResourceNotFoundException(String.format("Alert for %s with %s not found", serviceId, serviceCode));
        }
        // by api design nothing needed here
        return null;
    });
}

16 Source : ReadStoreStreamerService.java
with Apache License 2.0
from Romeh

/**
 * the read side service to show the case how you can stream stored write event store to a read side store using Rx java and ignite streamer APIs
 *
 * @author romeh
 */
@Component
public clreplaced ReadStoreStreamerService implements ApplicationListener<ContextRefreshedEvent> {

    private static final String JOURNAL_CACHE = "akka-journal";

    private static final String READ_CACHE = "Read-Store";

    private final IgniteExtension igniteExtension;

    private final ActorSystem actorSystem;

    private final IgniteCache<String, JournalReadItem> readStore;

    @Autowired
    public ReadStoreStreamerService(ActorSystem actorSystem) {
        this.actorSystem = actorSystem;
        this.igniteExtension = IgniteExtensionProvider.EXTENSION.get(actorSystem);
        // make sure the read store cache is created
        // usually you should not need that as the writer and reader should be different nodes
        this.readStore = getOrCreateReadStoreCache();
    }

    /**
     * @param orderId order id to get the status for
     * @return the order status if any
     */
    public JournalReadItem getOrderStatus(String orderId) throws OrderNotFoundException {
        return Optional.ofNullable(readStore.get(orderId)).orElseThrow(() -> new OrderNotFoundException("order is not found in the read store"));
    }

    /**
     * @param contextStartedEvent the spring context started event
     *                            start the events streamer once the spring context init is finished
     */
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextStartedEvent) {
        actorSystem.actorOf(Props.create(IgniteStreamerStarter.clreplaced, IgniteStreamerStarter::new), "IgniteStreamerActor");
    }

    /**
     * start the event streamer from the journal write event store to the read side cache store which store only query intersted data
     */
    private void startIgniteStreamer() {
        // streamer parameters
        Map<String, String> sourceMap = new HashMap<>();
        sourceMap.put(IgniteSourceConstants.CACHE_NAME, JOURNAL_CACHE);
        Map<String, String> sinkMap = new HashMap<>();
        sinkMap.put(IgniteSinkConstants.CACHE_NAME, READ_CACHE);
        sinkMap.put(IgniteSinkConstants.CACHE_ALLOW_OVERWRITE, "true");
        sinkMap.put(IgniteSinkConstants.SINGLE_TUPLE_EXTRACTOR_CLreplaced, ReadStoreExtractor.clreplaced.getName());
        // start the streamer
        final IgniteCacheEventStreamerRx journalStreamer = IgniteCacheEventStreamerRx.builderWithContinuousQuery().pollingInterval(500).flushBufferSize(5).retryTimesOnError(2).sourceCache(sourceMap, igniteExtension.getIgnite()).sinkCache(sinkMap, igniteExtension.getIgnite()).build();
        journalStreamer.execute();
    }

    /**
     * check if the read side cache is already created or create it if missing
     * usually you should not need that as the writer and reader should be different nodes
     */
    private IgniteCache<String, JournalReadItem> getOrCreateReadStoreCache() {
        IgniteCache<String, JournalReadItem> cache = igniteExtension.getIgnite().cache(READ_CACHE);
        if (null == cache) {
            CacheConfiguration<String, JournalReadItem> readItemCacheConfiguration = new CacheConfiguration<>();
            readItemCacheConfiguration.setBackups(1);
            readItemCacheConfiguration.setName(READ_CACHE);
            readItemCacheConfiguration.setAtomicityMode(CacheAtomicityMode.ATOMIC);
            readItemCacheConfiguration.setCacheMode(CacheMode.PARreplacedIONED);
            readItemCacheConfiguration.setQueryEnreplacedies(Collections.singletonList(createJournalBinaryQueryEnreplacedy()));
            cache = igniteExtension.getIgnite().getOrCreateCache(readItemCacheConfiguration);
        }
        return cache;
    }

    /**
     * @return QueryEnreplacedy which the binary query definition of the binary object stored into the read side cache
     */
    private QueryEnreplacedy createJournalBinaryQueryEnreplacedy() {
        QueryEnreplacedy queryEnreplacedy = new QueryEnreplacedy();
        queryEnreplacedy.setValueType(JournalReadItem.clreplaced.getName());
        queryEnreplacedy.setKeyType(String.clreplaced.getName());
        LinkedHashMap<String, String> fields = new LinkedHashMap<>();
        fields.put(JournalReadItem.ORDER_ID, String.clreplaced.getName());
        fields.put(JournalReadItem.STATUS_FIELD, String.clreplaced.getName());
        queryEnreplacedy.setFields(fields);
        queryEnreplacedy.setIndexes(Arrays.asList(new QueryIndex(JournalReadItem.ORDER_ID), new QueryIndex(JournalReadItem.STATUS_FIELD)));
        return queryEnreplacedy;
    }

    /**
     * simple akka actor to listen to the journal started event so it can start the event store streamer once the persistence store is running
     * usually you should not need that as the writer and reader should be different nodes but as here for the sake of the example we have reader and writer
     * running in the same server ignite node
     */
    private final clreplaced IgniteStreamerStarter extends AbstractActor {

        @Override
        public void preStart() {
            getContext().getSystem().eventStream().subscribe(getSelf(), JournalStarted.clreplaced);
        }

        @Override
        public Receive createReceive() {
            // start the streamer once it receive the journal started event
            return ReceiveBuilder.create().match(JournalStarted.clreplaced, journalStarted -> startIgniteStreamer()).build();
        }
    }
}

16 Source : JournalStoreInterceptor.java
with Apache License 2.0
from Romeh

@Override
public void onAfterPut(Cache.Entry<Long, JournalItem> entry) {
    IgniteCache<String, Long> sequenceNumberTrack = ignite.getOrCreateCache("sequenceNumberTrack");
    sequenceNumberTrack.invoke(entry.getValue().getPersistenceId(), (mutableEntry, objects) -> {
        if (mutableEntry.exists() && mutableEntry.getValue() != null) {
            // if it is less than the new sequence value , use it
            if (mutableEntry.getValue() < entry.getKey()) {
                mutableEntry.setValue(entry.getKey());
            }
        } else {
            // if does not exist , just use it
            mutableEntry.setValue(entry.getKey());
        }
        // by api design nothing needed here
        return null;
    });
}

16 Source : IgniteWriteJournal.java
with Apache License 2.0
from Romeh

private Void doAsyncDeleteMessages(String persistenceId, long toSequenceNr) {
    if (log.isDebugEnabled()) {
        log.debug("doAsyncDeleteMessagesTo persistenceId'{}' toSequenceNr : {}", persistenceId, toSequenceNr);
    }
    final IgniteCache<Long, BinaryObject> journalBinary = cache.withKeepBinary();
    List<List<?>> seq = journalBinary.query(new SqlFieldsQuery("select sequenceNr from JournalItem where sequenceNr <= ? and persistenceId=?").setArgs(toSequenceNr, persistenceId)).getAll();
    Set<Long> keys = listsToStreamLong(seq).collect(Collectors.toSet());
    if (log.isDebugEnabled()) {
        log.debug("remove keys {}", keys);
    }
    cache.removeAll(keys);
    return null;
}

16 Source : JournalCaches.java
with Apache License 2.0
from Romeh

/**
 * the wrapper for journal and sequence cache to be used by  {@link JournalCacheProvider}
 */
@Builder
@Getter
@ToString
public clreplaced JournalCaches {

    private IgniteCache<Long, JournalItem> journalCache;

    private IgniteCache<String, Long> sequenceCache;
}

16 Source : IgniteTestHelper.java
with GNU Lesser General Public License v2.1
from hibernate

@Override
public long getNumberOfEnreplacedies(SessionFactory sessionFactory) {
    int enreplacedyCount = 0;
    Set<IgniteCache<?, ?>> processedCaches = Collections.newSetFromMap(new IdenreplacedyHashMap<IgniteCache<?, ?>, Boolean>());
    for (EnreplacedyPersister enreplacedyPersister : ((SessionFactoryImplementor) sessionFactory).getEnreplacedyPersisters().values()) {
        IgniteCache<?, ?> enreplacedyCache = getEnreplacedyCache(sessionFactory, ((OgmEnreplacedyPersister) enreplacedyPersister).getEnreplacedyKeyMetadata());
        if (!processedCaches.contains(enreplacedyCache)) {
            enreplacedyCount += enreplacedyCache.size(CachePeekMode.ALL);
            processedCaches.add(enreplacedyCache);
        }
    }
    return enreplacedyCount;
}

See More Examples