Search in sources :

Example 61 with ClientMessage

use of com.hazelcast.client.impl.protocol.ClientMessage in project hazelcast by hazelcast.

the class ClientMessageReadHandler method onRead.

@Override
public void onRead(ByteBuffer src) throws Exception {
    int messagesCreated = 0;
    while (src.hasRemaining()) {
        final boolean complete = message.readFrom(src);
        if (!complete) {
            messageCounter.inc(messagesCreated);
            return;
        }
        //MESSAGE IS COMPLETE HERE
        if (message.isFlagSet(BEGIN_AND_END_FLAGS)) {
            //HANDLE-MESSAGE
            handleMessage(message);
            message = ClientMessage.create();
            messagesCreated++;
            continue;
        }
        // first fragment
        if (message.isFlagSet(BEGIN_FLAG)) {
            final BufferBuilder builder = new BufferBuilder();
            builderBySessionIdMap.put(message.getCorrelationId(), builder);
            builder.append(message.buffer(), 0, message.getFrameLength());
        } else {
            final BufferBuilder builder = builderBySessionIdMap.get(message.getCorrelationId());
            if (builder.position() == 0) {
                throw new IllegalStateException();
            }
            builder.append(message.buffer(), message.getDataOffset(), message.getFrameLength() - message.getDataOffset());
            if (message.isFlagSet(END_FLAG)) {
                final int msgLength = builder.position();
                ClientMessage cm = ClientMessage.createForDecode(builder.buffer(), 0);
                cm.setFrameLength(msgLength);
                //HANDLE-MESSAGE
                handleMessage(cm);
                builderBySessionIdMap.remove(message.getCorrelationId());
            }
        }
        message = ClientMessage.create();
        messagesCreated++;
    }
}
Also used : ClientMessage(com.hazelcast.client.impl.protocol.ClientMessage)

Example 62 with ClientMessage

use of com.hazelcast.client.impl.protocol.ClientMessage in project hazelcast by hazelcast.

the class AbstractClientCacheProxy method putToAllPartitionsAndWaitForCompletion.

private void putToAllPartitionsAndWaitForCompletion(List<Map.Entry<Data, Data>>[] entriesPerPartition, ExpiryPolicy expiryPolicy, long start) throws ExecutionException, InterruptedException {
    Data expiryPolicyData = toData(expiryPolicy);
    List<FutureEntriesTuple> futureEntriesTuples = new ArrayList<FutureEntriesTuple>(entriesPerPartition.length);
    for (int partitionId = 0; partitionId < entriesPerPartition.length; partitionId++) {
        List<Map.Entry<Data, Data>> entries = entriesPerPartition[partitionId];
        if (entries != null) {
            int completionId = nextCompletionId();
            // TODO If there is a single entry, we could make use of a put operation since that is a bit cheaper
            ClientMessage request = CachePutAllCodec.encodeRequest(nameWithPrefix, entries, expiryPolicyData, completionId);
            Future f = invoke(request, partitionId, completionId);
            futureEntriesTuples.add(new FutureEntriesTuple(f, entries));
        }
    }
    waitResponseFromAllPartitionsForPutAll(futureEntriesTuples, start);
}
Also used : ArrayList(java.util.ArrayList) ClientDelegatingFuture(com.hazelcast.client.util.ClientDelegatingFuture) Future(java.util.concurrent.Future) CompletedFuture(com.hazelcast.util.executor.CompletedFuture) ClientInvocationFuture(com.hazelcast.client.spi.impl.ClientInvocationFuture) ICompletableFuture(com.hazelcast.core.ICompletableFuture) Data(com.hazelcast.nio.serialization.Data) ClientMessage(com.hazelcast.client.impl.protocol.ClientMessage)

Example 63 with ClientMessage

use of com.hazelcast.client.impl.protocol.ClientMessage in project hazelcast by hazelcast.

the class AbstractClientCacheProxy method getAll.

@Override
public Map<K, V> getAll(Set<? extends K> keys, ExpiryPolicy expiryPolicy) {
    final long start = System.nanoTime();
    ensureOpen();
    validateNotNull(keys);
    if (keys.isEmpty()) {
        return emptyMap();
    }
    final Set<Data> keySet = new HashSet<Data>(keys.size());
    for (K key : keys) {
        final Data k = toData(key);
        keySet.add(k);
    }
    Map<K, V> result = createHashMap(keys.size());
    populateResultFromNearCache(keySet, result);
    if (keySet.isEmpty()) {
        return result;
    }
    List<Map.Entry<Data, Data>> entries;
    Map<Data, Long> reservations = createHashMap(keySet.size());
    try {
        for (Data key : keySet) {
            long reservationId = tryReserveForUpdate(key);
            if (reservationId != NOT_RESERVED) {
                reservations.put(key, reservationId);
            }
        }
        Data expiryPolicyData = toData(expiryPolicy);
        ClientMessage request = CacheGetAllCodec.encodeRequest(nameWithPrefix, keySet, expiryPolicyData);
        ClientMessage responseMessage = invoke(request);
        entries = CacheGetAllCodec.decodeResponse(responseMessage).response;
        for (Map.Entry<Data, Data> dataEntry : entries) {
            Data keyData = dataEntry.getKey();
            Data valueData = dataEntry.getValue();
            K key = toObject(keyData);
            V value = toObject(valueData);
            result.put(key, value);
            Long reservationId = reservations.get(keyData);
            if (reservationId != null) {
                storeInNearCache(keyData, valueData, value, reservationId, false);
                reservations.remove(keyData);
            }
        }
    } finally {
        releaseRemainingReservedKeys(reservations);
    }
    if (statisticsEnabled) {
        statistics.increaseCacheHits(entries.size());
        statistics.addGetTimeNanos(System.nanoTime() - start);
    }
    return result;
}
Also used : Data(com.hazelcast.nio.serialization.Data) ClientMessage(com.hazelcast.client.impl.protocol.ClientMessage) MapUtil.createHashMap(com.hazelcast.util.MapUtil.createHashMap) Map(java.util.Map) Collections.emptyMap(java.util.Collections.emptyMap) AbstractMap(java.util.AbstractMap) HashSet(java.util.HashSet)

Example 64 with ClientMessage

use of com.hazelcast.client.impl.protocol.ClientMessage in project hazelcast by hazelcast.

the class AbstractClientCacheProxy method getInternal.

protected Object getInternal(final K key, ExpiryPolicy expiryPolicy, boolean async) {
    final long start = System.nanoTime();
    ensureOpen();
    validateNotNull(key);
    final Data keyData = toData(key);
    Object cached = getCachedValue(keyData, !async);
    if (cached != NOT_CACHED) {
        return asCompletedFutureOrValue(cached, async);
    }
    final long reservationId = tryReserveForUpdate(keyData);
    final Data expiryPolicyData = toData(expiryPolicy);
    ClientMessage request = CacheGetCodec.encodeRequest(nameWithPrefix, keyData, expiryPolicyData);
    ClientInvocationFuture future;
    try {
        final int partitionId = clientContext.getPartitionService().getPartitionId(keyData);
        final HazelcastClientInstanceImpl client = (HazelcastClientInstanceImpl) clientContext.getHazelcastInstance();
        final ClientInvocation clientInvocation = new ClientInvocation(client, request, partitionId);
        future = clientInvocation.invoke();
    } catch (Throwable t) {
        invalidateNearCache(keyData);
        throw rethrow(t);
    }
    SerializationService serializationService = clientContext.getSerializationService();
    ClientDelegatingFuture<V> delegatingFuture = new ClientDelegatingFuture<V>(future, serializationService, cacheGetResponseDecoder);
    if (async) {
        if (nearCache != null) {
            delegatingFuture.andThenInternal(new ExecutionCallback<Data>() {

                public void onResponse(Data valueData) {
                    storeInNearCache(keyData, valueData, null, reservationId, false);
                    if (statisticsEnabled) {
                        handleStatisticsOnGet(start, valueData);
                    }
                }

                public void onFailure(Throwable t) {
                    invalidateNearCache(keyData);
                }
            }, false);
        }
        return delegatingFuture;
    } else {
        try {
            V value = toObject(delegatingFuture.get());
            if (nearCache != null) {
                storeInNearCache(keyData, (Data) delegatingFuture.getResponse(), value, reservationId, false);
            }
            if (statisticsEnabled) {
                handleStatisticsOnGet(start, value);
            }
            return value;
        } catch (Throwable e) {
            invalidateNearCache(keyData);
            throw rethrowAllowedTypeFirst(e, CacheException.class);
        }
    }
}
Also used : ClientDelegatingFuture(com.hazelcast.client.util.ClientDelegatingFuture) CacheException(javax.cache.CacheException) SerializationService(com.hazelcast.spi.serialization.SerializationService) Data(com.hazelcast.nio.serialization.Data) ClientInvocation(com.hazelcast.client.spi.impl.ClientInvocation) ClientMessage(com.hazelcast.client.impl.protocol.ClientMessage) ClientInvocationFuture(com.hazelcast.client.spi.impl.ClientInvocationFuture) HazelcastClientInstanceImpl(com.hazelcast.client.impl.HazelcastClientInstanceImpl)

Example 65 with ClientMessage

use of com.hazelcast.client.impl.protocol.ClientMessage in project hazelcast by hazelcast.

the class ClientCacheHelper method createCacheConfig.

/**
     * Sends the cache configuration to server.
     *
     * @param client             the client instance which will send the operation to server
     * @param configs            {@link ConcurrentMap} based store that holds cache configurations
     * @param cacheName          full cache name with prefixes
     * @param newCacheConfig     the cache configuration to be sent to server
     * @param createAlsoOnOthers flag which represents whether cache config
     *                           will be sent to other nodes by the target node
     * @param syncCreate         flag which represents response will be waited from the server
     * @param <K>                type of the key of the cache
     * @param <V>                type of the value of the cache
     * @return the created cache configuration
     */
static <K, V> CacheConfig<K, V> createCacheConfig(HazelcastClientInstanceImpl client, ConcurrentMap<String, CacheConfig> configs, String cacheName, CacheConfig<K, V> newCacheConfig, boolean createAlsoOnOthers, boolean syncCreate) {
    try {
        CacheConfig<K, V> currentCacheConfig = configs.get(cacheName);
        int partitionId = client.getClientPartitionService().getPartitionId(newCacheConfig.getNameWithPrefix());
        Object resolvedConfig = resolveCacheConfig(client, newCacheConfig, partitionId);
        Data configData = client.getSerializationService().toData(resolvedConfig);
        ClientMessage request = CacheCreateConfigCodec.encodeRequest(configData, createAlsoOnOthers);
        ClientInvocation clientInvocation = new ClientInvocation(client, request, partitionId);
        Future<ClientMessage> future = clientInvocation.invoke();
        if (syncCreate) {
            final ClientMessage response = future.get();
            final Data data = CacheCreateConfigCodec.decodeResponse(response).response;
            return resolveCacheConfig(client, clientInvocation, data);
        } else {
            return currentCacheConfig;
        }
    } catch (Exception e) {
        throw rethrow(e);
    }
}
Also used : Data(com.hazelcast.nio.serialization.Data) ClientInvocation(com.hazelcast.client.spi.impl.ClientInvocation) ClientMessage(com.hazelcast.client.impl.protocol.ClientMessage) IOException(java.io.IOException)

Aggregations

ClientMessage (com.hazelcast.client.impl.protocol.ClientMessage)377 Data (com.hazelcast.nio.serialization.Data)140 ClientInvocation (com.hazelcast.client.spi.impl.ClientInvocation)47 ClientInvocationFuture (com.hazelcast.client.spi.impl.ClientInvocationFuture)37 SafeBuffer (com.hazelcast.client.impl.protocol.util.SafeBuffer)29 Address (com.hazelcast.nio.Address)25 QuickTest (com.hazelcast.test.annotation.QuickTest)24 Test (org.junit.Test)24 ClientDelegatingFuture (com.hazelcast.client.util.ClientDelegatingFuture)21 DataInputStream (java.io.DataInputStream)20 InputStream (java.io.InputStream)20 CacheEventData (com.hazelcast.cache.impl.CacheEventData)19 ParallelTest (com.hazelcast.test.annotation.ParallelTest)19 Member (com.hazelcast.core.Member)18 SerializationService (com.hazelcast.spi.serialization.SerializationService)18 ExecutionException (java.util.concurrent.ExecutionException)18 UnmodifiableLazyList (com.hazelcast.spi.impl.UnmodifiableLazyList)16 ArrayList (java.util.ArrayList)16 QueryCacheEventData (com.hazelcast.map.impl.querycache.event.QueryCacheEventData)13 CacheException (javax.cache.CacheException)13