You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@ignite.apache.org by dm...@apache.org on 2016/05/27 11:30:40 UTC

[01/17] ignite git commit: ignite-3056: Service implementation class is required even if it's not expected to be deployed on current node (fixed)

Repository: ignite
Updated Branches:
  refs/heads/master 57a630e5a -> 271f9eea4


ignite-3056: Service implementation class is required even if it's not expected to be deployed on current node (fixed)


Project: http://git-wip-us.apache.org/repos/asf/ignite/repo
Commit: http://git-wip-us.apache.org/repos/asf/ignite/commit/b5f59412
Tree: http://git-wip-us.apache.org/repos/asf/ignite/tree/b5f59412
Diff: http://git-wip-us.apache.org/repos/asf/ignite/diff/b5f59412

Branch: refs/heads/master
Commit: b5f594124dbdc75525bdd2c92fc49b9e126e60ab
Parents: 2a35fb6
Author: ashutak <as...@gridgain.com>
Authored: Wed May 18 20:47:26 2016 +0300
Committer: ashutak <as...@gridgain.com>
Committed: Wed May 18 20:47:26 2016 +0300

----------------------------------------------------------------------
 .../apache/ignite/IgniteSystemProperties.java   |  14 +
 .../ignite/internal/IgniteNodeAttributes.java   |   3 +
 .../discovery/GridDiscoveryManager.java         |  33 ++-
 .../service/GridServiceAssignments.java         |  10 +-
 .../service/GridServiceProcessor.java           | 215 ++++++++++++++-
 .../service/LazyServiceConfiguration.java       | 129 +++++++++
 .../service/ServiceDescriptorImpl.java          |  17 +-
 .../ignite/services/ServiceConfiguration.java   |  14 +-
 .../ignite/spi/discovery/tcp/ServerImpl.java    |  72 ++++++
 .../GridDiscoveryManagerAttributesSelfTest.java |  63 +++++
 ...yment2ClassLoadersDefaultMarshallerTest.java | 259 +++++++++++++++++++
 ...eployment2ClassLoadersJdkMarshallerTest.java |  31 +++
 ...ent2ClassLoadersOptimizedMarshallerTest.java |  31 +++
 ...oymentClassLoadingDefaultMarshallerTest.java | 212 +++++++++++++++
 ...DeploymentClassLoadingJdkMarshallerTest.java |  31 +++
 ...mentClassLoadingOptimizedMarshallerTest.java |  31 +++
 .../testsuites/IgniteKernalSelfTestSuite.java   |  13 +
 .../apache/ignite/tests/p2p/NoopService.java    |  41 +++
 .../apache/ignite/tests/p2p/NoopService2.java   |  41 +++
 19 files changed, 1229 insertions(+), 31 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/b5f59412/modules/core/src/main/java/org/apache/ignite/IgniteSystemProperties.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/IgniteSystemProperties.java b/modules/core/src/main/java/org/apache/ignite/IgniteSystemProperties.java
index c28181e..5f761a2 100644
--- a/modules/core/src/main/java/org/apache/ignite/IgniteSystemProperties.java
+++ b/modules/core/src/main/java/org/apache/ignite/IgniteSystemProperties.java
@@ -430,6 +430,20 @@ public final class IgniteSystemProperties {
     public static final String IGNITE_H2_INDEXING_CACHE_THREAD_USAGE_TIMEOUT =
         "IGNITE_H2_INDEXING_CACHE_THREAD_USAGE_TIMEOUT";
 
+    /**
+     * Manages backward compatibility of {@link IgniteServices}. All nodes in cluster must have identical value
+     * of this property.
+     * <p>
+     * If property is {@code false} then node is not required to have service implementation class if service is not
+     * deployed on this node.
+     * <p>
+     * If the property is {@code true} then service implementation class is required on node even if service
+     * is not deployed on this node.
+     * <p>
+     * If the property is not set ({@code null}) then Ignite will automatically detect which compatibility mode
+     * should be used.
+     */
+    public static final String IGNITE_SERVICES_COMPATIBILITY_MODE = "IGNITE_SERVICES_COMPATIBILITY_MODE";
 
     /**
      * Enforces singleton.

http://git-wip-us.apache.org/repos/asf/ignite/blob/b5f59412/modules/core/src/main/java/org/apache/ignite/internal/IgniteNodeAttributes.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/IgniteNodeAttributes.java b/modules/core/src/main/java/org/apache/ignite/internal/IgniteNodeAttributes.java
index 0e6a254..e7c984f 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/IgniteNodeAttributes.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/IgniteNodeAttributes.java
@@ -157,6 +157,9 @@ public final class IgniteNodeAttributes {
     /** Late affinity assignment mode. */
     public static final String ATTR_LATE_AFFINITY_ASSIGNMENT = ATTR_PREFIX + ".cache.lateAffinity";
 
+    /** Ignite services compatibility mode (can be {@code null}). */
+    public static final String ATTR_SERVICES_COMPATIBILITY_MODE = ATTR_PREFIX + ".services.compatibility.enabled";
+
     /**
      * Enforces singleton.
      */

http://git-wip-us.apache.org/repos/asf/ignite/blob/b5f59412/modules/core/src/main/java/org/apache/ignite/internal/managers/discovery/GridDiscoveryManager.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/managers/discovery/GridDiscoveryManager.java b/modules/core/src/main/java/org/apache/ignite/internal/managers/discovery/GridDiscoveryManager.java
index 6aa4d54..0d3ff0a 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/managers/discovery/GridDiscoveryManager.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/managers/discovery/GridDiscoveryManager.java
@@ -78,6 +78,7 @@ import org.apache.ignite.internal.processors.cache.CacheAffinitySharedManager;
 import org.apache.ignite.internal.processors.cache.GridCacheAdapter;
 import org.apache.ignite.internal.processors.jobmetrics.GridJobMetrics;
 import org.apache.ignite.internal.processors.security.SecurityContext;
+import org.apache.ignite.internal.processors.service.GridServiceProcessor;
 import org.apache.ignite.internal.processors.timeout.GridTimeoutProcessor;
 import org.apache.ignite.internal.util.F0;
 import org.apache.ignite.internal.util.GridBoundedConcurrentOrderedMap;
@@ -118,6 +119,7 @@ import org.jsr166.ConcurrentHashMap8;
 
 import static java.util.concurrent.TimeUnit.MILLISECONDS;
 import static org.apache.ignite.IgniteSystemProperties.IGNITE_OPTIMIZED_MARSHALLER_USE_DEFAULT_SUID;
+import static org.apache.ignite.IgniteSystemProperties.IGNITE_SERVICES_COMPATIBILITY_MODE;
 import static org.apache.ignite.IgniteSystemProperties.IGNITE_BINARY_MARSHALLER_USE_STRING_SERIALIZATION_VER_2;
 import static org.apache.ignite.events.EventType.EVT_CLIENT_NODE_DISCONNECTED;
 import static org.apache.ignite.events.EventType.EVT_CLIENT_NODE_RECONNECTED;
@@ -126,12 +128,13 @@ import static org.apache.ignite.events.EventType.EVT_NODE_JOINED;
 import static org.apache.ignite.events.EventType.EVT_NODE_LEFT;
 import static org.apache.ignite.events.EventType.EVT_NODE_METRICS_UPDATED;
 import static org.apache.ignite.events.EventType.EVT_NODE_SEGMENTED;
-import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_LATE_AFFINITY_ASSIGNMENT;
 import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_DEPLOYMENT_MODE;
+import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_LATE_AFFINITY_ASSIGNMENT;
 import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_MACS;
 import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_MARSHALLER_USE_BINARY_STRING_SER_VER_2;
 import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_MARSHALLER_USE_DFLT_SUID;
 import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_PEER_CLASSLOADING;
+import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_SERVICES_COMPATIBILITY_MODE;
 import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_USER_NAME;
 import static org.apache.ignite.internal.IgniteVersionUtils.VER;
 import static org.apache.ignite.plugin.segmentation.SegmentationPolicy.NOOP;
@@ -696,6 +699,8 @@ public class GridDiscoveryManager extends GridManagerAdapter<DiscoverySpi> {
 
         checkAttributes(discoCache().remoteNodes());
 
+        ctx.service().initCompatibilityMode(discoCache().remoteNodes());
+
         // Start discovery worker.
         new IgniteThread(discoWrk).start();
 
@@ -1012,6 +1017,8 @@ public class GridDiscoveryManager extends GridManagerAdapter<DiscoverySpi> {
 
         boolean locDelayAssign = locNode.attribute(ATTR_LATE_AFFINITY_ASSIGNMENT);
 
+        Boolean locSrvcCompatibilityEnabled = locNode.attribute(ATTR_SERVICES_COMPATIBILITY_MODE);
+
         for (ClusterNode n : nodes) {
             int rmtJvmMajVer = nodeJavaMajorVersion(n);
 
@@ -1100,6 +1107,30 @@ public class GridDiscoveryManager extends GridManagerAdapter<DiscoverySpi> {
                     ", rmtLateAssign=" + rmtLateAssign +
                     ", rmtAddrs=" + U.addressesAsString(n) + ']');
             }
+
+            if (n.version().compareToIgnoreTimestamp(GridServiceProcessor.LAZY_SERVICES_CFG_SINCE) >= 0) {
+                Boolean rmtSrvcCompatibilityEnabled = n.attribute(ATTR_SERVICES_COMPATIBILITY_MODE);
+
+                if (!F.eq(locSrvcCompatibilityEnabled, rmtSrvcCompatibilityEnabled)) {
+                    throw new IgniteCheckedException("Local node's " + IGNITE_SERVICES_COMPATIBILITY_MODE +
+                        " property value differs from remote node's value " +
+                        "(to make sure all nodes in topology have identical IgniteServices compatibility mode enabled, " +
+                        "configure system property explicitly) " +
+                        "[locSrvcCompatibilityEnabled=" + locSrvcCompatibilityEnabled +
+                        ", rmtSrvcCompatibilityEnabled=" + rmtSrvcCompatibilityEnabled +
+                        ", locNodeAddrs=" + U.addressesAsString(locNode) +
+                        ", rmtNodeAddrs=" + U.addressesAsString(n) +
+                        ", locNodeId=" + locNode.id() + ", rmtNodeId=" + n.id() + ']');
+                }
+            }
+            else if (Boolean.FALSE.equals(locSrvcCompatibilityEnabled)) {
+                throw new IgniteCheckedException("Remote node doesn't support lazy services configuration and " +
+                    "local node cannot join node because local node's "
+                    + IGNITE_SERVICES_COMPATIBILITY_MODE + " property value explicitly set to 'false'" +
+                    "[locNodeAddrs=" + U.addressesAsString(locNode) +
+                    ", rmtNodeAddrs=" + U.addressesAsString(n) +
+                    ", locNodeId=" + locNode.id() + ", rmtNodeId=" + n.id() + ']');
+            }
         }
 
         if (log.isDebugEnabled())

http://git-wip-us.apache.org/repos/asf/ignite/blob/b5f59412/modules/core/src/main/java/org/apache/ignite/internal/processors/service/GridServiceAssignments.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/service/GridServiceAssignments.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/service/GridServiceAssignments.java
index c629a48..66b2816 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/service/GridServiceAssignments.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/service/GridServiceAssignments.java
@@ -26,7 +26,6 @@ import org.apache.ignite.internal.processors.cache.GridCacheInternal;
 import org.apache.ignite.internal.util.tostring.GridToStringInclude;
 import org.apache.ignite.internal.util.typedef.internal.S;
 import org.apache.ignite.lang.IgnitePredicate;
-import org.apache.ignite.services.Service;
 import org.apache.ignite.services.ServiceConfiguration;
 
 /**
@@ -75,13 +74,6 @@ public class GridServiceAssignments implements Serializable, GridCacheInternal {
     }
 
     /**
-     * @return Service.
-     */
-    public Service service() {
-        return cfg.getService();
-    }
-
-    /**
      * @return Topology version.
      */
     public long topologyVersion() {
@@ -134,4 +126,4 @@ public class GridServiceAssignments implements Serializable, GridCacheInternal {
     @Override public String toString() {
         return S.toString(GridServiceAssignments.class, this);
     }
-}
\ No newline at end of file
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/b5f59412/modules/core/src/main/java/org/apache/ignite/internal/processors/service/GridServiceProcessor.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/service/GridServiceProcessor.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/service/GridServiceProcessor.java
index 06cbe79..132dac4 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/service/GridServiceProcessor.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/service/GridServiceProcessor.java
@@ -32,6 +32,7 @@ import java.util.concurrent.ExecutorService;
 import java.util.concurrent.Executors;
 import java.util.concurrent.ThreadFactory;
 import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
 import javax.cache.Cache;
 import javax.cache.event.CacheEntryEvent;
 import javax.cache.event.CacheEntryListenerException;
@@ -89,12 +90,16 @@ import org.apache.ignite.resources.IgniteInstanceResource;
 import org.apache.ignite.services.Service;
 import org.apache.ignite.services.ServiceConfiguration;
 import org.apache.ignite.services.ServiceDescriptor;
+import org.apache.ignite.spi.IgniteNodeValidationResult;
 import org.apache.ignite.thread.IgniteThreadFactory;
 import org.jetbrains.annotations.Nullable;
 import org.jsr166.ConcurrentHashMap8;
 
+import static org.apache.ignite.IgniteSystemProperties.IGNITE_SERVICES_COMPATIBILITY_MODE;
+import static org.apache.ignite.IgniteSystemProperties.getString;
 import static org.apache.ignite.configuration.DeploymentMode.ISOLATED;
 import static org.apache.ignite.configuration.DeploymentMode.PRIVATE;
+import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_SERVICES_COMPATIBILITY_MODE;
 import static org.apache.ignite.internal.processors.cache.GridCacheUtils.UTILITY_CACHE_NAME;
 import static org.apache.ignite.transactions.TransactionConcurrency.PESSIMISTIC;
 import static org.apache.ignite.transactions.TransactionIsolation.REPEATABLE_READ;
@@ -104,6 +109,12 @@ import static org.apache.ignite.transactions.TransactionIsolation.REPEATABLE_REA
  */
 @SuppressWarnings({"SynchronizationOnLocalVariableOrMethodParameter", "ConstantConditions"})
 public class GridServiceProcessor extends GridProcessorAdapter {
+    /** */
+    public static final IgniteProductVersion LAZY_SERVICES_CFG_SINCE = IgniteProductVersion.fromString("1.5.22");
+
+    /** */
+    private final Boolean srvcCompatibilitySysProp;
+
     /** Time to wait before reassignment retries. */
     private static final long RETRY_TIMEOUT = 1000;
 
@@ -115,6 +126,9 @@ public class GridServiceProcessor extends GridProcessorAdapter {
         DiscoveryCustomEvent.EVT_DISCOVERY_CUSTOM_EVT
     };
 
+    /** */
+    private final AtomicReference<ServicesCompatibilityState> compatibilityState;
+
     /** Local service instances. */
     private final Map<String, Collection<ServiceContextImpl>> locSvcs = new HashMap<>();
 
@@ -155,10 +169,19 @@ public class GridServiceProcessor extends GridProcessorAdapter {
         super(ctx);
 
         depExe = Executors.newSingleThreadExecutor(new IgniteThreadFactory(ctx.gridName(), "srvc-deploy"));
+
+        String servicesCompatibilityMode = getString(IGNITE_SERVICES_COMPATIBILITY_MODE);
+
+        srvcCompatibilitySysProp = servicesCompatibilityMode == null ? null : Boolean.valueOf(servicesCompatibilityMode);
+
+        compatibilityState = new AtomicReference<>(
+            new ServicesCompatibilityState(srvcCompatibilitySysProp != null ? srvcCompatibilitySysProp : false, false));
     }
 
     /** {@inheritDoc} */
     @Override public void start() throws IgniteCheckedException {
+        ctx.addNodeAttribute(ATTR_SERVICES_COMPATIBILITY_MODE, srvcCompatibilitySysProp);
+
         if (ctx.isDaemon())
             return;
 
@@ -402,8 +425,30 @@ public class GridServiceProcessor extends GridProcessorAdapter {
     public IgniteInternalFuture<?> deploy(ServiceConfiguration cfg) {
         A.notNull(cfg, "cfg");
 
+        ServicesCompatibilityState state = markCompatibilityStateAsUsed();
+
         validate(cfg);
 
+        if (!state.srvcCompatibility) {
+            Marshaller marsh = ctx.config().getMarshaller();
+
+            LazyServiceConfiguration cfg0;
+
+            try {
+                byte[] srvcBytes = marsh.marshal(cfg.getService());
+
+                cfg0 = new LazyServiceConfiguration(cfg, srvcBytes);
+            }
+            catch (IgniteCheckedException e) {
+                U.error(log, "Failed to marshal service with configured marshaller [srvc=" + cfg.getService()
+                    + ", marsh=" + marsh + "]", e);
+
+                return new GridFinishedFuture<>(e);
+            }
+
+            cfg = cfg0;
+        }
+
         GridServiceDeploymentFuture fut = new GridServiceDeploymentFuture(cfg);
 
         GridServiceDeploymentFuture old = depFuts.putIfAbsent(cfg.getName(), fut);
@@ -499,6 +544,23 @@ public class GridServiceProcessor extends GridProcessorAdapter {
     }
 
     /**
+     * @return Compatibility state.
+     */
+    private ServicesCompatibilityState markCompatibilityStateAsUsed() {
+        while (true) {
+            ServicesCompatibilityState state = compatibilityState.get();
+
+            if (state.used)
+                return state;
+
+            ServicesCompatibilityState newState = new ServicesCompatibilityState(state.srvcCompatibility, true);
+
+            if (compatibilityState.compareAndSet(state, newState))
+                return newState;
+        }
+    }
+
+    /**
      * @param name Service name.
      * @return Future.
      */
@@ -971,16 +1033,18 @@ public class GridServiceProcessor extends GridProcessorAdapter {
         }
 
         for (final ServiceContextImpl svcCtx : toInit) {
-            final Service svc = copyAndInject(assigns.service());
+            final Service svc;
 
             try {
+                svc = copyAndInject(assigns.configuration());
+
                 // Initialize service.
                 svc.init(svcCtx);
 
                 svcCtx.service(svc);
             }
             catch (Throwable e) {
-                log.error("Failed to initialize service (service will not be deployed): " + assigns.name(), e);
+                U.error(log, "Failed to initialize service (service will not be deployed): " + assigns.name(), e);
 
                 synchronized (ctxs) {
                     ctxs.removeAll(toInit);
@@ -1041,26 +1105,40 @@ public class GridServiceProcessor extends GridProcessorAdapter {
     }
 
     /**
-     * @param svc Service.
+     * @param cfg Service configuration.
      * @return Copy of service.
+     * @throws IgniteCheckedException If failed.
      */
-    private Service copyAndInject(Service svc) {
+    private Service copyAndInject(ServiceConfiguration cfg) throws IgniteCheckedException {
         Marshaller m = ctx.config().getMarshaller();
 
-        try {
-            byte[] bytes = m.marshal(svc);
+        if (cfg instanceof LazyServiceConfiguration) {
+            byte[] bytes = ((LazyServiceConfiguration)cfg).serviceBytes();
 
-            Service cp = m.unmarshal(bytes,
-                U.resolveClassLoader(svc.getClass().getClassLoader(), ctx.config()));
+            Service srvc = m.unmarshal(bytes, U.resolveClassLoader(null, ctx.config()));
 
-            ctx.resource().inject(cp);
+            ctx.resource().inject(srvc);
 
-            return cp;
+            return srvc;
         }
-        catch (IgniteCheckedException e) {
-            log.error("Failed to copy service (will reuse same instance): " + svc.getClass(), e);
+        else {
+            Service svc = cfg.getService();
+
+            try {
+                byte[] bytes = m.marshal(svc);
+
+                Service cp = m.unmarshal(bytes,
+                    U.resolveClassLoader(svc.getClass().getClassLoader(), ctx.config()));
 
-            return svc;
+                ctx.resource().inject(cp);
+
+                return cp;
+            }
+            catch (IgniteCheckedException e) {
+                U.error(log, "Failed to copy service (will reuse same instance): " + svc.getClass(), e);
+
+                return svc;
+            }
         }
     }
 
@@ -1157,6 +1235,73 @@ public class GridServiceProcessor extends GridProcessorAdapter {
         }
     }
 
+    /** {@inheritDoc} */
+    @Nullable @Override public IgniteNodeValidationResult validateNode(ClusterNode node) {
+        IgniteNodeValidationResult res = super.validateNode(node);
+
+        if (res != null)
+            return res;
+
+        boolean rmtNodeIsOld = node.version().compareToIgnoreTimestamp(LAZY_SERVICES_CFG_SINCE) < 0;
+
+        if (!rmtNodeIsOld)
+            return null;
+
+        while (true) {
+            ServicesCompatibilityState state = compatibilityState.get();
+
+            if (state.srvcCompatibility)
+                return null;
+
+            // Remote node is old and services are in not compatible mode.
+            if (!state.used) {
+                if (!compatibilityState.compareAndSet(state, new ServicesCompatibilityState(true, false)))
+                    continue;
+
+                return null;
+            }
+
+            ClusterNode locNode = ctx.discovery().localNode();
+
+            return new IgniteNodeValidationResult(node.id(), "Local node uses IgniteServices and works in not " +
+                "compatible mode with old nodes (" + IGNITE_SERVICES_COMPATIBILITY_MODE + " system property can be " +
+                "set explicitly) [locNodeId=" + locNode.id() + ", rmtNodeId=" + node.id() + "]",
+                "Remote node uses IgniteServices and works in not compatible mode with old nodes " +
+                    IGNITE_SERVICES_COMPATIBILITY_MODE + " system property can be set explicitly" +
+                    "[locNodeId=" + node.id() + ", rmtNodeId=" + locNode.id() + "]");
+        }
+    }
+
+    /**
+     * @param nodes Remote nodes.
+     */
+    public void initCompatibilityMode(Collection<ClusterNode> nodes) {
+        boolean mode;
+
+        if (srvcCompatibilitySysProp == null) {
+            boolean clusterHasOldNode = false;
+
+            for (ClusterNode n : nodes) {
+                if (n.version().compareToIgnoreTimestamp(LAZY_SERVICES_CFG_SINCE) < 0) {
+                    clusterHasOldNode = true;
+
+                    break;
+                }
+            }
+
+            mode = clusterHasOldNode;
+        }
+        else
+            mode = srvcCompatibilitySysProp;
+
+        while (true) {
+            ServicesCompatibilityState state = compatibilityState.get();
+
+            if (compatibilityState.compareAndSet(state, new ServicesCompatibilityState(mode, state.used)))
+                return;
+        }
+    }
+
     /**
      * Service deployment listener.
      */
@@ -1165,10 +1310,18 @@ public class GridServiceProcessor extends GridProcessorAdapter {
         @Override public void onUpdated(final Iterable<CacheEntryEvent<?, ?>> deps) {
             depExe.submit(new BusyRunnable() {
                 @Override public void run0() {
+                    boolean firstTime = true;
+
                     for (CacheEntryEvent<?, ?> e : deps) {
                         if (!(e.getKey() instanceof GridServiceDeploymentKey))
                             continue;
 
+                        if (firstTime) {
+                            markCompatibilityStateAsUsed();
+
+                            firstTime = false;
+                        }
+
                         GridServiceDeployment dep;
 
                         try {
@@ -1336,12 +1489,20 @@ public class GridServiceProcessor extends GridProcessorAdapter {
                                 Iterator<Cache.Entry<Object, Object>> it = serviceEntries(
                                     ServiceDeploymentPredicate.INSTANCE);
 
+                                boolean firstTime = true;
+
                                 while (it.hasNext()) {
                                     Cache.Entry<Object, Object> e = it.next();
 
                                     if (!(e.getKey() instanceof GridServiceDeploymentKey))
                                         continue;
 
+                                    if (firstTime) {
+                                        markCompatibilityStateAsUsed();
+
+                                        firstTime = false;
+                                    }
+
                                     GridServiceDeployment dep = (GridServiceDeployment)e.getValue();
 
                                     try {
@@ -1465,10 +1626,18 @@ public class GridServiceProcessor extends GridProcessorAdapter {
         @Override public void onUpdated(final Iterable<CacheEntryEvent<?, ?>> assignCol) throws CacheEntryListenerException {
             depExe.submit(new BusyRunnable() {
                 @Override public void run0() {
+                    boolean firstTime = true;
+
                     for (CacheEntryEvent<?, ?> e : assignCol) {
                         if (!(e.getKey() instanceof GridServiceAssignmentsKey))
                             continue;
 
+                        if (firstTime) {
+                            markCompatibilityStateAsUsed();
+
+                            firstTime = false;
+                        }
+
                         GridServiceAssignments assigns;
 
                         try {
@@ -1630,4 +1799,24 @@ public class GridServiceProcessor extends GridProcessorAdapter {
             return serviceTopology(ignite.context().cache().utilityCache(), svcName);
         }
     }
+
+    /**
+     *
+     */
+    private static class ServicesCompatibilityState {
+        /** */
+        private final boolean srvcCompatibility;
+
+        /** */
+        private final boolean used;
+
+        /**
+         * @param srvcCompatibility Services compatibility mode ({@code true} if compatible with old nodes).
+         * @param used Services has been used.
+         */
+        ServicesCompatibilityState(boolean srvcCompatibility, boolean used) {
+            this.srvcCompatibility = srvcCompatibility;
+            this.used = used;
+        }
+    }
 }

http://git-wip-us.apache.org/repos/asf/ignite/blob/b5f59412/modules/core/src/main/java/org/apache/ignite/internal/processors/service/LazyServiceConfiguration.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/service/LazyServiceConfiguration.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/service/LazyServiceConfiguration.java
new file mode 100644
index 0000000..e0add26
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/service/LazyServiceConfiguration.java
@@ -0,0 +1,129 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ignite.internal.processors.service;
+
+import org.apache.ignite.internal.util.tostring.GridToStringExclude;
+import org.apache.ignite.internal.util.typedef.F;
+import org.apache.ignite.internal.util.typedef.internal.S;
+import org.apache.ignite.services.Service;
+import org.apache.ignite.services.ServiceConfiguration;
+
+/**
+ * Lazy service configuration.
+ */
+public class LazyServiceConfiguration extends ServiceConfiguration {
+    /** */
+    private static final long serialVersionUID = 0L;
+
+    /** Service instance. */
+    @GridToStringExclude
+    private transient Service srvc;
+
+    /** */
+    private String srvcClsName;
+
+    /** */
+    private byte[] srvcBytes;
+
+    /**
+     * Default constructor.
+     */
+    public LazyServiceConfiguration() {
+        // No-op.
+    }
+
+    /**
+     * @param cfg Configuration.
+     * @param srvcBytes Marshaller service.
+     */
+    public LazyServiceConfiguration(ServiceConfiguration cfg, byte[] srvcBytes) {
+        assert cfg.getService() != null : cfg;
+        assert srvcBytes != null;
+
+        name = cfg.getName();
+        totalCnt = cfg.getTotalCount();
+        maxPerNodeCnt = cfg.getMaxPerNodeCount();
+        cacheName = cfg.getCacheName();
+        affKey = cfg.getAffinityKey();
+        nodeFilter = cfg.getNodeFilter();
+        this.srvcBytes = srvcBytes;
+        srvc = cfg.getService();
+        srvcClsName = srvc.getClass().getName();
+    }
+
+    /**
+     * @return Service bytes.
+     */
+    public byte[] serviceBytes() {
+        return srvcBytes;
+    }
+
+    /**
+     * @return Service class name.
+     */
+    public String serviceClassName() {
+        return srvcClsName;
+    }
+
+    /** {@inheritDoc} */
+    @Override public Service getService() {
+        assert srvc != null : this;
+
+        return srvc;
+    }
+
+    /** {@inheritDoc} */
+    @SuppressWarnings("RedundantIfStatement")
+    @Override public boolean equalsIgnoreNodeFilter(Object o) {
+        if (this == o)
+            return true;
+
+        if (o == null || getClass() != o.getClass())
+            return false;
+
+        LazyServiceConfiguration that = (LazyServiceConfiguration)o;
+
+        if (maxPerNodeCnt != that.getMaxPerNodeCount())
+            return false;
+
+        if (totalCnt != that.getTotalCount())
+            return false;
+
+        if (affKey != null ? !affKey.equals(that.getAffinityKey()) : that.getAffinityKey() != null)
+            return false;
+
+        if (cacheName != null ? !cacheName.equals(that.getCacheName()) : that.getCacheName() != null)
+            return false;
+
+        if (name != null ? !name.equals(that.getName()) : that.getName() != null)
+            return false;
+
+        if (!F.eq(srvcClsName, that.srvcClsName))
+            return false;
+
+        return true;
+    }
+
+    /** {@inheritDoc} */
+    @Override public String toString() {
+        String svcCls = srvc == null ? "" : srvc.getClass().getSimpleName();
+        String nodeFilterCls = nodeFilter == null ? "" : nodeFilter.getClass().getSimpleName();
+
+        return S.toString(LazyServiceConfiguration.class, this, "svcCls", svcCls, "nodeFilterCls", nodeFilterCls);
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/b5f59412/modules/core/src/main/java/org/apache/ignite/internal/processors/service/ServiceDescriptorImpl.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/service/ServiceDescriptorImpl.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/service/ServiceDescriptorImpl.java
index 7671a2e..9ec3eb0 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/service/ServiceDescriptorImpl.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/service/ServiceDescriptorImpl.java
@@ -19,9 +19,11 @@ package org.apache.ignite.internal.processors.service;
 
 import java.util.Map;
 import java.util.UUID;
+import org.apache.ignite.IgniteException;
 import org.apache.ignite.internal.util.tostring.GridToStringInclude;
 import org.apache.ignite.internal.util.typedef.internal.S;
 import org.apache.ignite.services.Service;
+import org.apache.ignite.services.ServiceConfiguration;
 import org.apache.ignite.services.ServiceDescriptor;
 import org.jetbrains.annotations.Nullable;
 
@@ -54,7 +56,20 @@ public class ServiceDescriptorImpl implements ServiceDescriptor {
 
     /** {@inheritDoc} */
     @Override public Class<? extends Service> serviceClass() {
-        return dep.configuration().getService().getClass();
+        ServiceConfiguration cfg = dep.configuration();
+
+        if (cfg instanceof LazyServiceConfiguration) {
+            String clsName = ((LazyServiceConfiguration)cfg).serviceClassName();
+
+            try {
+                return (Class<? extends Service>)Class.forName(clsName);
+            }
+            catch (ClassNotFoundException e) {
+                throw new IgniteException("Failed to find service class: " + clsName, e);
+            }
+        }
+        else
+            return dep.configuration().getService().getClass();
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/b5f59412/modules/core/src/main/java/org/apache/ignite/services/ServiceConfiguration.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/services/ServiceConfiguration.java b/modules/core/src/main/java/org/apache/ignite/services/ServiceConfiguration.java
index 126ad47..6698dd4 100644
--- a/modules/core/src/main/java/org/apache/ignite/services/ServiceConfiguration.java
+++ b/modules/core/src/main/java/org/apache/ignite/services/ServiceConfiguration.java
@@ -55,27 +55,27 @@ public class ServiceConfiguration implements Serializable {
     private static final long serialVersionUID = 0L;
 
     /** Service name. */
-    private String name;
+    protected String name;
 
     /** Service instance. */
     @GridToStringExclude
     private Service svc;
 
     /** Total count. */
-    private int totalCnt;
+    protected int totalCnt;
 
     /** Max per-node count. */
-    private int maxPerNodeCnt;
+    protected int maxPerNodeCnt;
 
     /** Cache name. */
-    private String cacheName;
+    protected String cacheName;
 
     /** Affinity key. */
-    private Object affKey;
+    protected Object affKey;
 
     /** Node filter. */
     @GridToStringExclude
-    private IgnitePredicate<ClusterNode> nodeFilter;
+    protected IgnitePredicate<ClusterNode> nodeFilter;
 
     /**
      * Gets service name.
@@ -301,4 +301,4 @@ public class ServiceConfiguration implements Serializable {
 
         return S.toString(ServiceConfiguration.class, this, "svcCls", svcCls, "nodeFilterCls", nodeFilterCls);
     }
-}
\ No newline at end of file
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/b5f59412/modules/core/src/main/java/org/apache/ignite/spi/discovery/tcp/ServerImpl.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/spi/discovery/tcp/ServerImpl.java b/modules/core/src/main/java/org/apache/ignite/spi/discovery/tcp/ServerImpl.java
index a4c7276..a9a86bc 100644
--- a/modules/core/src/main/java/org/apache/ignite/spi/discovery/tcp/ServerImpl.java
+++ b/modules/core/src/main/java/org/apache/ignite/spi/discovery/tcp/ServerImpl.java
@@ -72,6 +72,7 @@ import org.apache.ignite.internal.IgnitionEx;
 import org.apache.ignite.internal.events.DiscoveryCustomEvent;
 import org.apache.ignite.internal.processors.cache.CacheAffinitySharedManager;
 import org.apache.ignite.internal.processors.security.SecurityContext;
+import org.apache.ignite.internal.processors.service.GridServiceProcessor;
 import org.apache.ignite.internal.util.GridBoundedLinkedHashSet;
 import org.apache.ignite.internal.util.GridConcurrentHashSet;
 import org.apache.ignite.internal.util.IgniteUtils;
@@ -133,6 +134,7 @@ import org.jsr166.ConcurrentHashMap8;
 
 import static org.apache.ignite.IgniteSystemProperties.IGNITE_DISCOVERY_HISTORY_SIZE;
 import static org.apache.ignite.IgniteSystemProperties.IGNITE_OPTIMIZED_MARSHALLER_USE_DEFAULT_SUID;
+import static org.apache.ignite.IgniteSystemProperties.IGNITE_SERVICES_COMPATIBILITY_MODE;
 import static org.apache.ignite.IgniteSystemProperties.IGNITE_BINARY_MARSHALLER_USE_STRING_SERIALIZATION_VER_2;
 import static org.apache.ignite.IgniteSystemProperties.getInteger;
 import static org.apache.ignite.events.EventType.EVT_NODE_FAILED;
@@ -145,6 +147,7 @@ import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_MARSHALLER;
 import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_MARSHALLER_COMPACT_FOOTER;
 import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_MARSHALLER_USE_BINARY_STRING_SER_VER_2;
 import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_MARSHALLER_USE_DFLT_SUID;
+import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_SERVICES_COMPATIBILITY_MODE;
 import static org.apache.ignite.spi.IgnitePortProtocol.TCP;
 import static org.apache.ignite.spi.discovery.tcp.internal.TcpDiscoverySpiState.AUTH_FAILED;
 import static org.apache.ignite.spi.discovery.tcp.internal.TcpDiscoverySpiState.CHECK_FAILED;
@@ -3413,6 +3416,75 @@ class ServerImpl extends TcpDiscoveryImpl {
                     return;
                 }
 
+                final Boolean locSrvcCompatibilityEnabled = locNode.attribute(ATTR_SERVICES_COMPATIBILITY_MODE);
+
+                if (node.version().compareToIgnoreTimestamp(GridServiceProcessor.LAZY_SERVICES_CFG_SINCE) >= 0) {
+                    final Boolean rmtSrvcCompatibilityEnabled = node.attribute(ATTR_SERVICES_COMPATIBILITY_MODE);
+
+                    if (!F.eq(locSrvcCompatibilityEnabled, rmtSrvcCompatibilityEnabled)) {
+                        utilityPool.submit(
+                            new Runnable() {
+                                @Override public void run() {
+                                    String errMsg = "Local node's " + IGNITE_SERVICES_COMPATIBILITY_MODE +
+                                        " property value differs from remote node's value " +
+                                        "(to make sure all nodes in topology have identical IgniteServices compatibility mode, " +
+                                        "configure system property explicitly) " +
+                                        "[locSrvcCompatibilityEnabled=" + locSrvcCompatibilityEnabled +
+                                        ", rmtSrvcCompatibilityEnabled=" + rmtSrvcCompatibilityEnabled +
+                                        ", locNodeAddrs=" + U.addressesAsString(locNode) +
+                                        ", rmtNodeAddrs=" + U.addressesAsString(node) +
+                                        ", locNodeId=" + locNode.id() + ", rmtNodeId=" + msg.creatorNodeId() + ']';
+
+                                    String sndMsg = "Local node's " + IGNITE_SERVICES_COMPATIBILITY_MODE +
+                                        " property value differs from remote node's value " +
+                                        "(to make sure all nodes in topology have identical IgniteServices compatibility mode, " +
+                                        "configure system property explicitly) " +
+                                        "[locSrvcCompatibilityEnabled=" + rmtSrvcCompatibilityEnabled +
+                                        ", rmtSrvcCompatibilityEnabled=" + locSrvcCompatibilityEnabled +
+                                        ", locNodeAddrs=" + U.addressesAsString(node) + ", locPort=" + node.discoveryPort() +
+                                        ", rmtNodeAddr=" + U.addressesAsString(locNode) + ", locNodeId=" + node.id() +
+                                        ", rmtNodeId=" + locNode.id() + ']';
+
+                                    nodeCheckError(
+                                        node,
+                                        errMsg,
+                                        sndMsg);
+                                }
+                            });
+
+                        // Ignore join request.
+                        return;
+                    }
+                }
+                else if (Boolean.FALSE.equals(locSrvcCompatibilityEnabled)) {
+                    utilityPool.submit(
+                        new Runnable() {
+                            @Override public void run() {
+                                String errMsg = "Remote node doesn't support lazy services configuration and " +
+                                    "cannot be joined to local node because local node's "
+                                    + IGNITE_SERVICES_COMPATIBILITY_MODE + " property value explicitly set to 'false'" +
+                                    "[locNodeAddrs=" + U.addressesAsString(locNode) +
+                                    ", rmtNodeAddrs=" + U.addressesAsString(node) +
+                                    ", locNodeId=" + locNode.id() + ", rmtNodeId=" + node.id() + ']';
+
+                                String sndMsg = "Local node doesn't support lazy services configuration and " +
+                                    "cannot be joined to local node because remote node's "
+                                    + IGNITE_SERVICES_COMPATIBILITY_MODE + " property value explicitly set to 'false'" +
+                                    "[locNodeAddrs=" + U.addressesAsString(node) +
+                                    ", rmtNodeAddrs=" + U.addressesAsString(locNode) +
+                                    ", locNodeId=" + node.id() + ", rmtNodeId=" + locNode.id() + ']';
+
+                                nodeCheckError(
+                                    node,
+                                    errMsg,
+                                    sndMsg);
+                            }
+                        });
+
+                    // Ignore join request.
+                    return;
+                }
+
                 // Handle join.
                 node.internalOrder(ring.nextNodeOrder());
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/b5f59412/modules/core/src/test/java/org/apache/ignite/internal/managers/discovery/GridDiscoveryManagerAttributesSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/managers/discovery/GridDiscoveryManagerAttributesSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/managers/discovery/GridDiscoveryManagerAttributesSelfTest.java
index 28380df..ba8fa5b 100644
--- a/modules/core/src/test/java/org/apache/ignite/internal/managers/discovery/GridDiscoveryManagerAttributesSelfTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/internal/managers/discovery/GridDiscoveryManagerAttributesSelfTest.java
@@ -29,6 +29,7 @@ import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder;
 import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
 
 import static org.apache.ignite.IgniteSystemProperties.IGNITE_OPTIMIZED_MARSHALLER_USE_DEFAULT_SUID;
+import static org.apache.ignite.IgniteSystemProperties.IGNITE_SERVICES_COMPATIBILITY_MODE;
 import static org.apache.ignite.IgniteSystemProperties.IGNITE_BINARY_MARSHALLER_USE_STRING_SERIALIZATION_VER_2;
 import static org.apache.ignite.configuration.DeploymentMode.CONTINUOUS;
 import static org.apache.ignite.configuration.DeploymentMode.SHARED;
@@ -227,6 +228,68 @@ public abstract class GridDiscoveryManagerAttributesSelfTest extends GridCommonA
     /**
      * @throws Exception If failed.
      */
+    public void testServiceCompatibilityEnabled() throws Exception {
+        String backup = System.getProperty(IGNITE_SERVICES_COMPATIBILITY_MODE);
+
+        try {
+            doTestServiceCompatibilityEnabled(true, null, true);
+            doTestServiceCompatibilityEnabled(false, null, true);
+            doTestServiceCompatibilityEnabled(null, false, true);
+            doTestServiceCompatibilityEnabled(true, false, true);
+            doTestServiceCompatibilityEnabled(null, true, true);
+            doTestServiceCompatibilityEnabled(false, true, true);
+
+            doTestServiceCompatibilityEnabled(true, true, false);
+            doTestServiceCompatibilityEnabled(false, false, false);
+            doTestServiceCompatibilityEnabled(null, null, false);
+        }
+        finally {
+            if (backup != null)
+                System.setProperty(IGNITE_SERVICES_COMPATIBILITY_MODE, backup);
+            else
+                System.clearProperty(IGNITE_SERVICES_COMPATIBILITY_MODE);
+        }
+    }
+
+    /**
+     * @param first Service compatibility enabled flag for first node.
+     * @param second Service compatibility enabled flag for second node.
+     * @param fail Fail flag.
+     * @throws Exception If failed.
+     */
+    private void doTestServiceCompatibilityEnabled(Object first, Object second, boolean fail) throws Exception {
+        try {
+            if (first != null)
+                System.setProperty(IGNITE_SERVICES_COMPATIBILITY_MODE, String.valueOf(first));
+            else
+                System.clearProperty(IGNITE_SERVICES_COMPATIBILITY_MODE);
+
+            startGrid(0);
+
+            if (second != null)
+                System.setProperty(IGNITE_SERVICES_COMPATIBILITY_MODE, String.valueOf(second));
+            else
+                System.clearProperty(IGNITE_SERVICES_COMPATIBILITY_MODE);
+
+            try {
+                startGrid(1);
+
+                if (fail)
+                    fail("Node must not join");
+            }
+            catch (Exception e) {
+                if (!fail)
+                    fail("Node must join: " + e.getMessage());
+            }
+        }
+        finally {
+            stopAllGrids();
+        }
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
     public void testDifferentDeploymentModes() throws Exception {
         startGrid(0);
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/b5f59412/modules/core/src/test/java/org/apache/ignite/internal/processors/service/IgniteServiceDeployment2ClassLoadersDefaultMarshallerTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/service/IgniteServiceDeployment2ClassLoadersDefaultMarshallerTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/service/IgniteServiceDeployment2ClassLoadersDefaultMarshallerTest.java
new file mode 100644
index 0000000..e77ded7
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/service/IgniteServiceDeployment2ClassLoadersDefaultMarshallerTest.java
@@ -0,0 +1,259 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.ignite.internal.processors.service;
+
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Set;
+import org.apache.ignite.cluster.ClusterNode;
+import org.apache.ignite.configuration.IgniteConfiguration;
+import org.apache.ignite.lang.IgnitePredicate;
+import org.apache.ignite.marshaller.Marshaller;
+import org.apache.ignite.services.Service;
+import org.apache.ignite.services.ServiceConfiguration;
+import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi;
+import org.apache.ignite.spi.discovery.tcp.ipfinder.TcpDiscoveryIpFinder;
+import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder;
+import org.apache.ignite.testframework.GridTestExternalClassLoader;
+import org.apache.ignite.testframework.config.GridTestProperties;
+import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
+
+/**
+ * Tests that not all nodes in cluster need user's service definition (only nodes according to filter).
+ */
+public class IgniteServiceDeployment2ClassLoadersDefaultMarshallerTest extends GridCommonAbstractTest {
+    /** */
+    private static final String NOOP_SERVICE_CLS_NAME = "org.apache.ignite.tests.p2p.NoopService";
+
+    /** */
+    private static final String NOOP_SERVICE_2_CLS_NAME = "org.apache.ignite.tests.p2p.NoopService2";
+
+    /** IP finder. */
+    private static final TcpDiscoveryIpFinder IP_FINDER = new TcpDiscoveryVmIpFinder(true);
+
+    /** */
+    private static final int GRID_CNT = 6;
+
+    /** */
+    private static final String NODE_NAME_ATTR = "NODE_NAME";
+
+    /** */
+    private static final URL[] URLS;
+
+    /** */
+    private static ClassLoader extClsLdr1;
+
+    /** */
+    private static ClassLoader extClsLdr2;
+
+    /** */
+    private Set<String> grp1 = new HashSet<>();
+
+    /** */
+    private Set<String> grp2 = new HashSet<>();
+
+    /** */
+    private boolean client;
+
+    /**
+     * Initialize URLs.
+     */
+    static {
+        try {
+            URLS = new URL[] {new URL(GridTestProperties.getProperty("p2p.uri.cls"))};
+        }
+        catch (MalformedURLException e) {
+            throw new RuntimeException("Define property p2p.uri.cls", e);
+        }
+    }
+
+
+    /** {@inheritDoc} */
+    @Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception {
+        IgniteConfiguration cfg = super.getConfiguration(gridName);
+
+        cfg.setPeerClassLoadingEnabled(false);
+
+        TcpDiscoverySpi discoSpi = new TcpDiscoverySpi();
+
+        discoSpi.setIpFinder(IP_FINDER);
+
+        cfg.setDiscoverySpi(discoSpi);
+
+        cfg.setMarshaller(marshaller());
+
+        cfg.setUserAttributes(Collections.singletonMap(NODE_NAME_ATTR, gridName));
+
+        if (grp1.contains(gridName))
+            cfg.setClassLoader(extClsLdr1);
+
+        if (grp2.contains(gridName))
+            cfg.setClassLoader(extClsLdr2);
+
+        cfg.setClientMode(client);
+
+        return cfg;
+    }
+
+    /**
+     * @return Marshaller.
+     */
+    protected Marshaller marshaller() {
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void beforeTest() throws Exception {
+        super.beforeTest();
+
+        for (int i = 0; i < GRID_CNT; i += 2)
+            grp1.add(getTestGridName(i));
+
+        for (int i = 1; i < GRID_CNT; i += 2)
+            grp2.add(getTestGridName(i));
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void beforeTestsStarted() throws Exception {
+        extClsLdr1 = new GridTestExternalClassLoader(URLS, NOOP_SERVICE_2_CLS_NAME);
+        extClsLdr2 = new GridTestExternalClassLoader(URLS, NOOP_SERVICE_CLS_NAME);
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void afterTestsStopped() throws Exception {
+        extClsLdr1 = null;
+        extClsLdr2 = null;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void afterTest() throws Exception {
+        stopAllGrids();
+
+        super.afterTest();
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testServiceDeployment1() throws Exception {
+        startGrid(0).services().deploy(serviceConfig(true));
+
+        startGrid(1).services().deploy(serviceConfig(false));
+
+        client = true;
+
+        startGrid(2).services().deploy(serviceConfig(true));
+
+        startGrid(3).services().deploy(serviceConfig(false));
+
+        for (int i = 0; i < 4; i++)
+            ignite(i).services().serviceDescriptors();
+
+        ignite(0).services().cancel("TestDeploymentService1");
+
+        ignite(1).services().cancel("TestDeploymentService2");
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testServiceDeployment2() throws Exception {
+        for (int i = 0 ; i < 4; i++)
+            startGrid(i);
+
+        client = true;
+
+        for (int i = 4 ; i < 6; i++)
+            startGrid(i);
+
+        ignite(4).services().deploy(serviceConfig(true));
+
+        ignite(5).services().deploy(serviceConfig(false));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testServiceDeployment3() throws Exception {
+        startGrid(0).services().deploy(serviceConfig(true));
+
+        startGrid(1);
+
+        startGrid(2);
+
+        stopGrid(0);
+
+        awaitPartitionMapExchange();
+
+        ignite(1).services().deploy(serviceConfig(false));
+
+        startGrid(0);
+    }
+
+    /**
+     * @param firstGrp First group flag.
+     * @return Service configuration.
+     * @throws Exception If failed.
+     */
+    private ServiceConfiguration serviceConfig(final boolean firstGrp) throws Exception {
+        ServiceConfiguration srvCfg = new ServiceConfiguration();
+
+        srvCfg.setNodeFilter(new TestNodeFilter(firstGrp ? grp1 : grp2));
+
+        Class<Service> srvcCls;
+
+        if (firstGrp)
+            srvcCls = (Class<Service>)extClsLdr1.loadClass(NOOP_SERVICE_CLS_NAME);
+        else
+            srvcCls = (Class<Service>)extClsLdr2.loadClass(NOOP_SERVICE_2_CLS_NAME);
+
+        Service srvc = srvcCls.newInstance();
+
+        srvCfg.setService(srvc);
+
+        srvCfg.setName("TestDeploymentService" + (firstGrp ? 1 : 2));
+
+        srvCfg.setMaxPerNodeCount(1);
+
+        return srvCfg;
+    }
+
+    /**
+     *
+     */
+    private static class TestNodeFilter implements IgnitePredicate<ClusterNode> {
+        /** */
+        private Set<String> grp;
+
+        /**
+         * @param grp Group.
+         */
+        private TestNodeFilter(Set<String> grp) {
+            this.grp = grp;
+        }
+
+        /** {@inheritDoc} */
+        @SuppressWarnings("SuspiciousMethodCalls")
+        @Override public boolean apply(ClusterNode node) {
+            Object gridName = node.attribute(NODE_NAME_ATTR);
+
+            return grp.contains(gridName);
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/b5f59412/modules/core/src/test/java/org/apache/ignite/internal/processors/service/IgniteServiceDeployment2ClassLoadersJdkMarshallerTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/service/IgniteServiceDeployment2ClassLoadersJdkMarshallerTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/service/IgniteServiceDeployment2ClassLoadersJdkMarshallerTest.java
new file mode 100644
index 0000000..f9e24c1
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/service/IgniteServiceDeployment2ClassLoadersJdkMarshallerTest.java
@@ -0,0 +1,31 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.ignite.internal.processors.service;
+
+import org.apache.ignite.marshaller.Marshaller;
+import org.apache.ignite.marshaller.jdk.JdkMarshaller;
+
+/**
+ * Tests that not all nodes in cluster need user's service definition (only nodes according to filter).
+ */
+public class IgniteServiceDeployment2ClassLoadersJdkMarshallerTest
+    extends IgniteServiceDeployment2ClassLoadersDefaultMarshallerTest{
+    /** {@inheritDoc} */
+    @Override protected Marshaller marshaller() {
+        return new JdkMarshaller();
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/b5f59412/modules/core/src/test/java/org/apache/ignite/internal/processors/service/IgniteServiceDeployment2ClassLoadersOptimizedMarshallerTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/service/IgniteServiceDeployment2ClassLoadersOptimizedMarshallerTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/service/IgniteServiceDeployment2ClassLoadersOptimizedMarshallerTest.java
new file mode 100644
index 0000000..f2988cc
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/service/IgniteServiceDeployment2ClassLoadersOptimizedMarshallerTest.java
@@ -0,0 +1,31 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.ignite.internal.processors.service;
+
+import org.apache.ignite.marshaller.Marshaller;
+import org.apache.ignite.marshaller.optimized.OptimizedMarshaller;
+
+/**
+ * Tests that not all nodes in cluster need user's service definition (only nodes according to filter).
+ */
+public class IgniteServiceDeployment2ClassLoadersOptimizedMarshallerTest
+    extends IgniteServiceDeployment2ClassLoadersDefaultMarshallerTest{
+    /** {@inheritDoc} */
+    @Override protected Marshaller marshaller() {
+        return new OptimizedMarshaller(false);
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/b5f59412/modules/core/src/test/java/org/apache/ignite/internal/processors/service/IgniteServiceDeploymentClassLoadingDefaultMarshallerTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/service/IgniteServiceDeploymentClassLoadingDefaultMarshallerTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/service/IgniteServiceDeploymentClassLoadingDefaultMarshallerTest.java
new file mode 100644
index 0000000..a8599f4
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/service/IgniteServiceDeploymentClassLoadingDefaultMarshallerTest.java
@@ -0,0 +1,212 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.ignite.internal.processors.service;
+
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Set;
+import org.apache.ignite.cluster.ClusterNode;
+import org.apache.ignite.configuration.IgniteConfiguration;
+import org.apache.ignite.lang.IgnitePredicate;
+import org.apache.ignite.marshaller.Marshaller;
+import org.apache.ignite.services.Service;
+import org.apache.ignite.services.ServiceConfiguration;
+import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi;
+import org.apache.ignite.spi.discovery.tcp.ipfinder.TcpDiscoveryIpFinder;
+import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder;
+import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
+
+/**
+ * Tests that not all nodes in cluster need user's service definition (only nodes according to filter).
+ */
+public class IgniteServiceDeploymentClassLoadingDefaultMarshallerTest extends GridCommonAbstractTest {
+    /** */
+    private static final String NOOP_SERVICE_CLS_NAME = "org.apache.ignite.tests.p2p.NoopService";
+
+    /** IP finder. */
+    private static final TcpDiscoveryIpFinder IP_FINDER = new TcpDiscoveryVmIpFinder(true);
+
+    /** */
+    private static final int SERVER_NODE = 0;
+
+    /** */
+    private static final int SERVER_NODE_WITH_EXT_CLASS_LOADER = 1;
+
+    /** */
+    private static final int CLIENT_NODE = 2;
+
+    /** */
+    private static final int CLIENT_NODE_WITH_EXT_CLASS_LOADER = 3;
+
+    /** */
+    private static final String NODE_NAME_ATTR = "NODE_NAME";
+
+    /** */
+    private static ClassLoader extClsLdr;
+
+    /** */
+    private Set<String> extClsLdrGrids = new HashSet<>();
+
+    /** {@inheritDoc} */
+    @Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception {
+        IgniteConfiguration cfg = super.getConfiguration(gridName);
+
+        cfg.setPeerClassLoadingEnabled(false);
+
+        TcpDiscoverySpi discoSpi = new TcpDiscoverySpi();
+
+        discoSpi.setIpFinder(IP_FINDER);
+
+        cfg.setDiscoverySpi(discoSpi);
+
+        cfg.setMarshaller(marshaller());
+
+        cfg.setUserAttributes(Collections.singletonMap(NODE_NAME_ATTR, gridName));
+
+        if (getTestGridName(CLIENT_NODE_WITH_EXT_CLASS_LOADER).equals(gridName)
+            || getTestGridName(CLIENT_NODE).equals(gridName))
+            cfg.setClientMode(true);
+
+        if (extClsLdrGrids.contains(gridName))
+            cfg.setClassLoader(extClsLdr);
+
+        return cfg;
+    }
+
+    /**
+     * @return Marshaller.
+     */
+    protected Marshaller marshaller() {
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void beforeTest() throws Exception {
+        super.beforeTest();
+
+        extClsLdrGrids.clear();
+
+        extClsLdrGrids.add(getTestGridName(SERVER_NODE_WITH_EXT_CLASS_LOADER));
+        extClsLdrGrids.add(getTestGridName(CLIENT_NODE_WITH_EXT_CLASS_LOADER));
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void afterTest() throws Exception {
+        stopAllGrids();
+
+        super.afterTest();
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void beforeTestsStarted() throws Exception {
+        extClsLdr = getExternalClassLoader();
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void afterTestsStopped() throws Exception {
+        extClsLdr = null;
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testServiceDeployment1() throws Exception {
+        startGrid(SERVER_NODE);
+
+        startGrid(SERVER_NODE_WITH_EXT_CLASS_LOADER).services().deploy(serviceConfig());
+
+        startGrid(CLIENT_NODE);
+
+        startGrid(CLIENT_NODE_WITH_EXT_CLASS_LOADER).services().deploy(serviceConfig());
+
+        ignite(SERVER_NODE).services().serviceDescriptors();
+
+        ignite(SERVER_NODE_WITH_EXT_CLASS_LOADER).services().serviceDescriptors();
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testServiceDeployment2() throws Exception {
+        startGrid(SERVER_NODE);
+
+        startGrid(CLIENT_NODE_WITH_EXT_CLASS_LOADER).services().deploy(serviceConfig());
+
+        startGrid(CLIENT_NODE);
+
+        startGrid(SERVER_NODE_WITH_EXT_CLASS_LOADER).services().deploy(serviceConfig());
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testServiceDeployment3() throws Exception {
+        startGrid(SERVER_NODE_WITH_EXT_CLASS_LOADER).services().deploy(serviceConfig());
+
+        startGrid(SERVER_NODE);
+
+        startGrid(CLIENT_NODE);
+
+        startGrid(CLIENT_NODE_WITH_EXT_CLASS_LOADER).services().deploy(serviceConfig());
+    }
+
+    /**
+     * @return Service configuration.
+     * @throws Exception If failed.
+     */
+    private ServiceConfiguration serviceConfig() throws Exception {
+        ServiceConfiguration srvCfg = new ServiceConfiguration();
+
+        srvCfg.setNodeFilter(new TestNodeFilter(extClsLdrGrids));
+
+        Class<Service> srvcCls = (Class<Service>)extClsLdr.loadClass(NOOP_SERVICE_CLS_NAME);
+
+        Service srvc = srvcCls.newInstance();
+
+        srvCfg.setService(srvc);
+
+        srvCfg.setName("TestDeploymentService");
+
+        srvCfg.setMaxPerNodeCount(1);
+
+        return srvCfg;
+    }
+
+    /**
+     *
+     */
+    private static class TestNodeFilter implements IgnitePredicate<ClusterNode> {
+        /** */
+        private static final long serialVersionUID = 0;
+
+        /** */
+        private Set<String> grids;
+
+        /**
+         * @param grids Grid names.
+         */
+        private TestNodeFilter(Set<String> grids) {
+            this.grids = grids;
+        }
+
+        /** {@inheritDoc} */
+        @SuppressWarnings("SuspiciousMethodCalls")
+        @Override public boolean apply(ClusterNode node) {
+            return grids.contains(node.attribute(NODE_NAME_ATTR));
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/b5f59412/modules/core/src/test/java/org/apache/ignite/internal/processors/service/IgniteServiceDeploymentClassLoadingJdkMarshallerTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/service/IgniteServiceDeploymentClassLoadingJdkMarshallerTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/service/IgniteServiceDeploymentClassLoadingJdkMarshallerTest.java
new file mode 100644
index 0000000..aeb68af
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/service/IgniteServiceDeploymentClassLoadingJdkMarshallerTest.java
@@ -0,0 +1,31 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.ignite.internal.processors.service;
+
+import org.apache.ignite.marshaller.Marshaller;
+import org.apache.ignite.marshaller.jdk.JdkMarshaller;
+
+/**
+ * Tests that not all nodes in cluster need user's service definition (only nodes according to filter).
+ */
+public class IgniteServiceDeploymentClassLoadingJdkMarshallerTest
+    extends IgniteServiceDeploymentClassLoadingDefaultMarshallerTest {
+    /** {@inheritDoc} */
+    @Override protected Marshaller marshaller() {
+        return new JdkMarshaller();
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/b5f59412/modules/core/src/test/java/org/apache/ignite/internal/processors/service/IgniteServiceDeploymentClassLoadingOptimizedMarshallerTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/service/IgniteServiceDeploymentClassLoadingOptimizedMarshallerTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/service/IgniteServiceDeploymentClassLoadingOptimizedMarshallerTest.java
new file mode 100644
index 0000000..cb0c911
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/service/IgniteServiceDeploymentClassLoadingOptimizedMarshallerTest.java
@@ -0,0 +1,31 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.ignite.internal.processors.service;
+
+import org.apache.ignite.marshaller.Marshaller;
+import org.apache.ignite.marshaller.optimized.OptimizedMarshaller;
+
+/**
+ * Tests that not all nodes in cluster need user's service definition (only nodes according to filter).
+ */
+public class IgniteServiceDeploymentClassLoadingOptimizedMarshallerTest
+    extends IgniteServiceDeploymentClassLoadingDefaultMarshallerTest {
+    /** {@inheritDoc} */
+    @Override protected Marshaller marshaller() {
+        return new OptimizedMarshaller(false);
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/b5f59412/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteKernalSelfTestSuite.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteKernalSelfTestSuite.java b/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteKernalSelfTestSuite.java
index 05d33d7..b9e64c3 100644
--- a/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteKernalSelfTestSuite.java
+++ b/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteKernalSelfTestSuite.java
@@ -58,6 +58,12 @@ import org.apache.ignite.internal.processors.service.GridServiceProxyClientRecon
 import org.apache.ignite.internal.processors.service.GridServiceProxyNodeStopSelfTest;
 import org.apache.ignite.internal.processors.service.GridServiceReassignmentSelfTest;
 import org.apache.ignite.internal.processors.service.GridServiceSerializationSelfTest;
+import org.apache.ignite.internal.processors.service.IgniteServiceDeployment2ClassLoadersDefaultMarshallerTest;
+import org.apache.ignite.internal.processors.service.IgniteServiceDeployment2ClassLoadersJdkMarshallerTest;
+import org.apache.ignite.internal.processors.service.IgniteServiceDeployment2ClassLoadersOptimizedMarshallerTest;
+import org.apache.ignite.internal.processors.service.IgniteServiceDeploymentClassLoadingDefaultMarshallerTest;
+import org.apache.ignite.internal.processors.service.IgniteServiceDeploymentClassLoadingJdkMarshallerTest;
+import org.apache.ignite.internal.processors.service.IgniteServiceDeploymentClassLoadingOptimizedMarshallerTest;
 import org.apache.ignite.internal.processors.service.ServicePredicateAccessCacheTest;
 import org.apache.ignite.internal.util.GridStartupWithSpecifiedWorkDirectorySelfTest;
 import org.apache.ignite.internal.util.GridStartupWithUndefinedIgniteHomeSelfTest;
@@ -132,6 +138,13 @@ public class IgniteKernalSelfTestSuite extends TestSuite {
         suite.addTestSuite(GridServiceProxyNodeStopSelfTest.class);
         suite.addTestSuite(GridServiceProxyClientReconnectSelfTest.class);
 
+        suite.addTestSuite(IgniteServiceDeploymentClassLoadingDefaultMarshallerTest.class);
+        suite.addTestSuite(IgniteServiceDeploymentClassLoadingOptimizedMarshallerTest.class);
+        suite.addTestSuite(IgniteServiceDeploymentClassLoadingJdkMarshallerTest.class);
+        suite.addTestSuite(IgniteServiceDeployment2ClassLoadersDefaultMarshallerTest.class);
+        suite.addTestSuite(IgniteServiceDeployment2ClassLoadersOptimizedMarshallerTest.class);
+        suite.addTestSuite(IgniteServiceDeployment2ClassLoadersJdkMarshallerTest.class);
+
         return suite;
     }
 }

http://git-wip-us.apache.org/repos/asf/ignite/blob/b5f59412/modules/extdata/p2p/src/main/java/org/apache/ignite/tests/p2p/NoopService.java
----------------------------------------------------------------------
diff --git a/modules/extdata/p2p/src/main/java/org/apache/ignite/tests/p2p/NoopService.java b/modules/extdata/p2p/src/main/java/org/apache/ignite/tests/p2p/NoopService.java
new file mode 100644
index 0000000..b3d06b2
--- /dev/null
+++ b/modules/extdata/p2p/src/main/java/org/apache/ignite/tests/p2p/NoopService.java
@@ -0,0 +1,41 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ignite.tests.p2p;
+
+import org.apache.ignite.services.Service;
+import org.apache.ignite.services.ServiceContext;
+
+/**
+ * No-op service.
+ */
+public class NoopService implements Service {
+    /** {@inheritDoc} */
+    @Override public void cancel(ServiceContext ctx) {
+        // No-op.
+    }
+
+    /** {@inheritDoc} */
+    @Override public void init(ServiceContext ctx) throws Exception {
+        // No-op.
+    }
+
+    /** {@inheritDoc} */
+    @Override public void execute(ServiceContext ctx) throws Exception {
+        // No-op.
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/b5f59412/modules/extdata/p2p/src/main/java/org/apache/ignite/tests/p2p/NoopService2.java
----------------------------------------------------------------------
diff --git a/modules/extdata/p2p/src/main/java/org/apache/ignite/tests/p2p/NoopService2.java b/modules/extdata/p2p/src/main/java/org/apache/ignite/tests/p2p/NoopService2.java
new file mode 100644
index 0000000..ad65d5b
--- /dev/null
+++ b/modules/extdata/p2p/src/main/java/org/apache/ignite/tests/p2p/NoopService2.java
@@ -0,0 +1,41 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ignite.tests.p2p;
+
+import org.apache.ignite.services.Service;
+import org.apache.ignite.services.ServiceContext;
+
+/**
+ * No-op service.
+ */
+public class NoopService2 implements Service {
+    /** {@inheritDoc} */
+    @Override public void cancel(ServiceContext ctx) {
+        // No-op.
+    }
+
+    /** {@inheritDoc} */
+    @Override public void init(ServiceContext ctx) throws Exception {
+        // No-op.
+    }
+
+    /** {@inheritDoc} */
+    @Override public void execute(ServiceContext ctx) throws Exception {
+        // No-op.
+    }
+}


[09/17] ignite git commit: ignite-2620: Need override 'unswap' for detached entry. (cherry picked from commit f7b376b)

Posted by dm...@apache.org.
ignite-2620: Need override 'unswap' for detached entry.
(cherry picked from commit f7b376b)


Project: http://git-wip-us.apache.org/repos/asf/ignite/repo
Commit: http://git-wip-us.apache.org/repos/asf/ignite/commit/c8269da3
Tree: http://git-wip-us.apache.org/repos/asf/ignite/tree/c8269da3
Diff: http://git-wip-us.apache.org/repos/asf/ignite/diff/c8269da3

Branch: refs/heads/master
Commit: c8269da30a1d55f06531857c52d254268056e84e
Parents: 54e432e
Author: sboikov <sb...@gridgain.com>
Authored: Tue May 24 11:14:03 2016 +0300
Committer: sboikov <sb...@gridgain.com>
Committed: Tue May 24 13:42:36 2016 +0300

----------------------------------------------------------------------
 .../internal/processors/cache/GridCacheMapEntry.java    | 12 ++++++++----
 .../dht/colocated/GridDhtDetachedCacheEntry.java        |  2 +-
 2 files changed, 9 insertions(+), 5 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/c8269da3/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheMapEntry.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheMapEntry.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheMapEntry.java
index 4fbe0e6..de69f53 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheMapEntry.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheMapEntry.java
@@ -475,12 +475,12 @@ public abstract class GridCacheMapEntry extends GridMetadataAwareAdapter impleme
     }
 
     /** {@inheritDoc} */
-    @Override public CacheObject unswap() throws IgniteCheckedException, GridCacheEntryRemovedException {
+    @Override public final CacheObject unswap() throws IgniteCheckedException, GridCacheEntryRemovedException {
         return unswap(true);
     }
 
     /** {@inheritDoc} */
-    @Nullable @Override public CacheObject unswap(boolean needVal)
+    @Nullable @Override public final CacheObject unswap(boolean needVal)
         throws IgniteCheckedException, GridCacheEntryRemovedException {
         return unswap(needVal, true);
     }
@@ -489,14 +489,18 @@ public abstract class GridCacheMapEntry extends GridMetadataAwareAdapter impleme
      * Unswaps an entry.
      *
      * @param needVal If {@code false} then do not to deserialize value during unswap.
+     * @param checkExpire If {@code true} checks for expiration, as result entry can be obsoleted or marked deleted.
      * @return Value.
      * @throws IgniteCheckedException If failed.
+     * @throws GridCacheEntryRemovedException If entry was removed.
      */
-    @Nullable private CacheObject unswap(boolean needVal, boolean checkExpire)
+    @Nullable protected CacheObject unswap(boolean needVal, boolean checkExpire)
         throws IgniteCheckedException, GridCacheEntryRemovedException {
         if (!cctx.isSwapOrOffheapEnabled())
             return null;
 
+        assert !detached() : this;
+
         boolean obsolete = false;
         boolean deferred = false;
         GridCacheVersion ver0 = null;
@@ -527,7 +531,7 @@ public abstract class GridCacheMapEntry extends GridMetadataAwareAdapter impleme
                     }
                 }
                 else
-                    e = detached() ? cctx.swap().read(this, true, true, true, false) : cctx.swap().readAndRemove(this);
+                    e = cctx.swap().readAndRemove(this);
 
                 if (log.isDebugEnabled())
                     log.debug("Read swap entry [swapEntry=" + e + ", cacheEntry=" + this + ']');

http://git-wip-us.apache.org/repos/asf/ignite/blob/c8269da3/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/colocated/GridDhtDetachedCacheEntry.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/colocated/GridDhtDetachedCacheEntry.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/colocated/GridDhtDetachedCacheEntry.java
index c06f68b..db91134 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/colocated/GridDhtDetachedCacheEntry.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/colocated/GridDhtDetachedCacheEntry.java
@@ -57,7 +57,7 @@ public class GridDhtDetachedCacheEntry extends GridDistributedCacheEntry {
     }
 
     /** {@inheritDoc} */
-    @Nullable @Override public CacheObject unswap(boolean needVal) throws IgniteCheckedException {
+    @Nullable @Override public CacheObject unswap(boolean needVal, boolean checkExpire) throws IgniteCheckedException {
         return null;
     }
 


[08/17] ignite git commit: ignite-2899 Fixed issues with 'keepBinary' handling, added test. (cherry picked from commit e47440d)

Posted by dm...@apache.org.
ignite-2899 Fixed issues with 'keepBinary' handling, added test.
(cherry picked from commit e47440d)


Project: http://git-wip-us.apache.org/repos/asf/ignite/repo
Commit: http://git-wip-us.apache.org/repos/asf/ignite/commit/54e432e9
Tree: http://git-wip-us.apache.org/repos/asf/ignite/tree/54e432e9
Diff: http://git-wip-us.apache.org/repos/asf/ignite/diff/54e432e9

Branch: refs/heads/master
Commit: 54e432e9bb6927351ea45d85b94965925a8351c7
Parents: 07611bd
Author: sboikov <sb...@gridgain.com>
Authored: Mon May 23 21:08:14 2016 +0300
Committer: sboikov <sb...@gridgain.com>
Committed: Tue May 24 11:21:11 2016 +0300

----------------------------------------------------------------------
 .../processors/cache/GridCacheAdapter.java      |  71 +++-
 .../CacheKeepBinaryWithInterceptorTest.java     | 419 +++++++++++++++++++
 .../testsuites/IgniteBinaryCacheTestSuite.java  |   2 +
 3 files changed, 471 insertions(+), 21 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/54e432e9/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheAdapter.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheAdapter.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheAdapter.java
index b68a8ca..3a72ba2 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheAdapter.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheAdapter.java
@@ -1388,10 +1388,18 @@ public abstract class GridCacheAdapter<K, V> implements IgniteInternalCache<K, V
 
         long start = statsEnabled ? System.nanoTime() : 0L;
 
-        V val = get(key, !ctx.keepBinary(), false);
+        boolean keeyBinary = ctx.keepBinary();
+
+        if (keeyBinary)
+            key = (K)ctx.toCacheKeyObject(key);
+
+        V val = get(key, !keeyBinary, false);
+
+        if (ctx.config().getInterceptor() != null) {
+            key = keeyBinary ? (K) ctx.unwrapBinaryIfNeeded(key, true, false) : key;
 
-        if (ctx.config().getInterceptor() != null)
             val = (V)ctx.config().getInterceptor().onGet(key, val);
+        }
 
         if (statsEnabled)
             metrics0().addGetTimeNanos(System.nanoTime() - start);
@@ -1407,18 +1415,22 @@ public abstract class GridCacheAdapter<K, V> implements IgniteInternalCache<K, V
 
         long start = statsEnabled ? System.nanoTime() : 0L;
 
-        if (ctx.keepBinary())
+        boolean keepBinary = ctx.keepBinary();
+
+        if (keepBinary)
             key = (K)ctx.toCacheKeyObject(key);
 
-        T2<V, GridCacheVersion> t = (T2<V, GridCacheVersion>)get(key, !ctx.keepBinary(), true);
+        T2<V, GridCacheVersion> t = (T2<V, GridCacheVersion>)get(key, !keepBinary, true);
 
         CacheEntry<K, V> val = t != null ? new CacheEntryImplEx<>(
-            ctx.keepBinary() ? (K)ctx.unwrapBinaryIfNeeded(key, true, false) : key,
+            keepBinary ? (K)ctx.unwrapBinaryIfNeeded(key, true, false) : key,
             t.get1(),
             t.get2())
             : null;
 
         if (ctx.config().getInterceptor() != null) {
+            key = keepBinary ? (K) ctx.unwrapBinaryIfNeeded(key, true, false) : key;
+
             V val0 = (V)ctx.config().getInterceptor().onGet(key, t != null ? val.getValue() : null);
 
             val = (val0 != null) ? new CacheEntryImplEx<>(key, val0, t != null ? t.get2() : null) : null;
@@ -1438,11 +1450,17 @@ public abstract class GridCacheAdapter<K, V> implements IgniteInternalCache<K, V
 
         final long start = statsEnabled ? System.nanoTime() : 0L;
 
-        IgniteInternalFuture<V> fut = getAsync(key, !ctx.keepBinary(), false);
+        final boolean keepBinary = ctx.keepBinary();
+
+        final K key0 = keepBinary ? (K)ctx.toCacheKeyObject(key) : key;
+
+        IgniteInternalFuture<V> fut = getAsync(key, !keepBinary, false);
 
         if (ctx.config().getInterceptor() != null)
             fut = fut.chain(new CX1<IgniteInternalFuture<V>, V>() {
                 @Override public V applyx(IgniteInternalFuture<V> f) throws IgniteCheckedException {
+                    K key = keepBinary ? (K)ctx.unwrapBinaryIfNeeded(key0, true, false) : key0;
+
                     return (V)ctx.config().getInterceptor().onGet(key, f.get());
                 }
             });
@@ -1461,10 +1479,12 @@ public abstract class GridCacheAdapter<K, V> implements IgniteInternalCache<K, V
 
         final long start = statsEnabled ? System.nanoTime() : 0L;
 
-        final K key0 = ctx.keepBinary() ? (K)ctx.toCacheKeyObject(key) : key;
+        final boolean keepBinary = ctx.keepBinary();
+
+        final K key0 = keepBinary ? (K)ctx.toCacheKeyObject(key) : key;
 
         IgniteInternalFuture<T2<V, GridCacheVersion>> fut =
-            (IgniteInternalFuture<T2<V, GridCacheVersion>>)getAsync(key0, !ctx.keepBinary(), true);
+            (IgniteInternalFuture<T2<V, GridCacheVersion>>)getAsync(key0, !keepBinary, true);
 
         final boolean intercept = ctx.config().getInterceptor() != null;
 
@@ -1474,19 +1494,21 @@ public abstract class GridCacheAdapter<K, V> implements IgniteInternalCache<K, V
                     throws IgniteCheckedException {
                     T2<V, GridCacheVersion> t = f.get();
 
-                    CacheEntry val = t != null ? new CacheEntryImplEx<>(
-                        ctx.keepBinary() ? (K)ctx.unwrapBinaryIfNeeded(key0, true, false) : key0,
-                        t.get1(),
-                        t.get2())
-                        : null;
+                K key = keepBinary ? (K)ctx.unwrapBinaryIfNeeded(key0, true, false) : key0;
 
-                    if (intercept) {
-                        V val0 = (V)ctx.config().getInterceptor().onGet(key0, t != null ? val.getValue() : null);
+                CacheEntry val = t != null ? new CacheEntryImplEx<>(
+                    key,
+                    t.get1(),
+                    t.get2())
+                    : null;
 
-                        return val0 != null ? new CacheEntryImplEx(key0, val0, t != null ? t.get2() : null) : null;
-                    }
-                    else
-                        return val;
+                if (intercept) {
+                    V val0 = (V)ctx.config().getInterceptor().onGet(key, t != null ? val.getValue() : null);
+
+                    return val0 != null ? new CacheEntryImplEx(key, val0, t != null ? t.get2() : null) : null;
+                }
+                else
+                    return val;
             }
         });
 
@@ -2870,17 +2892,24 @@ public abstract class GridCacheAdapter<K, V> implements IgniteInternalCache<K, V
         if (keyCheck)
             validateCacheKey(key);
 
+        final boolean keepBinary = ctx.keepBinary();
+
         V prevVal = syncOp(new SyncOp<V>(true) {
             @Override public V op(IgniteTxLocalAdapter tx) throws IgniteCheckedException {
+                K key0 = keepBinary ? (K)ctx.toCacheKeyObject(key) : key;
+
                 V ret = tx.removeAllAsync(ctx,
                     null,
-                    Collections.singletonList(key),
+                    Collections.singletonList(key0),
                     /*retval*/true,
                     null,
                     /*singleRmv*/false).get().value();
 
-                if (ctx.config().getInterceptor() != null)
+                if (ctx.config().getInterceptor() != null) {
+                    K key = keepBinary ? (K)ctx.unwrapBinaryIfNeeded(key0, true, false) : key0;
+
                     return (V)ctx.config().getInterceptor().onBeforeRemove(new CacheEntryImpl(key, ret)).get2();
+                }
 
                 return ret;
             }

http://git-wip-us.apache.org/repos/asf/ignite/blob/54e432e9/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/binary/CacheKeepBinaryWithInterceptorTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/binary/CacheKeepBinaryWithInterceptorTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/binary/CacheKeepBinaryWithInterceptorTest.java
new file mode 100644
index 0000000..60b48a8
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/binary/CacheKeepBinaryWithInterceptorTest.java
@@ -0,0 +1,419 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ignite.internal.processors.cache.binary;
+
+import org.apache.ignite.IgniteCache;
+import org.apache.ignite.binary.BinaryObject;
+import org.apache.ignite.cache.CacheAtomicityMode;
+import org.apache.ignite.cache.CacheInterceptor;
+import org.apache.ignite.cache.CacheWriteSynchronizationMode;
+import org.apache.ignite.configuration.CacheConfiguration;
+import org.apache.ignite.configuration.IgniteConfiguration;
+import org.apache.ignite.lang.IgniteBiTuple;
+import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi;
+import org.apache.ignite.spi.discovery.tcp.ipfinder.TcpDiscoveryIpFinder;
+import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder;
+import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
+import org.jetbrains.annotations.Nullable;
+
+import javax.cache.Cache;
+
+import static org.apache.ignite.cache.CacheAtomicityMode.*;
+import static org.apache.ignite.cache.CacheWriteSynchronizationMode.*;
+
+/**
+ *
+ */
+@SuppressWarnings("unchecked")
+public class CacheKeepBinaryWithInterceptorTest extends GridCommonAbstractTest {
+    /** */
+    private static final TcpDiscoveryIpFinder IP_FINDER = new TcpDiscoveryVmIpFinder(true);
+
+    /** {@inheritDoc} */
+    @Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception {
+        IgniteConfiguration cfg = super.getConfiguration(gridName);
+
+        ((TcpDiscoverySpi)cfg.getDiscoverySpi()).setIpFinder(IP_FINDER);
+
+        cfg.setMarshaller(null);
+
+        return cfg;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void beforeTestsStarted() throws Exception {
+        super.beforeTestsStarted();
+
+        startGrid(0);
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void afterTestsStopped() throws Exception {
+        stopAllGrids();
+
+        super.afterTestsStopped();
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testKeepBinaryWithInterceptor() throws Exception {
+        keepBinaryWithInterceptor(cacheConfiguration(ATOMIC, false));
+        keepBinaryWithInterceptor(cacheConfiguration(TRANSACTIONAL, false));
+
+        keepBinaryWithInterceptorPrimitives(cacheConfiguration(ATOMIC, true));
+        keepBinaryWithInterceptorPrimitives(cacheConfiguration(TRANSACTIONAL, true));
+
+        startGridsMultiThreaded(1, 3);
+
+        keepBinaryWithInterceptor(cacheConfiguration(ATOMIC, false));
+        keepBinaryWithInterceptor(cacheConfiguration(TRANSACTIONAL, false));
+
+        keepBinaryWithInterceptorPrimitives(cacheConfiguration(ATOMIC, true));
+        keepBinaryWithInterceptorPrimitives(cacheConfiguration(TRANSACTIONAL, true));
+    }
+
+    /**
+     * @param ccfg Cache configuration.
+     */
+    private void keepBinaryWithInterceptor(CacheConfiguration ccfg) {
+        ignite(0).createCache(ccfg);
+
+        try {
+            TestInterceptor1.onAfterRmv = 0;
+            TestInterceptor1.onBeforeRmv = 0;
+            TestInterceptor1.onAfterPut = 0;
+            TestInterceptor1.onBeforePut = 0;
+            TestInterceptor1.onGet = 0;
+
+            IgniteCache cache = ignite(0).cache(null).withKeepBinary();
+
+            IgniteCache asyncCache = cache.withAsync();
+
+            cache.put(new TestKey(1), new TestValue(10));
+
+            cache.put(new TestKey(1), new TestValue(10));
+
+            BinaryObject obj = (BinaryObject)cache.get(new TestKey(1));
+            assertEquals(10, obj.field("val"));
+
+            asyncCache.get(new TestKey(1));
+            obj = (BinaryObject)asyncCache.future().get();
+            assertEquals(10, obj.field("val"));
+
+            Cache.Entry<BinaryObject, BinaryObject> e = (Cache.Entry)cache.getEntry(new TestKey(1));
+            assertEquals(1, e.getKey().field("key"));
+            assertEquals(10, e.getValue().field("val"));
+
+            asyncCache.getEntry(new TestKey(1));
+            e = (Cache.Entry)asyncCache.future().get();
+            assertEquals(1, e.getKey().field("key"));
+            assertEquals(10, e.getValue().field("val"));
+
+            obj = (BinaryObject)cache.getAndRemove(new TestKey(1));
+            assertEquals(10, obj.field("val"));
+
+            cache.put(new TestKey(1), new TestValue(10));
+
+            assertTrue(cache.remove(new TestKey(1)));
+
+            assertTrue(TestInterceptor1.onAfterRmv > 0);
+            assertTrue(TestInterceptor1.onBeforeRmv > 0);
+            assertTrue(TestInterceptor1.onAfterPut > 0);
+            assertTrue(TestInterceptor1.onBeforePut > 0);
+            assertTrue(TestInterceptor1.onGet > 0);
+        }
+        finally {
+            ignite(0).destroyCache(ccfg.getName());
+        }
+    }
+
+    /**
+     * @param ccfg Cache configuration.
+     */
+    private void keepBinaryWithInterceptorPrimitives(CacheConfiguration ccfg) {
+        ignite(0).createCache(ccfg);
+
+        try {
+            TestInterceptor2.onAfterRmv = 0;
+            TestInterceptor2.onBeforeRmv = 0;
+            TestInterceptor2.onAfterPut = 0;
+            TestInterceptor2.onBeforePut = 0;
+            TestInterceptor2.onGet = 0;
+
+            IgniteCache cache = ignite(0).cache(null).withKeepBinary();
+
+            IgniteCache asyncCache = cache.withAsync();
+
+            cache.put(1, 10);
+
+            cache.put(1, 10);
+
+            Integer obj = (Integer)cache.get(1);
+            assertEquals((Integer)10, obj);
+
+            asyncCache.get(1);
+            obj = (Integer)asyncCache.future().get();
+            assertEquals((Integer)10, obj);
+
+            Cache.Entry<Integer, Integer> e = (Cache.Entry)cache.getEntry(1);
+            assertEquals((Integer)1, e.getKey());
+            assertEquals((Integer)10, e.getValue());
+
+            asyncCache.getEntry(1);
+            e = (Cache.Entry)asyncCache.future().get();
+            assertEquals((Integer)1, e.getKey());
+            assertEquals((Integer)10, e.getValue());
+
+            obj = (Integer)cache.getAndRemove(1);
+            assertEquals((Integer)10, obj);
+
+            cache.put(1, 10);
+
+            assertTrue(cache.remove(1));
+
+            assertTrue(TestInterceptor2.onAfterRmv > 0);
+            assertTrue(TestInterceptor2.onBeforeRmv > 0);
+            assertTrue(TestInterceptor2.onAfterPut > 0);
+            assertTrue(TestInterceptor2.onBeforePut > 0);
+            assertTrue(TestInterceptor2.onGet > 0);
+        }
+        finally {
+            ignite(0).destroyCache(ccfg.getName());
+        }
+    }
+
+    /**
+     * @param atomicityMode Cache atomicity mode.
+     * @param testPrimitives {@code True} if test interceptor with primitive values.
+     * @return Cache configuration.
+     */
+    private CacheConfiguration cacheConfiguration(CacheAtomicityMode atomicityMode, boolean testPrimitives) {
+        CacheConfiguration ccfg = new CacheConfiguration();
+
+        ccfg.setAtomicityMode(atomicityMode);
+        ccfg.setInterceptor(testPrimitives ? new TestInterceptor2() : new TestInterceptor1());
+        ccfg.setWriteSynchronizationMode(FULL_SYNC);
+        ccfg.setBackups(1);
+
+        return ccfg;
+    }
+
+    /**
+     *
+     */
+    static class TestInterceptor1 implements CacheInterceptor<BinaryObject, BinaryObject> {
+        /** */
+        static int onGet;
+
+        /** */
+        static int onBeforePut;
+
+        /** */
+        static int onAfterPut;
+
+        /** */
+        static int onBeforeRmv;
+
+        /** */
+        static int onAfterRmv;
+
+        /** {@inheritDoc} */
+        @Nullable @Override public BinaryObject onGet(BinaryObject key, @Nullable BinaryObject val) {
+            System.out.println("Get [key=" + key + ", val=" + val + ']');
+
+            onGet++;
+
+            assertEquals(1, key.field("key"));
+            assertEquals(10, val.field("val"));
+
+            return val;
+        }
+
+        /** {@inheritDoc} */
+        @Nullable @Override public BinaryObject onBeforePut(Cache.Entry<BinaryObject, BinaryObject> entry, BinaryObject newVal) {
+            System.out.println("Before put [e=" + entry + ", newVal=" + newVal + ']');
+
+            onBeforePut++;
+
+            if (entry.getValue() != null)
+                assertEquals(10, entry.getValue().field("val"));
+
+            assertEquals(1, entry.getKey().field("key"));
+            assertEquals(10, newVal.field("val"));
+
+            return newVal;
+        }
+
+        /** {@inheritDoc} */
+        @Override public void onAfterPut(Cache.Entry<BinaryObject, BinaryObject> entry) {
+            System.out.println("After put [e=" + entry + ']');
+
+            onAfterPut++;
+
+            assertEquals(1, entry.getKey().field("key"));
+            assertEquals(10, entry.getValue().field("val"));
+        }
+
+        /** {@inheritDoc} */
+        @Nullable @Override public IgniteBiTuple<Boolean, BinaryObject> onBeforeRemove(Cache.Entry<BinaryObject, BinaryObject> entry) {
+            assertEquals(1, entry.getKey().field("key"));
+            assertEquals(10, entry.getValue().field("val"));
+
+            onBeforeRmv++;
+
+            return new IgniteBiTuple<>(false, entry.getValue());
+        }
+
+        /** {@inheritDoc} */
+        @Override public void onAfterRemove(Cache.Entry<BinaryObject, BinaryObject> entry) {
+            System.out.println("After remove [e=" + entry + ']');
+
+            onAfterRmv++;
+
+            assertEquals(1, entry.getKey().field("key"));
+            assertEquals(10, entry.getValue().field("val"));
+        }
+    }
+
+    /**
+     *
+     */
+    static class TestInterceptor2 implements CacheInterceptor<Integer, Integer> {
+        /** */
+        static int onGet;
+
+        /** */
+        static int onBeforePut;
+
+        /** */
+        static int onAfterPut;
+
+        /** */
+        static int onBeforeRmv;
+
+        /** */
+        static int onAfterRmv;
+
+        /** {@inheritDoc} */
+        @Nullable @Override public Integer onGet(Integer key, @Nullable Integer val) {
+            System.out.println("Get [key=" + key + ", val=" + val + ']');
+
+            onGet++;
+
+            assertEquals((Integer)1, key);
+            assertEquals((Integer)10, val);
+
+            return val;
+        }
+
+        /** {@inheritDoc} */
+        @Nullable @Override public Integer onBeforePut(Cache.Entry<Integer, Integer> entry, Integer newVal) {
+            System.out.println("Before put [e=" + entry + ", newVal=" + newVal + ']');
+
+            onBeforePut++;
+
+            if (entry.getValue() != null)
+                assertEquals((Integer)10, entry.getValue());
+
+            assertEquals((Integer)1, entry.getKey());
+            assertEquals((Integer)10, newVal);
+
+            return newVal;
+        }
+
+        /** {@inheritDoc} */
+        @Override public void onAfterPut(Cache.Entry<Integer, Integer> entry) {
+            System.out.println("After put [e=" + entry + ']');
+
+            onAfterPut++;
+
+            assertEquals((Integer)1, entry.getKey());
+            assertEquals((Integer)10, entry.getValue());
+        }
+
+        /** {@inheritDoc} */
+        @Nullable @Override public IgniteBiTuple<Boolean, Integer> onBeforeRemove(Cache.Entry<Integer, Integer> entry) {
+            assertEquals((Integer)1, entry.getKey());
+            assertEquals((Integer)10, entry.getValue());
+
+            onBeforeRmv++;
+
+            return new IgniteBiTuple<>(false, entry.getValue());
+        }
+
+        /** {@inheritDoc} */
+        @Override public void onAfterRemove(Cache.Entry<Integer, Integer> entry) {
+            System.out.println("After remove [e=" + entry + ']');
+
+            onAfterRmv++;
+
+            assertEquals((Integer)1, entry.getKey());
+            assertEquals((Integer)10, entry.getValue());
+        }
+    }
+
+    /**
+     *
+     */
+    static class TestKey {
+        /** */
+        private int key;
+
+        /**
+         * @param key Key.
+         */
+        public TestKey(int key) {
+            this.key = key;
+        }
+
+        /** {@inheritDoc} */
+        @Override public boolean equals(Object o) {
+            if (this == o)
+                return true;
+
+            if (o == null || getClass() != o.getClass())
+                return false;
+
+            TestKey testKey = (TestKey)o;
+
+            return key == testKey.key;
+
+        }
+
+        /** {@inheritDoc} */
+        @Override public int hashCode() {
+            return key;
+        }
+    }
+
+    /**
+     *
+     */
+    static class TestValue {
+        /** */
+        private int val;
+
+        /**
+         * @param val Value.
+         */
+        public TestValue(int val) {
+            this.val = val;
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/54e432e9/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteBinaryCacheTestSuite.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteBinaryCacheTestSuite.java b/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteBinaryCacheTestSuite.java
index 69ca67e..2668598 100644
--- a/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteBinaryCacheTestSuite.java
+++ b/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteBinaryCacheTestSuite.java
@@ -27,6 +27,7 @@ import org.apache.ignite.internal.processors.cache.GridCacheOffHeapTieredAtomicS
 import org.apache.ignite.internal.processors.cache.GridCacheOffHeapTieredEvictionAtomicSelfTest;
 import org.apache.ignite.internal.processors.cache.GridCacheOffHeapTieredEvictionSelfTest;
 import org.apache.ignite.internal.processors.cache.GridCacheOffHeapTieredSelfTest;
+import org.apache.ignite.internal.processors.cache.binary.CacheKeepBinaryWithInterceptorTest;
 import org.apache.ignite.internal.processors.cache.expiry.IgniteCacheAtomicLocalExpiryPolicyTest;
 import org.apache.ignite.internal.processors.cache.binary.GridBinaryCacheEntryMemorySizeSelfTest;
 import org.apache.ignite.internal.processors.cache.binary.datastreaming.DataStreamProcessorBinarySelfTest;
@@ -97,6 +98,7 @@ public class IgniteBinaryCacheTestSuite extends TestSuite {
 
         suite.addTestSuite(GridCacheAffinityRoutingBinarySelfTest.class);
         suite.addTestSuite(GridBinaryCacheEntryMemorySizeSelfTest.class);
+        suite.addTestSuite(CacheKeepBinaryWithInterceptorTest.class);
 
         return suite;
     }


[10/17] ignite git commit: IGNITE-2865 Continuous query event passed to filter should be immutable for users. This closes #744. (cherry picked from commit 046657b)

Posted by dm...@apache.org.
IGNITE-2865 Continuous query event passed to filter should be immutable for users. This closes #744.
(cherry picked from commit 046657b)


Project: http://git-wip-us.apache.org/repos/asf/ignite/repo
Commit: http://git-wip-us.apache.org/repos/asf/ignite/commit/e1ec0ded
Tree: http://git-wip-us.apache.org/repos/asf/ignite/tree/e1ec0ded
Diff: http://git-wip-us.apache.org/repos/asf/ignite/diff/e1ec0ded

Branch: refs/heads/master
Commit: e1ec0dedab0221b53dd11f2854c8c88b2641d147
Parents: c8269da
Author: sboikov <sb...@gridgain.com>
Authored: Tue May 24 14:31:43 2016 +0300
Committer: tledkov-gridgain <tl...@gridgain.com>
Committed: Tue May 24 14:50:46 2016 +0300

----------------------------------------------------------------------
 .../ignite/codegen/MessageCodeGenerator.java    | 133 ++++++------
 .../ignite/internal/GridCodegenConverter.java   |  56 +++++
 .../continuous/CacheContinuousQueryEntry.java   |  24 ++-
 ...eCacheContinuousQueryImmutableEntryTest.java | 205 +++++++++++++++++++
 .../IgniteCacheQuerySelfTestSuite3.java         |   2 +
 5 files changed, 351 insertions(+), 69 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/e1ec0ded/modules/codegen/src/main/java/org/apache/ignite/codegen/MessageCodeGenerator.java
----------------------------------------------------------------------
diff --git a/modules/codegen/src/main/java/org/apache/ignite/codegen/MessageCodeGenerator.java b/modules/codegen/src/main/java/org/apache/ignite/codegen/MessageCodeGenerator.java
index 587ad06..a6ae0da 100644
--- a/modules/codegen/src/main/java/org/apache/ignite/codegen/MessageCodeGenerator.java
+++ b/modules/codegen/src/main/java/org/apache/ignite/codegen/MessageCodeGenerator.java
@@ -39,6 +39,7 @@ import java.util.Map;
 import java.util.Set;
 import java.util.TreeSet;
 import java.util.UUID;
+import org.apache.ignite.internal.GridCodegenConverter;
 import org.apache.ignite.internal.GridDirectCollection;
 import org.apache.ignite.internal.GridDirectMap;
 import org.apache.ignite.internal.GridDirectTransient;
@@ -544,8 +545,14 @@ public class MessageCodeGenerator {
 
         indent++;
 
-        returnFalseIfWriteFailed(field.getType(), field.getName(), colAnn != null ? colAnn.value() : null,
-            mapAnn != null ? mapAnn.keyType() : null, mapAnn != null ? mapAnn.valueType() : null, false);
+        GridCodegenConverter fldPreproc = field.getAnnotation(GridCodegenConverter.class);
+
+        String getExp = (fldPreproc != null && !fldPreproc.get().isEmpty())? fldPreproc.get(): field.getName();
+        Class<?> writeType = (fldPreproc != null && !fldPreproc.type().equals(GridCodegenConverter.Default.class))?
+            fldPreproc.type(): field.getType();
+
+        returnFalseIfWriteFailed(writeType, field.getName(), colAnn != null ? colAnn.value() : null,
+            mapAnn != null ? mapAnn.keyType() : null, mapAnn != null ? mapAnn.valueType() : null, false, getExp);
 
         write.add(EMPTY);
         write.add(builder().a("writer.incrementState();").toString());
@@ -569,8 +576,13 @@ public class MessageCodeGenerator {
 
         indent++;
 
-        returnFalseIfReadFailed(field.getType(), field.getName(), colAnn != null ? colAnn.value() : null,
-            mapAnn != null ? mapAnn.keyType() : null, mapAnn != null ? mapAnn.valueType() : null);
+        GridCodegenConverter fldPreproc = field.getAnnotation(GridCodegenConverter.class);
+        String setExp = (fldPreproc != null && !fldPreproc.get().isEmpty())? fldPreproc.set(): "";
+        Class<?> writeType = (fldPreproc != null && !fldPreproc.type().equals(GridCodegenConverter.Default.class))?
+            fldPreproc.type(): field.getType();
+
+        returnFalseIfReadFailed(writeType, field.getName(), colAnn != null ? colAnn.value() : null,
+            mapAnn != null ? mapAnn.keyType() : null, mapAnn != null ? mapAnn.valueType() : null, setExp);
 
         read.add(EMPTY);
         read.add(builder().a("reader.incrementState();").toString());
@@ -588,74 +600,74 @@ public class MessageCodeGenerator {
      * @param raw Raw write flag.
      */
     private void returnFalseIfWriteFailed(Class<?> type, String name, @Nullable Class<?> colItemType,
-        @Nullable Class<?> mapKeyType, @Nullable Class<?> mapValType, boolean raw) {
+        @Nullable Class<?> mapKeyType, @Nullable Class<?> mapValType, boolean raw, String getExpr) {
         assert type != null;
         assert name != null;
 
         String field = raw ? "null" : '"' + name + '"';
 
         if (type == byte.class)
-            returnFalseIfFailed(write, "writer.writeByte", field, name);
+            returnFalseIfFailed(write, "writer.writeByte", field, getExpr);
         else if (type == short.class)
-            returnFalseIfFailed(write, "writer.writeShort", field, name);
+            returnFalseIfFailed(write, "writer.writeShort", field, getExpr);
         else if (type == int.class)
-            returnFalseIfFailed(write, "writer.writeInt", field, name);
+            returnFalseIfFailed(write, "writer.writeInt", field, getExpr);
         else if (type == long.class)
-            returnFalseIfFailed(write, "writer.writeLong", field, name);
+            returnFalseIfFailed(write, "writer.writeLong", field, getExpr);
         else if (type == float.class)
-            returnFalseIfFailed(write, "writer.writeFloat", field, name);
+            returnFalseIfFailed(write, "writer.writeFloat", field, getExpr);
         else if (type == double.class)
-            returnFalseIfFailed(write, "writer.writeDouble", field, name);
+            returnFalseIfFailed(write, "writer.writeDouble", field, getExpr);
         else if (type == char.class)
-            returnFalseIfFailed(write, "writer.writeChar", field, name);
+            returnFalseIfFailed(write, "writer.writeChar", field, getExpr);
         else if (type == boolean.class)
-            returnFalseIfFailed(write, "writer.writeBoolean", field, name);
+            returnFalseIfFailed(write, "writer.writeBoolean", field, getExpr);
         else if (type == byte[].class)
-            returnFalseIfFailed(write, "writer.writeByteArray", field, name);
+            returnFalseIfFailed(write, "writer.writeByteArray", field, getExpr);
         else if (type == short[].class)
-            returnFalseIfFailed(write, "writer.writeShortArray", field, name);
+            returnFalseIfFailed(write, "writer.writeShortArray", field, getExpr);
         else if (type == int[].class)
-            returnFalseIfFailed(write, "writer.writeIntArray", field, name);
+            returnFalseIfFailed(write, "writer.writeIntArray", field, getExpr);
         else if (type == long[].class)
-            returnFalseIfFailed(write, "writer.writeLongArray", field, name);
+            returnFalseIfFailed(write, "writer.writeLongArray", field, getExpr);
         else if (type == float[].class)
-            returnFalseIfFailed(write, "writer.writeFloatArray", field, name);
+            returnFalseIfFailed(write, "writer.writeFloatArray", field, getExpr);
         else if (type == double[].class)
-            returnFalseIfFailed(write, "writer.writeDoubleArray", field, name);
+            returnFalseIfFailed(write, "writer.writeDoubleArray", field, getExpr);
         else if (type == char[].class)
-            returnFalseIfFailed(write, "writer.writeCharArray", field, name);
+            returnFalseIfFailed(write, "writer.writeCharArray", field, getExpr);
         else if (type == boolean[].class)
-            returnFalseIfFailed(write, "writer.writeBooleanArray", field, name);
+            returnFalseIfFailed(write, "writer.writeBooleanArray", field, getExpr);
         else if (type == String.class)
-            returnFalseIfFailed(write, "writer.writeString", field, name);
+            returnFalseIfFailed(write, "writer.writeString", field, getExpr);
         else if (type == BitSet.class)
-            returnFalseIfFailed(write, "writer.writeBitSet", field, name);
+            returnFalseIfFailed(write, "writer.writeBitSet", field, getExpr);
         else if (type == UUID.class)
-            returnFalseIfFailed(write, "writer.writeUuid", field, name);
+            returnFalseIfFailed(write, "writer.writeUuid", field, getExpr);
         else if (type == IgniteUuid.class)
-            returnFalseIfFailed(write, "writer.writeIgniteUuid", field, name);
+            returnFalseIfFailed(write, "writer.writeIgniteUuid", field, getExpr);
         else if (type.isEnum()) {
-            String arg = name + " != null ? (byte)" + name + ".ordinal() : -1";
+            String arg = getExpr + " != null ? (byte)" + getExpr + ".ordinal() : -1";
 
             returnFalseIfFailed(write, "writer.writeByte", field, arg);
         }
         else if (BASE_CLS.isAssignableFrom(type))
-            returnFalseIfFailed(write, "writer.writeMessage", field, name);
+            returnFalseIfFailed(write, "writer.writeMessage", field, getExpr);
         else if (type.isArray()) {
-            returnFalseIfFailed(write, "writer.writeObjectArray", field, name,
+            returnFalseIfFailed(write, "writer.writeObjectArray", field, getExpr,
                 "MessageCollectionItemType." + typeEnum(type.getComponentType()));
         }
         else if (Collection.class.isAssignableFrom(type) && !Set.class.isAssignableFrom(type)) {
             assert colItemType != null;
 
-            returnFalseIfFailed(write, "writer.writeCollection", field, name,
+            returnFalseIfFailed(write, "writer.writeCollection", field, getExpr,
                 "MessageCollectionItemType." + typeEnum(colItemType));
         }
         else if (Map.class.isAssignableFrom(type)) {
             assert mapKeyType != null;
             assert mapValType != null;
 
-            returnFalseIfFailed(write, "writer.writeMap", field, name,
+            returnFalseIfFailed(write, "writer.writeMap", field, getExpr,
                 "MessageCollectionItemType." + typeEnum(mapKeyType),
                 "MessageCollectionItemType." + typeEnum(mapValType));
         }
@@ -671,75 +683,75 @@ public class MessageCodeGenerator {
      * @param mapValType Map value type.
      */
     private void returnFalseIfReadFailed(Class<?> type, @Nullable String name, @Nullable Class<?> colItemType,
-        @Nullable Class<?> mapKeyType, @Nullable Class<?> mapValType) {
+        @Nullable Class<?> mapKeyType, @Nullable Class<?> mapValType, String setExpr) {
         assert type != null;
 
         String field = '"' + name + '"';
 
         if (type == byte.class)
-            returnFalseIfReadFailed(name, "reader.readByte", field);
+            returnFalseIfReadFailed(name, "reader.readByte", setExpr, field);
         else if (type == short.class)
-            returnFalseIfReadFailed(name, "reader.readShort", field);
+            returnFalseIfReadFailed(name, "reader.readShort", setExpr, field);
         else if (type == int.class)
-            returnFalseIfReadFailed(name, "reader.readInt", field);
+            returnFalseIfReadFailed(name, "reader.readInt", setExpr, field);
         else if (type == long.class)
-            returnFalseIfReadFailed(name, "reader.readLong", field);
+            returnFalseIfReadFailed(name, "reader.readLong", setExpr, field);
         else if (type == float.class)
-            returnFalseIfReadFailed(name, "reader.readFloat", field);
+            returnFalseIfReadFailed(name, "reader.readFloat", setExpr, field);
         else if (type == double.class)
-            returnFalseIfReadFailed(name, "reader.readDouble", field);
+            returnFalseIfReadFailed(name, "reader.readDouble", setExpr, field);
         else if (type == char.class)
-            returnFalseIfReadFailed(name, "reader.readChar", field);
+            returnFalseIfReadFailed(name, "reader.readChar", setExpr, field);
         else if (type == boolean.class)
-            returnFalseIfReadFailed(name, "reader.readBoolean", field);
+            returnFalseIfReadFailed(name, "reader.readBoolean", setExpr, field);
         else if (type == byte[].class)
-            returnFalseIfReadFailed(name, "reader.readByteArray", field);
+            returnFalseIfReadFailed(name, "reader.readByteArray", setExpr, field);
         else if (type == short[].class)
-            returnFalseIfReadFailed(name, "reader.readShortArray", field);
+            returnFalseIfReadFailed(name, "reader.readShortArray", setExpr, field);
         else if (type == int[].class)
-            returnFalseIfReadFailed(name, "reader.readIntArray", field);
+            returnFalseIfReadFailed(name, "reader.readIntArray", setExpr, field);
         else if (type == long[].class)
-            returnFalseIfReadFailed(name, "reader.readLongArray", field);
+            returnFalseIfReadFailed(name, "reader.readLongArray", setExpr, field);
         else if (type == float[].class)
-            returnFalseIfReadFailed(name, "reader.readFloatArray", field);
+            returnFalseIfReadFailed(name, "reader.readFloatArray", setExpr, field);
         else if (type == double[].class)
-            returnFalseIfReadFailed(name, "reader.readDoubleArray", field);
+            returnFalseIfReadFailed(name, "reader.readDoubleArray", setExpr, field);
         else if (type == char[].class)
-            returnFalseIfReadFailed(name, "reader.readCharArray", field);
+            returnFalseIfReadFailed(name, "reader.readCharArray", setExpr, field);
         else if (type == boolean[].class)
-            returnFalseIfReadFailed(name, "reader.readBooleanArray", field);
+            returnFalseIfReadFailed(name, "reader.readBooleanArray", setExpr, field);
         else if (type == String.class)
-            returnFalseIfReadFailed(name, "reader.readString", field);
+            returnFalseIfReadFailed(name, "reader.readString", setExpr, field);
         else if (type == BitSet.class)
-            returnFalseIfReadFailed(name, "reader.readBitSet", field);
+            returnFalseIfReadFailed(name, "reader.readBitSet", setExpr, field);
         else if (type == UUID.class)
-            returnFalseIfReadFailed(name, "reader.readUuid", field);
+            returnFalseIfReadFailed(name, "reader.readUuid", setExpr, field);
         else if (type == IgniteUuid.class)
-            returnFalseIfReadFailed(name, "reader.readIgniteUuid", field);
+            returnFalseIfReadFailed(name, "reader.readIgniteUuid", setExpr, field);
         else if (type.isEnum()) {
             String loc = name + "Ord";
 
             read.add(builder().a("byte ").a(loc).a(";").toString());
             read.add(EMPTY);
 
-            returnFalseIfReadFailed(loc, "reader.readByte", field);
+            returnFalseIfReadFailed(loc, "reader.readByte", setExpr, field);
 
             read.add(EMPTY);
             read.add(builder().a(name).a(" = ").a(type.getSimpleName()).a(".fromOrdinal(").a(loc).a(");").toString());
         }
         else if (BASE_CLS.isAssignableFrom(type))
-            returnFalseIfReadFailed(name, "reader.readMessage", field);
+            returnFalseIfReadFailed(name, "reader.readMessage", setExpr, field);
         else if (type.isArray()) {
             Class<?> compType = type.getComponentType();
 
-            returnFalseIfReadFailed(name, "reader.readObjectArray", field,
+            returnFalseIfReadFailed(name, "reader.readObjectArray", field, setExpr,
                 "MessageCollectionItemType." + typeEnum(compType),
                 compType.getSimpleName() + ".class");
         }
         else if (Collection.class.isAssignableFrom(type) && !Set.class.isAssignableFrom(type)) {
             assert colItemType != null;
 
-            returnFalseIfReadFailed(name, "reader.readCollection", field,
+            returnFalseIfReadFailed(name, "reader.readCollection", field, setExpr,
                 "MessageCollectionItemType." + typeEnum(colItemType));
         }
         else if (Map.class.isAssignableFrom(type)) {
@@ -748,7 +760,7 @@ public class MessageCodeGenerator {
 
             boolean linked = type.equals(LinkedHashMap.class);
 
-            returnFalseIfReadFailed(name, "reader.readMap", field,
+            returnFalseIfReadFailed(name, "reader.readMap", field, setExpr,
                 "MessageCollectionItemType." + typeEnum(mapKeyType),
                 "MessageCollectionItemType." + typeEnum(mapValType),
                 linked ? "true" : "false");
@@ -762,7 +774,7 @@ public class MessageCodeGenerator {
      * @param mtd Method name.
      * @param args Method arguments.
      */
-    private void returnFalseIfReadFailed(String var, String mtd, @Nullable String... args) {
+    private void returnFalseIfReadFailed(String var, String mtd, String setConverter, @Nullable String... args) {
         assert mtd != null;
 
         String argsStr = "";
@@ -774,7 +786,12 @@ public class MessageCodeGenerator {
             argsStr = argsStr.substring(0, argsStr.length() - 2);
         }
 
-        read.add(builder().a(var).a(" = ").a(mtd).a("(").a(argsStr).a(");").toString());
+        if (setConverter.isEmpty())
+            read.add(builder().a(var).a(" = ").a(mtd).a("(").a(argsStr).a(");").toString());
+        else {
+            read.add(builder().a(var).a(" = ").a(setConverter
+                .replace("$val$", new SB().a(mtd).a("(").a(argsStr).a(")").toString())).a(";").toString());
+        }
         read.add(EMPTY);
 
         read.add(builder().a("if (!reader.isLastRead())").toString());

http://git-wip-us.apache.org/repos/asf/ignite/blob/e1ec0ded/modules/core/src/main/java/org/apache/ignite/internal/GridCodegenConverter.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/GridCodegenConverter.java b/modules/core/src/main/java/org/apache/ignite/internal/GridCodegenConverter.java
new file mode 100644
index 0000000..7baccda
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/GridCodegenConverter.java
@@ -0,0 +1,56 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ignite.internal;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * Annotates fields that required custom reading / writing.
+ */
+@Retention(RetentionPolicy.RUNTIME)
+@Target(ElementType.FIELD)
+public @interface GridCodegenConverter {
+    /**
+     * Converter code. Replace original field value by converted.
+     *
+     * @return Code to get field value.
+     */
+    String get() default "";
+
+    /**
+     * Converter code. A raw read value is available at $val$ placeholder
+     *
+     * @return Code to set field value.
+     */
+    String set() default "";
+
+    /**
+     * @return Result type. Use this type to read / write the converted value.
+     */
+    Class<?> type() default Default.class;
+
+    /**
+     * Used as the default value for converter type
+     */
+    class Default {
+        // No-op.
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ignite/blob/e1ec0ded/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/continuous/CacheContinuousQueryEntry.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/continuous/CacheContinuousQueryEntry.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/continuous/CacheContinuousQueryEntry.java
index d105271..63dc4cb 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/continuous/CacheContinuousQueryEntry.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/continuous/CacheContinuousQueryEntry.java
@@ -20,6 +20,7 @@ package org.apache.ignite.internal.processors.cache.query.continuous;
 import java.nio.ByteBuffer;
 import javax.cache.event.EventType;
 import org.apache.ignite.IgniteCheckedException;
+import org.apache.ignite.internal.GridCodegenConverter;
 import org.apache.ignite.internal.GridDirectTransient;
 import org.apache.ignite.internal.managers.deployment.GridDeploymentInfo;
 import org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion;
@@ -61,18 +62,26 @@ public class CacheContinuousQueryEntry implements GridCacheDeployable, Message {
     }
 
     /** */
+    @GridCodegenConverter(
+        type = byte.class,
+        get = "evtType != null ? (byte)evtType.ordinal() : -1",
+        set = "eventTypeFromOrdinal($val$)"
+    )
     private EventType evtType;
 
     /** Key. */
     @GridToStringInclude
+    @GridCodegenConverter(get = "isFiltered() ? null : key")
     private KeyCacheObject key;
 
     /** New value. */
     @GridToStringInclude
+    @GridCodegenConverter(get = "isFiltered() ? null : newVal")
     private CacheObject newVal;
 
     /** Old value. */
     @GridToStringInclude
+    @GridCodegenConverter(get = "isFiltered() ? null : oldVal")
     private CacheObject oldVal;
 
     /** Cache name. */
@@ -187,9 +196,6 @@ public class CacheContinuousQueryEntry implements GridCacheDeployable, Message {
      */
     void markFiltered() {
         flags |= FILTERED_ENTRY;
-        newVal = null;
-        oldVal = null;
-        key = null;
         depInfo = null;
     }
 
@@ -345,19 +351,19 @@ public class CacheContinuousQueryEntry implements GridCacheDeployable, Message {
                 writer.incrementState();
 
             case 5:
-                if (!writer.writeMessage("key", key))
+                if (!writer.writeMessage("key", isFiltered() ? null : key))
                     return false;
 
                 writer.incrementState();
 
             case 6:
-                if (!writer.writeMessage("newVal", newVal))
+                if (!writer.writeMessage("newVal", isFiltered() ? null : newVal))
                     return false;
 
                 writer.incrementState();
 
             case 7:
-                if (!writer.writeMessage("oldVal", oldVal))
+                if (!writer.writeMessage("oldVal", isFiltered() ? null : oldVal))
                     return false;
 
                 writer.incrementState();
@@ -402,15 +408,11 @@ public class CacheContinuousQueryEntry implements GridCacheDeployable, Message {
                 reader.incrementState();
 
             case 1:
-                byte evtTypeOrd;
-
-                evtTypeOrd = reader.readByte("evtType");
+                evtType = eventTypeFromOrdinal(reader.readByte("evtType"));
 
                 if (!reader.isLastRead())
                     return false;
 
-                evtType = eventTypeFromOrdinal(evtTypeOrd);
-
                 reader.incrementState();
 
             case 2:

http://git-wip-us.apache.org/repos/asf/ignite/blob/e1ec0ded/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/query/continuous/IgniteCacheContinuousQueryImmutableEntryTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/query/continuous/IgniteCacheContinuousQueryImmutableEntryTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/query/continuous/IgniteCacheContinuousQueryImmutableEntryTest.java
new file mode 100644
index 0000000..66d727c
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/query/continuous/IgniteCacheContinuousQueryImmutableEntryTest.java
@@ -0,0 +1,205 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ignite.internal.processors.cache.query.continuous;
+
+import java.io.Serializable;
+import java.nio.ByteBuffer;
+import java.util.concurrent.ConcurrentLinkedQueue;
+import javax.cache.configuration.Factory;
+import javax.cache.event.CacheEntryEvent;
+import javax.cache.event.CacheEntryEventFilter;
+import javax.cache.event.CacheEntryUpdatedListener;
+import javax.cache.event.EventType;
+import org.apache.ignite.cache.query.ContinuousQuery;
+import org.apache.ignite.cache.query.QueryCursor;
+import org.apache.ignite.configuration.CacheConfiguration;
+import org.apache.ignite.configuration.IgniteConfiguration;
+import org.apache.ignite.internal.direct.DirectMessageReader;
+import org.apache.ignite.internal.direct.DirectMessageWriter;
+import org.apache.ignite.internal.managers.communication.GridIoMessageFactory;
+import org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion;
+import org.apache.ignite.internal.processors.cache.CacheObjectImpl;
+import org.apache.ignite.internal.processors.cache.KeyCacheObjectImpl;
+import org.apache.ignite.internal.util.GridLongList;
+import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi;
+import org.apache.ignite.spi.discovery.tcp.ipfinder.TcpDiscoveryIpFinder;
+import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder;
+import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
+
+import static org.apache.ignite.cache.CacheAtomicityMode.ATOMIC;
+import static org.apache.ignite.cache.CacheMode.PARTITIONED;
+import static org.apache.ignite.cache.CacheWriteSynchronizationMode.FULL_SYNC;
+
+/**
+ *
+ */
+public class IgniteCacheContinuousQueryImmutableEntryTest extends GridCommonAbstractTest {
+    /** */
+    private static final TcpDiscoveryIpFinder ipFinder = new TcpDiscoveryVmIpFinder(true);
+
+    /** Keys count. */
+    private static final int KEYS_COUNT = 10;
+
+    /** Grid count. */
+    private static final int GRID_COUNT = 3;
+
+    /** Events. */
+    private static final ConcurrentLinkedQueue<CacheEntryEvent<?, ?>> events = new ConcurrentLinkedQueue<>();
+
+    /** {@inheritDoc} */
+    @Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception {
+        IgniteConfiguration cfg = super.getConfiguration(gridName);
+
+        CacheConfiguration ccfg = new CacheConfiguration();
+        ccfg.setCacheMode(PARTITIONED);
+        ccfg.setAtomicityMode(ATOMIC);
+        ccfg.setWriteSynchronizationMode(FULL_SYNC);
+
+        cfg.setCacheConfiguration(ccfg);
+
+        ((TcpDiscoverySpi)cfg.getDiscoverySpi()).setIpFinder(ipFinder);
+
+        return cfg;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void afterTest() throws Exception {
+        super.afterTest();
+
+        stopAllGrids();
+
+        events.clear();
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testEventAvailabilityScope() throws Exception {
+        startGrids(GRID_COUNT);
+
+        final CacheEventListener lsnr = new CacheEventListener();
+
+        ContinuousQuery<Object, Object> qry = new ContinuousQuery<>();
+        qry.setLocalListener(lsnr);
+        qry.setRemoteFilterFactory(new FilterFactory());
+
+        Object keys[] = new Object[GRID_COUNT];
+
+        // Add initial values.
+        for (int i = 0; i < GRID_COUNT; ++i) {
+            keys[i] = primaryKey(grid(i).cache(null));
+
+            grid(0).cache(null).put(keys[i], -1);
+        }
+
+        try (QueryCursor<?> cur = grid(0).cache(null).query(qry)) {
+            // Replace values on the keys.
+            for (int i = 0; i < KEYS_COUNT; i++) {
+                log.info("Put key: " + i);
+
+                grid(i % GRID_COUNT).cache(null).put(keys[i % GRID_COUNT], i);
+            }
+        }
+
+        assertTrue("There are not filtered events", !events.isEmpty());
+
+        for (CacheEntryEvent<?, ?> event : events) {
+            assertNotNull("Key is null", event.getKey());
+            assertNotNull("Value is null", event.getValue());
+            assertNotNull("Old value is null", event.getOldValue());
+        }
+    }
+
+    /**
+     *
+     */
+    public void testCacheContinuousQueryEntrySerialization() {
+        CacheContinuousQueryEntry e0 = new CacheContinuousQueryEntry(
+            1,
+            EventType.UPDATED,
+            new KeyCacheObjectImpl(1, new byte[] {0, 0, 0, 1}),
+            new CacheObjectImpl(2, new byte[] {0, 0, 0, 2}),
+            new CacheObjectImpl(2, new byte[] {0, 0, 0, 3}),
+            true,
+            1,
+            1L,
+            new AffinityTopologyVersion(1L));
+
+        e0.filteredEvents(new GridLongList(new long[]{1L, 2L}));
+        e0.markFiltered();
+
+        ByteBuffer buf = ByteBuffer.allocate(4096);
+        DirectMessageWriter writer = new DirectMessageWriter((byte)1);
+
+        // Skip write class header.
+        writer.onHeaderWritten();
+        e0.writeTo(buf, writer);
+
+        CacheContinuousQueryEntry e1 = new CacheContinuousQueryEntry();
+        e1.readFrom(ByteBuffer.wrap(buf.array()), new DirectMessageReader(new GridIoMessageFactory(null), (byte)1));
+
+        assertEquals(e0.cacheId(), e1.cacheId());
+        assertEquals(e0.eventType(), e1.eventType());
+        assertEquals(e0.isFiltered(), e1.isFiltered());
+        assertEquals(GridLongList.asList(e0.filteredEvents()), GridLongList.asList(e1.filteredEvents()));
+        assertEquals(e0.isBackup(), e1.isBackup());
+        assertEquals(e0.isKeepBinary(), e1.isKeepBinary());
+        assertEquals(e0.partition(), e1.partition());
+        assertEquals(e0.updateCounter(), e1.updateCounter());
+
+        // Key and value shouldn't be serialized in case an event is filtered.
+        assertNull(e1.key());
+        assertNotNull(e0.key());
+        assertNull(e1.oldValue());
+        assertNotNull(e0.oldValue());
+        assertNull(e1.value());
+        assertNotNull(e0.value());
+    }
+
+    /**
+     *
+     */
+    private static class FilterFactory implements Factory<CacheEntryEventFilter<Object, Object>> {
+        /** {@inheritDoc} */
+        @Override public CacheEntryEventFilter<Object, Object> create() {
+            return new CacheEventFilter();
+        }
+    }
+
+    /**
+     *
+     */
+    private static class CacheEventFilter implements CacheEntryEventFilter<Object, Object>, Serializable {
+        /** {@inheritDoc} */
+         @Override public boolean evaluate(CacheEntryEvent<?, ?> evt) {
+            events.add(evt);
+
+            return false;
+        }
+    }
+
+    /**
+     *
+     */
+    private static class CacheEventListener implements CacheEntryUpdatedListener<Object, Object> {
+        /** {@inheritDoc} */
+        @Override public void onUpdated(Iterable<CacheEntryEvent<?, ?>> evts) {
+            // No-op
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ignite/blob/e1ec0ded/modules/indexing/src/test/java/org/apache/ignite/testsuites/IgniteCacheQuerySelfTestSuite3.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/test/java/org/apache/ignite/testsuites/IgniteCacheQuerySelfTestSuite3.java b/modules/indexing/src/test/java/org/apache/ignite/testsuites/IgniteCacheQuerySelfTestSuite3.java
index e0e81b7..dbbb3ed 100644
--- a/modules/indexing/src/test/java/org/apache/ignite/testsuites/IgniteCacheQuerySelfTestSuite3.java
+++ b/modules/indexing/src/test/java/org/apache/ignite/testsuites/IgniteCacheQuerySelfTestSuite3.java
@@ -54,6 +54,7 @@ import org.apache.ignite.internal.processors.cache.query.continuous.GridCacheCon
 import org.apache.ignite.internal.processors.cache.query.continuous.IgniteCacheContinuousQueryClientReconnectTest;
 import org.apache.ignite.internal.processors.cache.query.continuous.IgniteCacheContinuousQueryClientTest;
 import org.apache.ignite.internal.processors.cache.query.continuous.IgniteCacheContinuousQueryClientTxReconnectTest;
+import org.apache.ignite.internal.processors.cache.query.continuous.IgniteCacheContinuousQueryImmutableEntryTest;
 
 /**
  * Test suite for cache queries.
@@ -103,6 +104,7 @@ public class IgniteCacheQuerySelfTestSuite3 extends TestSuite {
         suite.addTestSuite(CacheContinuousBatchForceServerModeAckTest.class);
         suite.addTestSuite(CacheContinuousQueryExecuteInPrimaryTest.class);
         suite.addTestSuite(CacheContinuousQueryLostPartitionTest.class);
+        suite.addTestSuite(IgniteCacheContinuousQueryImmutableEntryTest.class);
 
         return suite;
     }


[13/17] ignite git commit: ignite-2620 Skip empty entries in GridCacheMapEntry.onTtlExpired (cherry picked from commit 6fc274a)

Posted by dm...@apache.org.
ignite-2620 Skip empty entries in GridCacheMapEntry.onTtlExpired
(cherry picked from commit 6fc274a)


Project: http://git-wip-us.apache.org/repos/asf/ignite/repo
Commit: http://git-wip-us.apache.org/repos/asf/ignite/commit/30aa287b
Tree: http://git-wip-us.apache.org/repos/asf/ignite/tree/30aa287b
Diff: http://git-wip-us.apache.org/repos/asf/ignite/diff/30aa287b

Branch: refs/heads/master
Commit: 30aa287b881d4f9dc3fd5eec9840eab8d9a20828
Parents: 183620c
Author: sboikov <sb...@gridgain.com>
Authored: Tue May 24 16:57:20 2016 +0300
Committer: sboikov <sb...@gridgain.com>
Committed: Wed May 25 10:24:44 2016 +0300

----------------------------------------------------------------------
 .../ignite/internal/processors/cache/GridCacheMapEntry.java       | 3 +++
 1 file changed, 3 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/30aa287b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheMapEntry.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheMapEntry.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheMapEntry.java
index de69f53..288d964 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheMapEntry.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheMapEntry.java
@@ -3670,6 +3670,9 @@ public abstract class GridCacheMapEntry extends GridMetadataAwareAdapter impleme
 
                 CacheObject expiredVal = rawGetOrUnmarshal(false);
 
+                if (expiredVal == null)
+                    return false;
+
                 if (onExpired(expiredVal, obsoleteVer)) {
                     if (cctx.deferredDelete()) {
                         deferred = true;


[12/17] ignite git commit: IGNITE-3168 Added idle timeout property.

Posted by dm...@apache.org.
IGNITE-3168 Added idle timeout property.


Project: http://git-wip-us.apache.org/repos/asf/ignite/repo
Commit: http://git-wip-us.apache.org/repos/asf/ignite/commit/183620cd
Tree: http://git-wip-us.apache.org/repos/asf/ignite/tree/183620cd
Diff: http://git-wip-us.apache.org/repos/asf/ignite/diff/183620cd

Branch: refs/heads/master
Commit: 183620cd31095dcd92471927cccf8741e3b63ed7
Parents: 727afc8
Author: nikolay_tikhonov <nt...@gridgain.com>
Authored: Wed May 25 09:47:14 2016 +0300
Committer: nikolay_tikhonov <nt...@gridgain.com>
Committed: Wed May 25 09:51:08 2016 +0300

----------------------------------------------------------------------
 .../apache/ignite/mesos/ClusterProperties.java  | 39 ++++++++++++++++++++
 .../apache/ignite/mesos/IgniteFramework.java    | 10 ++---
 .../ignite/mesos/resource/JettyServer.java      | 16 ++++++--
 3 files changed, 55 insertions(+), 10 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/183620cd/modules/mesos/src/main/java/org/apache/ignite/mesos/ClusterProperties.java
----------------------------------------------------------------------
diff --git a/modules/mesos/src/main/java/org/apache/ignite/mesos/ClusterProperties.java b/modules/mesos/src/main/java/org/apache/ignite/mesos/ClusterProperties.java
index 747fbe9..3c8f396 100644
--- a/modules/mesos/src/main/java/org/apache/ignite/mesos/ClusterProperties.java
+++ b/modules/mesos/src/main/java/org/apache/ignite/mesos/ClusterProperties.java
@@ -200,6 +200,15 @@ public class ClusterProperties {
     /** */
     public static final String IGNITE_CONFIG_XML_URL = "IGNITE_CONFIG_XML_URL";
 
+    /** */
+    public static final String IGNITE_HTTP_SERVER_IDLE_TIMEOUT = "IGNITE_HTTP_SERVER_IDLE_TIMEOUT";
+
+    /** */
+    public static final long IGNITE_HTTP_SERVER_IDLE_TIMEOUT_DEFAULT = 30000L;
+
+    /** Jetty idle timeout. */
+    private long idleTimeout = IGNITE_HTTP_SERVER_IDLE_TIMEOUT_DEFAULT;
+
     /** Url to ignite config. */
     private String igniteCfgUrl = null;
 
@@ -400,6 +409,17 @@ public class ClusterProperties {
     }
 
     /**
+     * Sets the maximum Idle time for a http connection, which will be used for
+     * jetty server. The server provides resources for ignite mesos framework such as
+     * ignite archive, user's libs, configurations and etc.
+     *
+     * @return Http server idle timeout.
+     */
+    public long idleTimeout() {
+        return idleTimeout;
+    }
+
+    /**
      * URL to ignite package. The URL should to point at valid apache ignite archive.
      * This property can be useful if using own apache ignite build.
      *
@@ -502,6 +522,8 @@ public class ClusterProperties {
 
             String ptrn = getStringProperty(IGNITE_HOSTNAME_CONSTRAINT, props, null);
 
+            prop.idleTimeout = getLongProperty(IGNITE_HTTP_SERVER_IDLE_TIMEOUT, props, IGNITE_HTTP_SERVER_IDLE_TIMEOUT_DEFAULT);
+
             if (ptrn != null) {
                 try {
                     prop.hostnameConstraint = Pattern.compile(ptrn);
@@ -540,6 +562,23 @@ public class ClusterProperties {
      * @param fileProps Property file.
      * @return Property value.
      */
+    private static long getLongProperty(String name, Properties fileProps, Long dfltVal) {
+        if (fileProps != null && fileProps.containsKey(name))
+            return Long.valueOf(fileProps.getProperty(name));
+
+        String prop = System.getProperty(name);
+
+        if (prop == null)
+            prop = System.getenv(name);
+
+        return prop == null ? dfltVal : Long.valueOf(prop);
+    }
+
+    /**
+     * @param name Property name.
+     * @param fileProps Property file.
+     * @return Property value.
+     */
     private static String getStringProperty(String name, Properties fileProps, String dfltVal) {
         if (fileProps != null && fileProps.containsKey(name))
             return fileProps.getProperty(name);

http://git-wip-us.apache.org/repos/asf/ignite/blob/183620cd/modules/mesos/src/main/java/org/apache/ignite/mesos/IgniteFramework.java
----------------------------------------------------------------------
diff --git a/modules/mesos/src/main/java/org/apache/ignite/mesos/IgniteFramework.java b/modules/mesos/src/main/java/org/apache/ignite/mesos/IgniteFramework.java
index 0cd9efb..6054302 100644
--- a/modules/mesos/src/main/java/org/apache/ignite/mesos/IgniteFramework.java
+++ b/modules/mesos/src/main/java/org/apache/ignite/mesos/IgniteFramework.java
@@ -18,8 +18,6 @@
 package org.apache.ignite.mesos;
 
 import com.google.protobuf.ByteString;
-import java.net.InetSocketAddress;
-import java.util.concurrent.TimeUnit;
 import java.util.logging.Level;
 import java.util.logging.Logger;
 import org.apache.ignite.mesos.resource.IgniteProvider;
@@ -35,10 +33,10 @@ import org.apache.mesos.Scheduler;
  */
 public class IgniteFramework {
     /** */
-    public static final Logger log = Logger.getLogger(IgniteFramework.class.getSimpleName());
+    private static final Logger log = Logger.getLogger(IgniteFramework.class.getSimpleName());
 
     /** Framework name. */
-    public static final String IGNITE_FRAMEWORK_NAME = "Ignite";
+    private static final String IGNITE_FRAMEWORK_NAME = "Ignite";
 
     /**
      * Main methods has only one optional parameter - path to properties files.
@@ -68,8 +66,8 @@ public class IgniteFramework {
         JettyServer httpSrv = new JettyServer();
 
         httpSrv.start(
-            new InetSocketAddress(clusterProps.httpServerHost(), clusterProps.httpServerPort()),
-            new ResourceHandler(clusterProps.userLibs(), clusterProps.igniteCfg(), clusterProps.igniteWorkDir())
+            new ResourceHandler(clusterProps.userLibs(), clusterProps.igniteCfg(), clusterProps.igniteWorkDir()),
+            clusterProps
         );
 
         ResourceProvider provider = new ResourceProvider();

http://git-wip-us.apache.org/repos/asf/ignite/blob/183620cd/modules/mesos/src/main/java/org/apache/ignite/mesos/resource/JettyServer.java
----------------------------------------------------------------------
diff --git a/modules/mesos/src/main/java/org/apache/ignite/mesos/resource/JettyServer.java b/modules/mesos/src/main/java/org/apache/ignite/mesos/resource/JettyServer.java
index 444c751..f1f5189 100644
--- a/modules/mesos/src/main/java/org/apache/ignite/mesos/resource/JettyServer.java
+++ b/modules/mesos/src/main/java/org/apache/ignite/mesos/resource/JettyServer.java
@@ -17,9 +17,10 @@
 
 package org.apache.ignite.mesos.resource;
 
-import java.net.InetSocketAddress;
+import org.apache.ignite.mesos.ClusterProperties;
 import org.eclipse.jetty.server.Handler;
 import org.eclipse.jetty.server.Server;
+import org.eclipse.jetty.server.ServerConnector;
 
 /**
  * Embedded jetty server.
@@ -31,14 +32,21 @@ public class JettyServer {
     /**
      * Starts jetty server.
      *
-     * @param address Inter socket address.
      * @param handler Handler.
+     * @param props Cluster properties.
      * @throws Exception If failed.
      */
-    public void start(InetSocketAddress address, Handler handler) throws Exception {
+    public void start(Handler handler, ClusterProperties props) throws Exception {
         if (server == null) {
-            server = new Server(address);
+            server = new Server();
 
+            ServerConnector connector = new ServerConnector(server);
+
+            connector.setHost(props.httpServerHost());
+            connector.setPort(props.httpServerPort());
+            connector.setIdleTimeout(props.idleTimeout());
+
+            server.addConnector(connector);
             server.setHandler(handler);
 
             server.start();


[15/17] ignite git commit: IGNITE-2538 - IgniteRDD count() and isEmpty() method use IgniteCache API

Posted by dm...@apache.org.
IGNITE-2538 - IgniteRDD count() and isEmpty() method use IgniteCache API


Project: http://git-wip-us.apache.org/repos/asf/ignite/repo
Commit: http://git-wip-us.apache.org/repos/asf/ignite/commit/6fcc7a41
Tree: http://git-wip-us.apache.org/repos/asf/ignite/tree/6fcc7a41
Diff: http://git-wip-us.apache.org/repos/asf/ignite/diff/6fcc7a41

Branch: refs/heads/master
Commit: 6fcc7a41d8676956983792717483318b85781479
Parents: e2db87b
Author: MaBiao <ma...@gmail.com>
Authored: Wed May 25 12:54:40 2016 +0300
Committer: Valentin Kulichenko <va...@gmail.com>
Committed: Wed May 25 12:56:38 2016 +0300

----------------------------------------------------------------------
 .../org/apache/ignite/spark/IgniteRDD.scala     | 20 +++++++++++++++
 .../org/apache/ignite/spark/IgniteRDDSpec.scala | 27 ++++++++++++++++++++
 2 files changed, 47 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/6fcc7a41/modules/spark/src/main/scala/org/apache/ignite/spark/IgniteRDD.scala
----------------------------------------------------------------------
diff --git a/modules/spark/src/main/scala/org/apache/ignite/spark/IgniteRDD.scala b/modules/spark/src/main/scala/org/apache/ignite/spark/IgniteRDD.scala
index 9112040..0d8e730 100644
--- a/modules/spark/src/main/scala/org/apache/ignite/spark/IgniteRDD.scala
+++ b/modules/spark/src/main/scala/org/apache/ignite/spark/IgniteRDD.scala
@@ -95,6 +95,26 @@ class IgniteRDD[K, V] (
     }
 
     /**
+     * Tells whether this IgniteRDD is empty or not.
+     *
+     * @return Whether this IgniteRDD is empty or not.
+     */
+    override def isEmpty(): Boolean = {
+        count() == 0
+    }
+
+    /**
+     * Gets number of tuples in this IgniteRDD.
+     *
+     * @return Number of tuples in this IgniteRDD.
+     */
+    override def count(): Long = {
+        val cache = ensureCache()
+
+        cache.size()
+    }
+
+    /**
      * Runs an object SQL on corresponding Ignite cache.
      *
      * @param typeName Type name to run SQL against.

http://git-wip-us.apache.org/repos/asf/ignite/blob/6fcc7a41/modules/spark/src/test/scala/org/apache/ignite/spark/IgniteRDDSpec.scala
----------------------------------------------------------------------
diff --git a/modules/spark/src/test/scala/org/apache/ignite/spark/IgniteRDDSpec.scala b/modules/spark/src/test/scala/org/apache/ignite/spark/IgniteRDDSpec.scala
index a25eaac..8e36275 100644
--- a/modules/spark/src/test/scala/org/apache/ignite/spark/IgniteRDDSpec.scala
+++ b/modules/spark/src/test/scala/org/apache/ignite/spark/IgniteRDDSpec.scala
@@ -192,6 +192,33 @@ class IgniteRDDSpec extends FunSpec with Matchers with BeforeAndAfterAll with Be
                 sc.stop()
             }
         }
+
+        it("should properly count RDD size") {
+            val sc = new SparkContext("local[*]", "test")
+
+            try {
+                val ic = new IgniteContext[Integer, WithObjectField](sc,
+                    () \u21d2 configuration("client", client = true))
+
+                val cache: IgniteRDD[Integer, WithObjectField] = ic.fromCache(PARTITIONED_CACHE_NAME)
+
+                assert(cache.count() == 0)
+                assert(cache.isEmpty())
+
+                cache.savePairs(sc.parallelize(0 until 1000, 2).map(i \u21d2 (i:java.lang.Integer, new WithObjectField(i, new Entity(i, "", i)))))
+
+                assert(cache.count() == 1000)
+                assert(!cache.isEmpty())
+
+                cache.clear()
+
+                assert(cache.count() == 0)
+                assert(cache.isEmpty())
+            }
+            finally {
+                sc.stop()
+            }
+        }
     }
 
     override protected def beforeEach() = {


[02/17] ignite git commit: Fixed IGNITE-3004 "Implement config variations test for ContinuousQueries"

Posted by dm...@apache.org.
Fixed IGNITE-3004 "Implement config variations test for ContinuousQueries"


Project: http://git-wip-us.apache.org/repos/asf/ignite/repo
Commit: http://git-wip-us.apache.org/repos/asf/ignite/commit/c9416ed9
Tree: http://git-wip-us.apache.org/repos/asf/ignite/tree/c9416ed9
Diff: http://git-wip-us.apache.org/repos/asf/ignite/diff/c9416ed9

Branch: refs/heads/master
Commit: c9416ed9b58bbb2287e896cc5860177939c4b3ed
Parents: b5f5941
Author: nikolay_tikhonov <nt...@gridgain.com>
Authored: Fri May 20 12:54:55 2016 +0300
Committer: nikolay_tikhonov <nt...@gridgain.com>
Committed: Fri May 20 12:54:55 2016 +0300

----------------------------------------------------------------------
 .../processors/cache/GridCacheMapEntry.java     |  56 +-
 .../CacheContinuousQueryVariationsTest.java     | 949 +++++++++++++++++++
 .../IgniteConfigVariationsAbstractTest.java     |   2 +-
 ...iteContinuousQueryConfigVariationsSuite.java |  60 ++
 4 files changed, 1040 insertions(+), 27 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/c9416ed9/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheMapEntry.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheMapEntry.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheMapEntry.java
index eb3d903..cb51a8c 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheMapEntry.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheMapEntry.java
@@ -1379,12 +1379,6 @@ public abstract class GridCacheMapEntry extends GridMetadataAwareAdapter impleme
 
             update(null, 0, 0, newVer, true);
 
-            if (cctx.offheapTiered() && hadValPtr) {
-                boolean rmv = cctx.swap().removeOffheap(key);
-
-                assert rmv;
-            }
-
             if (cctx.deferredDelete() && !detached() && !isInternal()) {
                 if (!deletedUnlocked()) {
                     deletedUnlocked(true);
@@ -1457,6 +1451,18 @@ public abstract class GridCacheMapEntry extends GridMetadataAwareAdapter impleme
 
             deferred = cctx.deferredDelete() && !detached() && !isInternal();
 
+            if (intercept) {
+                entry0.updateCounter(updateCntr0);
+
+                cctx.config().getInterceptor().onAfterRemove(entry0);
+            }
+
+            if (cctx.offheapTiered() && hadValPtr) {
+                boolean rmv = cctx.swap().removeOffheap(key);
+
+                assert rmv;
+            }
+
             if (!deferred) {
                 // If entry is still removed.
                 assert newVer == ver;
@@ -1483,12 +1489,6 @@ public abstract class GridCacheMapEntry extends GridMetadataAwareAdapter impleme
             onMarkedObsolete();
         }
 
-        if (intercept) {
-            entry0.updateCounter(updateCntr0);
-
-            cctx.config().getInterceptor().onAfterRemove(entry0);
-        }
-
         if (valid) {
             CacheObject ret;
 
@@ -1729,6 +1729,8 @@ public abstract class GridCacheMapEntry extends GridMetadataAwareAdapter impleme
             if (ttl == CU.TTL_ZERO)
                 op = GridCacheOperation.DELETE;
 
+            boolean hasValPtr = false;
+
             // Try write-through.
             if (op == GridCacheOperation.UPDATE) {
                 // Detach value before index update.
@@ -1772,7 +1774,7 @@ public abstract class GridCacheMapEntry extends GridMetadataAwareAdapter impleme
                     // Must persist inside synchronization in non-tx mode.
                     cctx.store().remove(null, key);
 
-                boolean hasValPtr = hasOffHeapPointer();
+                hasValPtr = hasOffHeapPointer();
 
                 if (old == null)
                     old = saveValueForIndexUnlocked();
@@ -1783,12 +1785,6 @@ public abstract class GridCacheMapEntry extends GridMetadataAwareAdapter impleme
 
                 update(null, CU.TTL_ETERNAL, CU.EXPIRE_TIME_ETERNAL, ver, true);
 
-                if (cctx.offheapTiered() && hasValPtr) {
-                    boolean rmv = cctx.swap().removeOffheap(key);
-
-                    assert rmv;
-                }
-
                 if (evt) {
                     CacheObject evtOld = null;
 
@@ -1838,6 +1834,12 @@ public abstract class GridCacheMapEntry extends GridMetadataAwareAdapter impleme
                 else
                     cctx.config().getInterceptor().onAfterRemove(new CacheLazyEntry(cctx, key, key0, old, old0, keepBinary, 0L));
             }
+
+            if (op != GridCacheOperation.UPDATE && cctx.offheapTiered() && hasValPtr) {
+                boolean rmv = cctx.swap().removeOffheap(key);
+
+                assert rmv;
+            }
         }
 
         return new GridTuple3<>(res,
@@ -2326,6 +2328,8 @@ public abstract class GridCacheMapEntry extends GridMetadataAwareAdapter impleme
 
             IgniteBiTuple<Boolean, Object> interceptRes = null;
 
+            boolean hasValPtr = false;
+
             // Actual update.
             if (op == GridCacheOperation.UPDATE) {
                 if (intercept) {
@@ -2461,7 +2465,7 @@ public abstract class GridCacheMapEntry extends GridMetadataAwareAdapter impleme
 
                 enqueueVer = newVer;
 
-                boolean hasValPtr = hasOffHeapPointer();
+                hasValPtr = hasOffHeapPointer();
 
                 // Clear value on backup. Entry will be removed from cache when it got evicted from queue.
                 update(null, CU.TTL_ETERNAL, CU.EXPIRE_TIME_ETERNAL, newVer, true);
@@ -2469,12 +2473,6 @@ public abstract class GridCacheMapEntry extends GridMetadataAwareAdapter impleme
                 assert newSysTtl == CU.TTL_NOT_CHANGED;
                 assert newSysExpireTime == CU.EXPIRE_TIME_CALCULATE;
 
-                if (cctx.offheapTiered() && hasValPtr) {
-                    boolean rmv = cctx.swap().removeOffheap(key);
-
-                    assert rmv;
-                }
-
                 clearReaders();
 
                 recordNodeId(affNodeId, topVer);
@@ -2548,6 +2546,12 @@ public abstract class GridCacheMapEntry extends GridMetadataAwareAdapter impleme
                 if (interceptRes != null)
                     oldVal = cctx.toCacheObject(cctx.unwrapTemporary(interceptRes.get2()));
             }
+
+            if (op != GridCacheOperation.UPDATE && cctx.offheapTiered() && hasValPtr) {
+                boolean rmv = cctx.swap().removeOffheap(key);
+
+                assert rmv;
+            }
         }
 
         if (log.isDebugEnabled())

http://git-wip-us.apache.org/repos/asf/ignite/blob/c9416ed9/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/query/continuous/CacheContinuousQueryVariationsTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/query/continuous/CacheContinuousQueryVariationsTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/query/continuous/CacheContinuousQueryVariationsTest.java
new file mode 100644
index 0000000..b0a53c0
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/query/continuous/CacheContinuousQueryVariationsTest.java
@@ -0,0 +1,949 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ignite.internal.processors.cache.query.continuous;
+
+import java.io.Externalizable;
+import java.io.IOException;
+import java.io.ObjectInput;
+import java.io.ObjectOutput;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.Random;
+import java.util.concurrent.ArrayBlockingQueue;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.TimeUnit;
+import javax.cache.configuration.Factory;
+import javax.cache.configuration.FactoryBuilder;
+import javax.cache.configuration.MutableCacheEntryListenerConfiguration;
+import javax.cache.event.CacheEntryCreatedListener;
+import javax.cache.event.CacheEntryEvent;
+import javax.cache.event.CacheEntryExpiredListener;
+import javax.cache.event.CacheEntryListener;
+import javax.cache.event.CacheEntryListenerException;
+import javax.cache.event.CacheEntryRemovedListener;
+import javax.cache.event.CacheEntryUpdatedListener;
+import javax.cache.event.EventType;
+import javax.cache.processor.EntryProcessor;
+import javax.cache.processor.MutableEntry;
+import org.apache.ignite.Ignite;
+import org.apache.ignite.IgniteCache;
+import org.apache.ignite.binary.BinaryObject;
+import org.apache.ignite.cache.CacheEntryEventSerializableFilter;
+import org.apache.ignite.cache.query.ContinuousQuery;
+import org.apache.ignite.cache.query.QueryCursor;
+import org.apache.ignite.configuration.CacheConfiguration;
+import org.apache.ignite.configuration.IgniteConfiguration;
+import org.apache.ignite.internal.binary.BinaryMarshaller;
+import org.apache.ignite.internal.util.typedef.CI1;
+import org.apache.ignite.internal.util.typedef.G;
+import org.apache.ignite.internal.util.typedef.PA;
+import org.apache.ignite.internal.util.typedef.internal.S;
+import org.apache.ignite.lang.IgniteAsyncCallback;
+import org.apache.ignite.lang.IgniteInClosure;
+import org.apache.ignite.testframework.GridTestUtils;
+import org.apache.ignite.testframework.junits.IgniteCacheConfigVariationsAbstractTest;
+import org.apache.ignite.transactions.Transaction;
+import org.apache.ignite.transactions.TransactionConcurrency;
+import org.apache.ignite.transactions.TransactionIsolation;
+import org.jetbrains.annotations.Nullable;
+
+import static java.util.concurrent.TimeUnit.MILLISECONDS;
+import static java.util.concurrent.TimeUnit.SECONDS;
+import static javax.cache.event.EventType.CREATED;
+import static javax.cache.event.EventType.REMOVED;
+import static org.apache.ignite.cache.CacheAtomicityMode.TRANSACTIONAL;
+import static org.apache.ignite.internal.processors.cache.query.continuous.CacheContinuousQueryVariationsTest.SerializableFilter.isAccepted;
+import static org.apache.ignite.testframework.junits.IgniteConfigVariationsAbstractTest.DataMode.EXTERNALIZABLE;
+import static org.apache.ignite.transactions.TransactionIsolation.READ_COMMITTED;
+import static org.apache.ignite.transactions.TransactionIsolation.REPEATABLE_READ;
+import static org.apache.ignite.transactions.TransactionIsolation.SERIALIZABLE;
+
+/**
+ *
+ */
+public class CacheContinuousQueryVariationsTest extends IgniteCacheConfigVariationsAbstractTest {
+    /** */
+    private static final int ITERATION_CNT = 20;
+
+    /** */
+    private static final int KEYS = 50;
+
+    /** */
+    private static final int VALS = 10;
+
+    /** */
+    public static boolean singleNode = false;
+
+    /** {@inheritDoc} */
+    @Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception {
+        IgniteConfiguration cfg = super.getConfiguration(gridName);
+
+        cfg.setClientMode(gridName.endsWith("0") && !singleNode);
+
+        return cfg;
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testRandomOperationJCacheApiKeepBinary() throws Exception {
+        testRandomOperation(true, false, false, false, true);
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testRandomOperationJCacheApiAsyncCallback() throws Exception {
+        testRandomOperation(true, false, false, true, false);
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testRandomOperationJCacheApiWithFilter() throws Exception {
+        testRandomOperation(true, false, true, false, false);
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testRandomOperationJCacheApiWithFilterAsyncCallback() throws Exception {
+        testRandomOperation(true, false, true, true, false);
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testRandomOperationJCacheApiSyncWithFilter() throws Exception {
+        testRandomOperation(true, true, true, false, false);
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testRandomOperation() throws Exception {
+        testRandomOperation(true, true, false, false, false);
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testRandomOperationWithKeepBinary() throws Exception {
+        testRandomOperation(true, true, false, false, true);
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testRandomOperationWithAsyncCallback() throws Exception {
+        testRandomOperation(true, true, false, true, false);
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testRandomOperationWithFilter() throws Exception {
+        testRandomOperation(true, true, true, false, false);
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testRandomOperationWithFilterWithKeepBinary() throws Exception {
+        testRandomOperation(true, true, true, false, true);
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testRandomOperationWithFilterAsyncCallback() throws Exception {
+        testRandomOperation(true, true, true, true, false);
+    }
+
+    /**
+     * @param jcacheApi Use JCache API.
+     * @param syncNtf Use sync notification.
+     * @param withFilter Use filter.
+     * @param asyncCallback Filter is annotated IgniteAsyncCallback
+     * @param keepBinary Keep binary.
+     * @throws Exception If failed.
+     */
+    private void testRandomOperation(final boolean jcacheApi, final boolean syncNtf, final boolean withFilter,
+        final boolean asyncCallback, final boolean keepBinary)
+        throws Exception {
+        if (keepBinary && !(getConfiguration().getMarshaller() == null
+            || getConfiguration().getMarshaller().getClass() == BinaryMarshaller.class))
+            return;
+
+        runInAllDataModes(new TestRunnable() {
+            @Override public void run() throws Exception {
+                long seed = System.currentTimeMillis();
+
+                Random rnd = new Random(seed);
+
+                log.info("Random seed: " + seed);
+
+                // Register listener on all nodes.
+                List<BlockingQueue<CacheEntryEvent<?, ?>>> evtsQueues = new ArrayList<>();
+
+                Collection<QueryCursor<?>> curs = new ArrayList<>();
+
+                Collection<MutableCacheEntryListenerConfiguration> lsnrCfgs = new ArrayList<>();
+
+                for (int idx = 0; idx < G.allGrids().size(); idx++) {
+                    final BlockingQueue<CacheEntryEvent<?, ?>> evtsQueue = new ArrayBlockingQueue<>(50_000);
+
+                    CI1<Iterable<CacheEntryEvent<?, ?>>> clsr = new CI1<Iterable<CacheEntryEvent<?, ?>>>() {
+                        @Override public void apply(Iterable<CacheEntryEvent<?, ?>> evts) {
+                            for (CacheEntryEvent<?, ?> evt : evts)
+                                evtsQueue.add(evt);
+                        }
+                    };
+
+                    final CacheEntryUpdatedListener<Object, Object> lsnr = asyncCallback ?
+                        new AsyncLocalNonSerializableListener(clsr): new LocalNonSerializableListener(clsr);
+
+                    IgniteCache<Object, Object> jcache = keepBinary ? jcache(idx).withKeepBinary() : jcache(idx);
+
+                    if (jcacheApi) {
+                        MutableCacheEntryListenerConfiguration<Object, Object> lsnrCfg =
+                            new MutableCacheEntryListenerConfiguration<>(
+                                new Factory<CacheEntryListener<? super Object, ? super Object>>() {
+                                    @Override public CacheEntryListener<? super Object, ? super Object> create() {
+                                        return lsnr;
+                                    }
+                                },
+                                withFilter ?
+                                    FactoryBuilder.factoryOf(
+                                        asyncCallback ? new AsyncSerializableFilter(keepBinary, dataMode)
+                                            : new SerializableFilter(keepBinary, dataMode))
+                                    : null,
+                                true,
+                                syncNtf
+                            );
+
+                        jcache.registerCacheEntryListener(lsnrCfg);
+
+                        lsnrCfgs.add(lsnrCfg);
+
+                        evtsQueues.add(evtsQueue);
+                    }
+                    else {
+                        ContinuousQuery<Object, Object> qry = new ContinuousQuery<>();
+
+                        qry.setLocalListener(lsnr);
+
+                        qry.setRemoteFilterFactory(withFilter ?
+                            FactoryBuilder.factoryOf(
+                                asyncCallback ? new AsyncSerializableFilter(keepBinary, dataMode)
+                                    : new SerializableFilter(keepBinary, dataMode))
+                            : null);
+
+                        curs.add(jcache.query(qry));
+
+                        evtsQueues.add(evtsQueue);
+                    }
+                }
+
+                ConcurrentMap<Object, Object> expData = new ConcurrentHashMap<>();
+
+                try {
+                    for (int i = 0; i < ITERATION_CNT; i++) {
+                        if (i % 5 == 0)
+                            log.info("Iteration: " + i);
+
+                        for (int idx = 0; idx < G.allGrids().size(); idx++)
+                            randomUpdate(rnd,
+                                evtsQueues,
+                                expData,
+                                keepBinary ? jcache(idx).withKeepBinary() : jcache(idx),
+                                keepBinary,
+                                withFilter);
+                    }
+                }
+                catch (Exception e) {
+                    log.error("Got unexpected error: ", e);
+
+                    throw e;
+                }
+                finally {
+                    for (QueryCursor<?> cur : curs)
+                        cur.close();
+
+                    for (int i = 0; i < G.allGrids().size(); i++) {
+                        for (MutableCacheEntryListenerConfiguration cfg : lsnrCfgs)
+                            jcache(i).deregisterCacheEntryListener(cfg);
+                    }
+                }
+            }
+        });
+    }
+
+    /**
+     * @param rnd Random generator.
+     * @param evtsQueues Events queue.
+     * @param expData Expected cache data.
+     * @param cache Cache.
+     * @throws Exception If failed.
+     */
+    private void randomUpdate(
+        Random rnd,
+        List<BlockingQueue<CacheEntryEvent<?, ?>>> evtsQueues,
+        ConcurrentMap<Object, Object> expData,
+        IgniteCache<Object, Object> cache,
+        boolean keepBinary,
+        boolean withFilter
+    ) throws Exception {
+        Object key = key(rnd.nextInt(KEYS));
+        Object newVal = value(rnd.nextInt());
+        Object oldVal = expData.get(key);
+
+        int op = rnd.nextInt(11);
+
+        Ignite ignite = cache.unwrap(Ignite.class);
+
+        Transaction tx = null;
+
+        if (cache.getConfiguration(CacheConfiguration.class).getAtomicityMode() == TRANSACTIONAL && rnd.nextBoolean())
+            tx = ignite.transactions().txStart(txRandomConcurrency(rnd), txRandomIsolation(rnd));
+
+        try {
+            // log.info("Random operation [key=" + key + ", op=" + op + ']');
+
+            switch (op) {
+                case 0: {
+                    cache.put(key, newVal);
+
+                    if (tx != null)
+                        tx.commit();
+
+                    waitAndCheckEvent(evtsQueues, key, newVal, oldVal, keepBinary, withFilter);
+
+                    expData.put(key, newVal);
+
+                    break;
+                }
+
+                case 1: {
+                    cache.getAndPut(key, newVal);
+
+                    if (tx != null)
+                        tx.commit();
+
+                    waitAndCheckEvent(evtsQueues, key, newVal, oldVal, keepBinary, withFilter);
+
+                    expData.put(key, newVal);
+
+                    break;
+                }
+
+                case 2: {
+                    cache.remove(key);
+
+                    if (tx != null)
+                        tx.commit();
+
+                    waitAndCheckEvent(evtsQueues, key, null, oldVal, keepBinary, withFilter);
+
+                    expData.remove(key);
+
+                    break;
+                }
+
+                case 3: {
+                    cache.getAndRemove(key);
+
+                    if (tx != null)
+                        tx.commit();
+
+                    waitAndCheckEvent(evtsQueues, key, null, oldVal, keepBinary, withFilter);
+
+                    expData.remove(key);
+
+                    break;
+                }
+
+                case 4: {
+                    cache.invoke(key, new EntrySetValueProcessor(newVal, rnd.nextBoolean()));
+
+                    if (tx != null)
+                        tx.commit();
+
+                    waitAndCheckEvent(evtsQueues, key, newVal, oldVal, keepBinary, withFilter);
+
+                    expData.put(key, newVal);
+
+                    break;
+                }
+
+                case 5: {
+                    cache.invoke(key, new EntrySetValueProcessor(null, rnd.nextBoolean()));
+
+                    if (tx != null)
+                        tx.commit();
+
+                    waitAndCheckEvent(evtsQueues, key, null, oldVal, keepBinary, withFilter);
+
+                    expData.remove(key);
+
+                    break;
+                }
+
+                case 6: {
+                    cache.putIfAbsent(key, newVal);
+
+                    if (tx != null)
+                        tx.commit();
+
+                    if (oldVal == null) {
+                        waitAndCheckEvent(evtsQueues, key, newVal, null, keepBinary, withFilter);
+
+                        expData.put(key, newVal);
+                    }
+                    else
+                        checkNoEvent(evtsQueues);
+
+                    break;
+                }
+
+                case 7: {
+                    cache.getAndPutIfAbsent(key, newVal);
+
+                    if (tx != null)
+                        tx.commit();
+
+                    if (oldVal == null) {
+                        waitAndCheckEvent(evtsQueues, key, newVal, null, keepBinary, withFilter);
+
+                        expData.put(key, newVal);
+                    }
+                    else
+                        checkNoEvent(evtsQueues);
+
+                    break;
+                }
+
+                case 8: {
+                    cache.replace(key, newVal);
+
+                    if (tx != null)
+                        tx.commit();
+
+                    if (oldVal != null) {
+                        waitAndCheckEvent(evtsQueues, key, newVal, oldVal, keepBinary, withFilter);
+
+                        expData.put(key, newVal);
+                    }
+                    else
+                        checkNoEvent(evtsQueues);
+
+                    break;
+                }
+
+                case 9: {
+                    cache.getAndReplace(key, newVal);
+
+                    if (tx != null)
+                        tx.commit();
+
+                    if (oldVal != null) {
+                        waitAndCheckEvent(evtsQueues, key, newVal, oldVal, keepBinary, withFilter);
+
+                        expData.put(key, newVal);
+                    }
+                    else
+                        checkNoEvent(evtsQueues);
+
+                    break;
+                }
+
+                case 10: {
+                    if (oldVal != null) {
+                        Object replaceVal = value(rnd.nextInt(VALS));
+
+                        boolean success = replaceVal.equals(oldVal);
+
+                        if (success) {
+                            cache.replace(key, replaceVal, newVal);
+
+                            if (tx != null)
+                                tx.commit();
+
+                            waitAndCheckEvent(evtsQueues, key, newVal, oldVal, keepBinary, withFilter);
+
+                            expData.put(key, newVal);
+                        }
+                        else {
+                            cache.replace(key, replaceVal, newVal);
+
+                            if (tx != null)
+                                tx.commit();
+
+                            checkNoEvent(evtsQueues);
+                        }
+                    }
+                    else {
+                        cache.replace(key, value(rnd.nextInt(VALS)), newVal);
+
+                        if (tx != null)
+                            tx.commit();
+
+                        checkNoEvent(evtsQueues);
+                    }
+
+                    break;
+                }
+
+                default:
+                    fail("Op:" + op);
+            }
+        }
+        finally {
+            if (tx != null)
+                tx.close();
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override protected long getTestTimeout() {
+        return TimeUnit.MINUTES.toMillis(5);
+    }
+
+    /**
+     * @param rnd {@link Random}.
+     * @return {@link TransactionConcurrency}.
+     */
+    private TransactionConcurrency txRandomConcurrency(Random rnd) {
+        return rnd.nextBoolean() ? TransactionConcurrency.OPTIMISTIC : TransactionConcurrency.PESSIMISTIC;
+    }
+
+    /**
+     * @param rnd {@link Random}.
+     * @return {@link TransactionIsolation}.
+     */
+    private TransactionIsolation txRandomIsolation(Random rnd) {
+        int val = rnd.nextInt(3);
+
+        if (val == 0)
+            return READ_COMMITTED;
+        else if (val == 1)
+            return REPEATABLE_READ;
+        else
+            return SERIALIZABLE;
+    }
+
+    /**
+     * @param evtsQueues Event queue.
+     * @param key Key.
+     * @param val Value.
+     * @param oldVal Old value.
+     * @param keepBinary Keep binary.
+     * @param withFilter With filter.
+     * @throws Exception If failed.
+     */
+    private void waitAndCheckEvent(List<BlockingQueue<CacheEntryEvent<?, ?>>> evtsQueues,
+        Object key,
+        Object val,
+        Object oldVal,
+        boolean keepBinary, boolean withFilter)
+        throws Exception {
+        if (val == null && oldVal == null || (withFilter && val != null && !isAccepted(val, false, dataMode))) {
+            checkNoEvent(evtsQueues);
+
+            return;
+        }
+
+        for (BlockingQueue<CacheEntryEvent<?, ?>> evtsQueue : evtsQueues) {
+            CacheEntryEvent<?, ?> evt = evtsQueue.poll(5, SECONDS);
+
+            assertNotNull("Failed to wait for event [key=" + key + ", val=" + val + ", oldVal=" + oldVal + ']', evt);
+
+            Object actKey = evt.getKey();
+            Object actVal = evt.getValue();
+            Object actOldVal = evt.getOldValue();
+
+            if (keepBinary) {
+                actKey = checkAndGetObject(actKey);
+                actVal = checkAndGetObject(actVal);
+                actOldVal = checkAndGetObject(actOldVal);
+            }
+
+            assertEquals(key, actKey);
+            assertEquals(val, actVal);
+            assertEquals(oldVal, actOldVal);
+        }
+    }
+
+    /**
+     * @param obj Binary object.
+     * @return Deserialize value.
+     */
+    private Object checkAndGetObject(@Nullable Object obj) {
+        if (obj != null) {
+            assert obj instanceof BinaryObject || dataMode == EXTERNALIZABLE: obj;
+
+            if (obj instanceof BinaryObject)
+                obj = ((BinaryObject)obj).deserialize();
+        }
+
+        return obj;
+    }
+
+    /**
+     * @param evtsQueues Event queue.
+     * @throws Exception If failed.
+     */
+    private void checkNoEvent(List<BlockingQueue<CacheEntryEvent<?, ?>>> evtsQueues) throws Exception {
+        for (BlockingQueue<CacheEntryEvent<?, ?>> evtsQueue : evtsQueues) {
+            CacheEntryEvent<?, ?> evt = evtsQueue.poll(10, MILLISECONDS);
+
+            assertNull(evt);
+        }
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testRemoveRemoveScenario() throws Exception {
+        runInAllDataModes(new TestRunnable() {
+            @Override public void run() throws Exception {
+                IgniteCache<Object, Object> cache = jcache();
+
+                ContinuousQuery<Object, Object> qry = new ContinuousQuery<>();
+
+                final List<CacheEntryEvent<?, ?>> evts = new CopyOnWriteArrayList<>();
+
+                qry.setLocalListener(new CacheEntryUpdatedListener<Object, Object>() {
+                    @Override public void onUpdated(Iterable<CacheEntryEvent<?, ?>> events)
+                        throws CacheEntryListenerException {
+                        for (CacheEntryEvent<?, ?> e : events)
+                            evts.add(e);
+                    }
+                });
+
+                Object key = key(1);
+
+                try (QueryCursor qryCur = cache.query(qry)) {
+                    for (int i = 0; i < ITERATION_CNT; i++) {
+                        log.info("Start iteration: " + i);
+                        // Not events.
+                        cache.invoke(key, new EntrySetValueProcessor(true));
+
+                        // Get events.
+                        cache.put(key, value(1));
+                        cache.remove(key);
+
+                        // Not events.
+                        cache.invoke(key, new EntrySetValueProcessor(null, false));
+                        cache.invoke(key, new EntrySetValueProcessor(null, false));
+                        cache.invoke(key, new EntrySetValueProcessor(true));
+                        cache.remove(key);
+
+                        // Get events.
+                        cache.put(key, value(2));
+
+                        // Not events.
+                        cache.invoke(key, new EntrySetValueProcessor(true));
+
+                        // Get events.
+                        cache.invoke(key, new EntrySetValueProcessor(null, false));
+
+                        // Not events.
+                        cache.remove(key);
+
+                        // Get events.
+                        cache.put(key, value(3));
+                        cache.put(key, value(4));
+
+                        // Not events.
+                        cache.invoke(key, new EntrySetValueProcessor(true));
+                        cache.putIfAbsent(key, value(5));
+                        cache.putIfAbsent(key, value(5));
+                        cache.putIfAbsent(key, value(5));
+                        cache.invoke(key, new EntrySetValueProcessor(true));
+                        cache.remove(key, value(5));
+
+                        // Get events.
+                        cache.remove(key, value(4));
+                        cache.putIfAbsent(key, value(5));
+
+                        // Not events.
+                        cache.replace(key, value(3), value(2));
+                        cache.replace(key, value(3), value(2));
+                        cache.replace(key, value(3), value(2));
+
+                        // Get events.
+                        cache.replace(key, value(5), value(6));
+
+                        assert GridTestUtils.waitForCondition(new PA() {
+                            @Override public boolean apply() {
+                                return evts.size() == 9;
+                            }
+                        }, 5_000);
+
+                        checkEvent(evts.get(0), CREATED, value(1), null);
+                        checkEvent(evts.get(1), REMOVED, null, value(1));
+                        checkEvent(evts.get(2), CREATED, value(2), null);
+                        checkEvent(evts.get(3), REMOVED, null, value(2));
+                        checkEvent(evts.get(4), CREATED, value(3), null);
+                        checkEvent(evts.get(5), EventType.UPDATED, value(4), value(3));
+                        checkEvent(evts.get(6), REMOVED, null, value(4));
+                        checkEvent(evts.get(7), CREATED, value(5), null);
+                        checkEvent(evts.get(8), EventType.UPDATED, value(6), value(5));
+
+                        cache.remove(key);
+                        cache.remove(key);
+
+                        evts.clear();
+
+                        log.info("Finish iteration: " + i);
+                    }
+                }
+            }
+        });
+    }
+
+    /**
+     * @param event Event.
+     * @param type Event type.
+     * @param val Value.
+     * @param oldVal Old value.
+     */
+    private void checkEvent(CacheEntryEvent<?, ?> event, EventType type, Object val, Object oldVal) {
+        assertEquals(event.getEventType(), type);
+        assertEquals(event.getValue(), val);
+        assertEquals(event.getOldValue(), oldVal);
+    }
+
+    /**
+     *
+     */
+    protected static class EntrySetValueProcessor implements EntryProcessor<Object, Object, Object> {
+        /** */
+        private Object val;
+
+        /** */
+        private boolean retOld;
+
+        /** */
+        private boolean skipModify;
+
+        /**
+         * @param skipModify If {@code true} then entry will not be modified.
+         */
+        public EntrySetValueProcessor(boolean skipModify) {
+            this.skipModify = skipModify;
+        }
+
+        /**
+         * @param val Value to set.
+         * @param retOld Return old value flag.
+         */
+        public EntrySetValueProcessor(Object val, boolean retOld) {
+            this.val = val;
+            this.retOld = retOld;
+        }
+
+        /** {@inheritDoc} */
+        @Override public Object process(MutableEntry<Object, Object> e, Object... args) {
+            if (skipModify)
+                return null;
+
+            Object old = retOld ? e.getValue() : null;
+
+            if (val != null)
+                e.setValue(val);
+            else
+                e.remove();
+
+            return old;
+        }
+
+        /** {@inheritDoc} */
+        @Override public String toString() {
+            return S.toString(EntrySetValueProcessor.class, this);
+        }
+    }
+
+    /**
+     *
+     */
+    @IgniteAsyncCallback
+    public static class AsyncSerializableFilter extends SerializableFilter {
+        /**
+         *
+         */
+        public AsyncSerializableFilter() {
+            // No-op.
+        }
+
+        /**
+         * @param keepBinary Keep binary.
+         * @param dataMode Data mode.
+         */
+        public AsyncSerializableFilter(boolean keepBinary, DataMode dataMode) {
+            super(keepBinary, dataMode);
+        }
+    }
+
+    /**
+     *
+     */
+    public static class SerializableFilter implements CacheEntryEventSerializableFilter<Object, Object> {
+        /** */
+        private boolean keepBinary;
+
+        /** */
+        private DataMode dataMode;
+
+        /** */
+        public SerializableFilter() {
+            // No-op.
+        }
+
+        /**
+         * @param keepBinary Keep binary.
+         * @param dataMode Data mode.
+         */
+        public SerializableFilter(boolean keepBinary, DataMode dataMode) {
+            this.keepBinary = keepBinary;
+            this.dataMode = dataMode;
+        }
+
+        /** {@inheritDoc} */
+        @Override public boolean evaluate(CacheEntryEvent<?, ?> event)
+            throws CacheEntryListenerException {
+            return isAccepted(event.getValue(), keepBinary, dataMode);
+        }
+
+        /**
+         * @param val Value.
+         * @param keepBinary Keep binary.
+         * @param dataMode Data mode.
+         * @return {@code True} if value is even.
+         */
+        public static boolean isAccepted(Object val, boolean keepBinary, DataMode dataMode) {
+            if (val != null) {
+                int val0 = 0;
+
+                if (val instanceof TestObject) {
+                    assert !keepBinary || dataMode == EXTERNALIZABLE : val;
+
+                    val0 = valueOf(val);
+                }
+                else if (val instanceof BinaryObject) {
+                    assert keepBinary : val;
+
+                    val0 = ((BinaryObject)val).field("val");
+                }
+                else
+                    fail("Unexpected object: " + val);
+
+                return val0 % 2 == 0;
+            }
+
+            return true;
+        }
+    }
+
+    /**
+     *
+     */
+    @IgniteAsyncCallback
+    public static class AsyncLocalNonSerializableListener extends LocalNonSerializableListener {
+        /**
+         * @param clsr Closure.
+         */
+        AsyncLocalNonSerializableListener(IgniteInClosure<Iterable<CacheEntryEvent<?, ?>>> clsr) {
+            super(clsr);
+        }
+
+        /**
+         *
+         */
+        public AsyncLocalNonSerializableListener() {
+            // No-op.
+        }
+    }
+
+    /**
+     *
+     */
+    public static class LocalNonSerializableListener implements
+        CacheEntryUpdatedListener<Object, Object>,
+        CacheEntryCreatedListener<Object, Object>,
+        CacheEntryExpiredListener<Object, Object>,
+        CacheEntryRemovedListener<Object, Object>,
+        Externalizable {
+        /** */
+        IgniteInClosure<Iterable<CacheEntryEvent<?, ?>>> clsr;
+
+        /**
+         * @param clsr Closure.
+         */
+        LocalNonSerializableListener(IgniteInClosure<Iterable<CacheEntryEvent<?, ?>>> clsr) {
+            this.clsr = clsr;
+        }
+
+        /** */
+        public LocalNonSerializableListener() {
+            // No-op.
+        }
+
+        /** {@inheritDoc} */
+        @Override public void onCreated(Iterable<CacheEntryEvent<?, ?>> evts) throws CacheEntryListenerException {
+            onEvents(evts);
+        }
+
+        /** {@inheritDoc} */
+        @Override public void onExpired(Iterable<CacheEntryEvent<?, ?>> evts) throws CacheEntryListenerException {
+            onEvents(evts);
+        }
+
+        /** {@inheritDoc} */
+        @Override public void onRemoved(Iterable<CacheEntryEvent<?, ?>> evts) throws CacheEntryListenerException {
+            onEvents(evts);
+        }
+
+        /** {@inheritDoc} */
+        @Override public void onUpdated(Iterable<CacheEntryEvent<?, ?>> evts) throws CacheEntryListenerException {
+            onEvents(evts);
+        }
+
+        /**
+         * @param evts Events.
+         */
+        private void onEvents(Iterable<CacheEntryEvent<?, ?>> evts) {
+            clsr.apply(evts);
+        }
+
+        /** {@inheritDoc} */
+        @Override public void writeExternal(ObjectOutput out) throws IOException {
+            throw new UnsupportedOperationException("Failed. Listener should not be marshaled.");
+        }
+
+        /** {@inheritDoc} */
+        @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
+            throw new UnsupportedOperationException("Failed. Listener should not be unmarshaled.");
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/c9416ed9/modules/core/src/test/java/org/apache/ignite/testframework/junits/IgniteConfigVariationsAbstractTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/testframework/junits/IgniteConfigVariationsAbstractTest.java b/modules/core/src/test/java/org/apache/ignite/testframework/junits/IgniteConfigVariationsAbstractTest.java
index d70b606..51fcfcf 100644
--- a/modules/core/src/test/java/org/apache/ignite/testframework/junits/IgniteConfigVariationsAbstractTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/testframework/junits/IgniteConfigVariationsAbstractTest.java
@@ -153,7 +153,7 @@ public abstract class IgniteConfigVariationsAbstractTest extends GridCommonAbstr
     }
 
     /** {@inheritDoc} */
-    @Override protected final IgniteConfiguration getConfiguration(String gridName) throws Exception {
+    @Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception {
         IgniteConfiguration cfg = super.getConfiguration(gridName);
 
         IgniteConfiguration resCfg = testsCfg.configurationFactory().getConfiguration(gridName, cfg);

http://git-wip-us.apache.org/repos/asf/ignite/blob/c9416ed9/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteContinuousQueryConfigVariationsSuite.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteContinuousQueryConfigVariationsSuite.java b/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteContinuousQueryConfigVariationsSuite.java
new file mode 100644
index 0000000..221dcae
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteContinuousQueryConfigVariationsSuite.java
@@ -0,0 +1,60 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ignite.testsuites;
+
+import junit.framework.TestSuite;
+import org.apache.ignite.internal.processors.cache.query.continuous.CacheContinuousQueryVariationsTest;
+import org.apache.ignite.testframework.configvariations.ConfigVariationsTestSuiteBuilder;
+
+import static org.apache.ignite.IgniteSystemProperties.IGNITE_DISCOVERY_HISTORY_SIZE;
+
+/**
+ * Test suite for cache queries.
+ */
+public class IgniteContinuousQueryConfigVariationsSuite extends TestSuite {
+    /**
+     * @return Test suite.
+     * @throws Exception If failed.
+     */
+    public static TestSuite suite() throws Exception {
+        System.setProperty(IGNITE_DISCOVERY_HISTORY_SIZE, "100");
+
+        TestSuite suite = new TestSuite("Ignite Continuous Query Config Variations Suite");
+
+        CacheContinuousQueryVariationsTest.singleNode = false;
+
+        suite.addTest(new ConfigVariationsTestSuiteBuilder(
+            "5 nodes 1 backup",
+            CacheContinuousQueryVariationsTest.class)
+            .withBasicCacheParams()
+            .gridsCount(5)
+            .backups(2)
+            .build());
+
+        CacheContinuousQueryVariationsTest.singleNode = true;
+
+        suite.addTest(new ConfigVariationsTestSuiteBuilder(
+            "Single node",
+            CacheContinuousQueryVariationsTest.class)
+            .withBasicCacheParams()
+            .gridsCount(1)
+            .build());
+
+        return suite;
+    }
+}


[16/17] ignite git commit: IGNITE-3188: Binary marshaller doesn't unmarshal a void type (added tests)

Posted by dm...@apache.org.
IGNITE-3188: Binary marshaller doesn't unmarshal a void type (added tests)


Project: http://git-wip-us.apache.org/repos/asf/ignite/repo
Commit: http://git-wip-us.apache.org/repos/asf/ignite/commit/e274d44a
Tree: http://git-wip-us.apache.org/repos/asf/ignite/tree/e274d44a
Diff: http://git-wip-us.apache.org/repos/asf/ignite/diff/e274d44a

Branch: refs/heads/master
Commit: e274d44a37fd1269e7a3a5f0000e1ee6139fd0b0
Parents: 6fcc7a4
Author: Denis Magda <dm...@gridgain.com>
Authored: Thu May 26 14:57:52 2016 +0300
Committer: Denis Magda <dm...@gridgain.com>
Committed: Thu May 26 14:57:52 2016 +0300

----------------------------------------------------------------------
 .../binary/BinaryMarshallerSelfTest.java        | 15 ++++++++
 .../CacheKeepBinaryWithInterceptorTest.java     | 36 ++++++++++----------
 2 files changed, 33 insertions(+), 18 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/e274d44a/modules/core/src/test/java/org/apache/ignite/internal/binary/BinaryMarshallerSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/binary/BinaryMarshallerSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/binary/BinaryMarshallerSelfTest.java
index 936b1e6..065081a 100644
--- a/modules/core/src/test/java/org/apache/ignite/internal/binary/BinaryMarshallerSelfTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/internal/binary/BinaryMarshallerSelfTest.java
@@ -833,6 +833,21 @@ public class BinaryMarshallerSelfTest extends GridCommonAbstractTest {
     }
 
     /**
+     * @throws Exception If failed.
+     */
+    public void testVoid() throws Exception {
+        Class clazz = Void.class;
+
+        assertEquals(clazz, marshalUnmarshal(clazz));
+
+        clazz = Void.TYPE;
+
+        assertEquals(clazz, marshalUnmarshal(clazz));
+    }
+
+
+
+    /**
      *
      */
     private static class EnclosingObj implements Serializable {

http://git-wip-us.apache.org/repos/asf/ignite/blob/e274d44a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/binary/CacheKeepBinaryWithInterceptorTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/binary/CacheKeepBinaryWithInterceptorTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/binary/CacheKeepBinaryWithInterceptorTest.java
index 60b48a8..74b8659 100644
--- a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/binary/CacheKeepBinaryWithInterceptorTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/binary/CacheKeepBinaryWithInterceptorTest.java
@@ -110,23 +110,23 @@ public class CacheKeepBinaryWithInterceptorTest extends GridCommonAbstractTest {
             cache.put(new TestKey(1), new TestValue(10));
 
             BinaryObject obj = (BinaryObject)cache.get(new TestKey(1));
-            assertEquals(10, obj.field("val"));
+            assertEquals(10, (int)obj.field("val"));
 
             asyncCache.get(new TestKey(1));
             obj = (BinaryObject)asyncCache.future().get();
-            assertEquals(10, obj.field("val"));
+            assertEquals(10, (int)obj.field("val"));
 
             Cache.Entry<BinaryObject, BinaryObject> e = (Cache.Entry)cache.getEntry(new TestKey(1));
-            assertEquals(1, e.getKey().field("key"));
-            assertEquals(10, e.getValue().field("val"));
+            assertEquals(1, (int)e.getKey().field("key"));
+            assertEquals(10, (int)e.getValue().field("val"));
 
             asyncCache.getEntry(new TestKey(1));
             e = (Cache.Entry)asyncCache.future().get();
-            assertEquals(1, e.getKey().field("key"));
-            assertEquals(10, e.getValue().field("val"));
+            assertEquals(1, (int)e.getKey().field("key"));
+            assertEquals(10, (int)e.getValue().field("val"));
 
             obj = (BinaryObject)cache.getAndRemove(new TestKey(1));
-            assertEquals(10, obj.field("val"));
+            assertEquals(10, (int)obj.field("val"));
 
             cache.put(new TestKey(1), new TestValue(10));
 
@@ -239,8 +239,8 @@ public class CacheKeepBinaryWithInterceptorTest extends GridCommonAbstractTest {
 
             onGet++;
 
-            assertEquals(1, key.field("key"));
-            assertEquals(10, val.field("val"));
+            assertEquals(1, (int)key.field("key"));
+            assertEquals(10, (int)val.field("val"));
 
             return val;
         }
@@ -252,10 +252,10 @@ public class CacheKeepBinaryWithInterceptorTest extends GridCommonAbstractTest {
             onBeforePut++;
 
             if (entry.getValue() != null)
-                assertEquals(10, entry.getValue().field("val"));
+                assertEquals(10, (int)entry.getValue().field("val"));
 
-            assertEquals(1, entry.getKey().field("key"));
-            assertEquals(10, newVal.field("val"));
+            assertEquals(1, (int)entry.getKey().field("key"));
+            assertEquals(10, (int)newVal.field("val"));
 
             return newVal;
         }
@@ -266,14 +266,14 @@ public class CacheKeepBinaryWithInterceptorTest extends GridCommonAbstractTest {
 
             onAfterPut++;
 
-            assertEquals(1, entry.getKey().field("key"));
-            assertEquals(10, entry.getValue().field("val"));
+            assertEquals(1, (int)entry.getKey().field("key"));
+            assertEquals(10, (int)entry.getValue().field("val"));
         }
 
         /** {@inheritDoc} */
         @Nullable @Override public IgniteBiTuple<Boolean, BinaryObject> onBeforeRemove(Cache.Entry<BinaryObject, BinaryObject> entry) {
-            assertEquals(1, entry.getKey().field("key"));
-            assertEquals(10, entry.getValue().field("val"));
+            assertEquals(1, (int)entry.getKey().field("key"));
+            assertEquals(10, (int)entry.getValue().field("val"));
 
             onBeforeRmv++;
 
@@ -286,8 +286,8 @@ public class CacheKeepBinaryWithInterceptorTest extends GridCommonAbstractTest {
 
             onAfterRmv++;
 
-            assertEquals(1, entry.getKey().field("key"));
-            assertEquals(10, entry.getValue().field("val"));
+            assertEquals(1, (int)entry.getKey().field("key"));
+            assertEquals(10, (int)entry.getValue().field("val"));
         }
     }
 


[03/17] ignite git commit: ignite-2528 Removed cache blocking operations from kernal write lock.

Posted by dm...@apache.org.
ignite-2528 Removed cache blocking operations from kernal write lock.

This closes #730
(cherry picked from commit f83a5f7)


Project: http://git-wip-us.apache.org/repos/asf/ignite/repo
Commit: http://git-wip-us.apache.org/repos/asf/ignite/commit/1ebbd57b
Tree: http://git-wip-us.apache.org/repos/asf/ignite/tree/1ebbd57b
Diff: http://git-wip-us.apache.org/repos/asf/ignite/diff/1ebbd57b

Branch: refs/heads/master
Commit: 1ebbd57b74eef1abeb99fa9427667da17db9d01a
Parents: c9416ed
Author: sboikov <sb...@gridgain.com>
Authored: Mon May 23 09:52:43 2016 +0300
Committer: sboikov <sb...@gridgain.com>
Committed: Mon May 23 09:56:10 2016 +0300

----------------------------------------------------------------------
 .../apache/ignite/internal/IgniteKernal.java    | 11 +--
 ...eConcurrentEntryProcessorAccessStopTest.java | 82 ++++++++++++++++++++
 .../testsuites/IgniteKernalSelfTestSuite.java   |  2 +
 3 files changed, 90 insertions(+), 5 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/1ebbd57b/modules/core/src/main/java/org/apache/ignite/internal/IgniteKernal.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/IgniteKernal.java b/modules/core/src/main/java/org/apache/ignite/internal/IgniteKernal.java
index 18e5c62..e77875e 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/IgniteKernal.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/IgniteKernal.java
@@ -1907,11 +1907,6 @@ public class IgniteKernal implements IgniteEx, IgniteMXBean, Externalizable {
                 Thread.currentThread().interrupt();
 
             try {
-                GridCacheProcessor cache = ctx.cache();
-
-                if (cache != null)
-                    cache.blockGateways();
-
                 assert gw.getState() == STARTED || gw.getState() == STARTING || gw.getState() == DISCONNECTED;
 
                 // No more kernal calls from this point on.
@@ -1926,6 +1921,12 @@ public class IgniteKernal implements IgniteEx, IgniteMXBean, Externalizable {
                 gw.writeUnlock();
             }
 
+            // Stopping cache operations.
+            GridCacheProcessor cache = ctx.cache();
+
+            if (cache != null)
+                cache.blockGateways();
+
             // Unregister MBeans.
             if (!(
                 unregisterMBean(pubExecSvcMBean) &

http://git-wip-us.apache.org/repos/asf/ignite/blob/1ebbd57b/modules/core/src/test/java/org/apache/ignite/internal/IgniteConcurrentEntryProcessorAccessStopTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/IgniteConcurrentEntryProcessorAccessStopTest.java b/modules/core/src/test/java/org/apache/ignite/internal/IgniteConcurrentEntryProcessorAccessStopTest.java
new file mode 100644
index 0000000..864c9dc
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/IgniteConcurrentEntryProcessorAccessStopTest.java
@@ -0,0 +1,82 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ignite.internal;
+
+import javax.cache.processor.EntryProcessor;
+import javax.cache.processor.MutableEntry;
+import org.apache.ignite.Ignite;
+import org.apache.ignite.IgniteCache;
+import org.apache.ignite.configuration.CacheConfiguration;
+import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
+
+/**
+ * Tests node stop while it is being accessed from EntryProcessor.
+ */
+public class IgniteConcurrentEntryProcessorAccessStopTest extends GridCommonAbstractTest {
+    /** {@inheritDoc} */
+    @Override protected void beforeTestsStarted() throws Exception {
+        startGrid();
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void afterTestsStopped() throws Exception {
+        stopAllGrids();
+
+        super.afterTestsStopped();
+    }
+
+    /**
+     * Tests concurrent instance shutdown.
+     *
+     * @throws Exception If failed.
+     */
+    public void testConcurrentAccess() throws Exception {
+        CacheConfiguration<Object, Object> ccfg = new CacheConfiguration<>();
+
+        Ignite ignite = grid();
+
+        final IgniteCache<Object, Object> dfltCache = ignite.getOrCreateCache(ccfg);
+
+        dfltCache.put("1", "1");
+
+        Thread invoker = new Thread(new Runnable() {
+            @Override public void run() {
+                dfltCache.invoke("1", new EntryProcessor<Object, Object, Object>() {
+                    @Override public Object process(MutableEntry<Object, Object> e, Object... args) {
+                        int i = 100_000;
+
+                        while (i-- >= 0)
+                            grid().cluster().nodes();
+
+                        e.remove();
+
+                        return null;
+                    }
+                });
+            }
+        });
+
+        invoker.setName("ConcurrentEntryProcessorActionThread");
+
+        invoker.start();
+
+        stopGrid();
+
+        invoker.join();
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/1ebbd57b/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteKernalSelfTestSuite.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteKernalSelfTestSuite.java b/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteKernalSelfTestSuite.java
index b9e64c3..620c298 100644
--- a/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteKernalSelfTestSuite.java
+++ b/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteKernalSelfTestSuite.java
@@ -26,6 +26,7 @@ import org.apache.ignite.internal.GridDiscoverySelfTest;
 import org.apache.ignite.internal.GridFailedInputParametersSelfTest;
 import org.apache.ignite.internal.GridHomePathSelfTest;
 import org.apache.ignite.internal.GridKernalConcurrentAccessStopSelfTest;
+import org.apache.ignite.internal.IgniteConcurrentEntryProcessorAccessStopTest;
 import org.apache.ignite.internal.GridListenActorSelfTest;
 import org.apache.ignite.internal.GridLocalEventListenerSelfTest;
 import org.apache.ignite.internal.GridNodeFilterSelfTest;
@@ -118,6 +119,7 @@ public class IgniteKernalSelfTestSuite extends TestSuite {
         suite.addTestSuite(GridListenActorSelfTest.class);
         suite.addTestSuite(GridNodeLocalSelfTest.class);
         suite.addTestSuite(GridKernalConcurrentAccessStopSelfTest.class);
+        suite.addTestSuite(IgniteConcurrentEntryProcessorAccessStopTest.class);
         suite.addTestSuite(GridUpdateNotifierSelfTest.class);
         suite.addTestSuite(IgniteUpdateNotifierPerClusterSettingSelfTest.class);
         suite.addTestSuite(GridLocalEventListenerSelfTest.class);


[11/17] ignite git commit: IGNITE-2667: Allow to start caches in PRIVATE and ISOLATED deployment modes when BinaryMarshaller is used

Posted by dm...@apache.org.
IGNITE-2667: Allow to start caches in PRIVATE and ISOLATED deployment modes when BinaryMarshaller is used


Project: http://git-wip-us.apache.org/repos/asf/ignite/repo
Commit: http://git-wip-us.apache.org/repos/asf/ignite/commit/727afc87
Tree: http://git-wip-us.apache.org/repos/asf/ignite/tree/727afc87
Diff: http://git-wip-us.apache.org/repos/asf/ignite/diff/727afc87

Branch: refs/heads/master
Commit: 727afc87dce6c26756b56620c2aaccc3a3d0117e
Parents: e1ec0de
Author: Vladislav Pyatkov <vl...@gmail.com>
Authored: Wed May 25 08:29:00 2016 +0300
Committer: Denis Magda <dm...@gridgain.com>
Committed: Wed May 25 08:29:00 2016 +0300

----------------------------------------------------------------------
 .../processors/cache/GridCacheProcessor.java    |   7 +-
 .../CacheStartupInDeploymentModesTest.java      | 230 +++++++++++++++++++
 .../testsuites/IgniteCacheTestSuite3.java       |   2 +
 3 files changed, 236 insertions(+), 3 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/727afc87/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheProcessor.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheProcessor.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheProcessor.java
index 5711366..6625093 100755
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheProcessor.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheProcessor.java
@@ -392,9 +392,10 @@ public class GridCacheProcessor extends GridProcessorAdapter {
         DeploymentMode depMode = c.getDeploymentMode();
 
         if (c.isPeerClassLoadingEnabled() && (depMode == PRIVATE || depMode == ISOLATED) &&
-            !CU.isSystemCache(cc.getName()))
-            throw new IgniteCheckedException("Cannot start cache in PRIVATE or ISOLATED deployment mode: " +
-                ctx.config().getDeploymentMode());
+            !CU.isSystemCache(cc.getName()) && !(c.getMarshaller() instanceof BinaryMarshaller))
+            throw new IgniteCheckedException("Cache can be started in PRIVATE or ISOLATED deployment mode only when" +
+                " BinaryMarshaller is used [depMode=" + ctx.config().getDeploymentMode() + ", marshaller=" +
+                c.getMarshaller().getClass().getName() + ']');
 
         if (cc.isWriteBehindEnabled()) {
             if (cfgStore == null)

http://git-wip-us.apache.org/repos/asf/ignite/blob/727afc87/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/CacheStartupInDeploymentModesTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/CacheStartupInDeploymentModesTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/CacheStartupInDeploymentModesTest.java
new file mode 100644
index 0000000..c7cd5ea
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/CacheStartupInDeploymentModesTest.java
@@ -0,0 +1,230 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ignite.internal.processors.cache;
+
+import org.apache.ignite.IgniteCache;
+import org.apache.ignite.cache.CacheMode;
+import org.apache.ignite.configuration.CacheConfiguration;
+import org.apache.ignite.configuration.DeploymentMode;
+import org.apache.ignite.configuration.IgniteConfiguration;
+import org.apache.ignite.internal.binary.BinaryMarshaller;
+import org.apache.ignite.marshaller.Marshaller;
+import org.apache.ignite.marshaller.optimized.OptimizedMarshaller;
+import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
+
+/**
+ * Test verifies that it's possible to start caches in Isolated and Private mode when BinaryMarshaller is used.
+ */
+public class CacheStartupInDeploymentModesTest extends GridCommonAbstractTest {
+    /** */
+    private static final String REPLICATED_CACHE = "replicated";
+
+    /** */
+    private static final String PARTITIONED_CACHE = "partitioned";
+
+    /** */
+    private DeploymentMode deploymentMode;
+
+    /** */
+    private Marshaller marshaller;
+
+    /** {@inheritDoc} */
+    @Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception {
+        IgniteConfiguration cfg = super.getConfiguration(gridName);
+
+        cfg.setMarshaller(marshaller);
+        cfg.setDeploymentMode(deploymentMode);
+
+        CacheConfiguration cacheCfg1 = new CacheConfiguration();
+        cacheCfg1.setCacheMode(CacheMode.REPLICATED);
+        cacheCfg1.setName(REPLICATED_CACHE);
+
+        CacheConfiguration cacheCfg2 = new CacheConfiguration();
+        cacheCfg2.setCacheMode(CacheMode.PARTITIONED);
+        cacheCfg2.setName(PARTITIONED_CACHE);
+
+        cfg.setCacheConfiguration(cacheCfg1, cacheCfg2);
+
+        return cfg;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void afterTest() throws Exception {
+        stopAllGrids();
+
+        super.afterTest();
+    }
+
+    /**
+     * @throws Exception If fail.
+     */
+    public void testFailedInIsolatedMode() throws Exception {
+        deploymentMode = DeploymentMode.ISOLATED;
+        marshaller = new OptimizedMarshaller();
+
+        doCheckFailed(deploymentMode);
+    }
+
+    /**
+     * @throws Exception If fail.
+     */
+    public void testFailedInPrivateMode() throws Exception {
+        deploymentMode = DeploymentMode.PRIVATE;
+        marshaller = new OptimizedMarshaller();
+
+        doCheckFailed(deploymentMode);
+    }
+
+    /**
+     * @throws Exception If fail.
+     */
+    public void testStartedInIsolatedMode() throws Exception {
+        deploymentMode = DeploymentMode.ISOLATED;
+        marshaller = new BinaryMarshaller();
+
+        doCheckStarted(deploymentMode);
+    }
+
+    /**
+     * @throws Exception If fail.
+     */
+    public void testStartedInPrivateMode() throws Exception {
+        deploymentMode = DeploymentMode.PRIVATE;
+        marshaller = new BinaryMarshaller();
+
+        doCheckStarted(deploymentMode);
+    }
+
+    /**
+     * @param mode Deployment mode.
+     * @throws Exception If failed.
+     */
+    private void doCheckStarted(DeploymentMode mode) throws Exception {
+        startGridsMultiThreaded(2);
+
+        checkTopology(2);
+
+        assertEquals(mode, ignite(0).configuration().getDeploymentMode());
+
+        assert ignite(0).configuration().getMarshaller() instanceof BinaryMarshaller;
+
+        IgniteCache rCache = ignite(0).cache(REPLICATED_CACHE);
+
+        checkPutCache(rCache);
+
+        IgniteCache pCache = ignite(0).cache(PARTITIONED_CACHE);
+
+        checkPutCache(pCache);
+    }
+
+    /**
+     * @param mode Deployment mode.
+     * @throws Exception If failed.
+     */
+    private void doCheckFailed(DeploymentMode mode) throws Exception {
+        try {
+            startGridsMultiThreaded(2);
+        }
+        catch (Exception e) {
+            assert e.getMessage().contains("Cache can be started in PRIVATE or ISOLATED deployment mode only ");
+
+            return;
+        }
+
+        fail("Unexpected start of the caches!");
+    }
+
+    /**
+     * @param cache IgniteCache
+     */
+    private void checkPutCache(IgniteCache cache) {
+        for (int i = 0; i < 10; i++) {
+            Organization val = new Organization();
+
+            val.setId(i);
+            val.setName("Org " + i);
+
+            cache.put(i, val);
+        }
+
+        for (int i = 0; i < 10; i++) {
+            Organization org = (Organization)cache.get(i);
+
+            assertEquals(i, org.getId());
+        }
+    }
+
+    /**
+     * Cache value class.
+     */
+    private static class Organization {
+
+        /**
+         * Identifier.
+         */
+        private int id;
+
+        /**
+         * Name.
+         */
+        private String name;
+
+        /**
+         * Default constructor.
+         */
+        public Organization() {
+        }
+
+        /**
+         * @return Identifier.
+         */
+        public int getId() {
+            return id;
+        }
+
+        /**
+         * @param id Identifier.
+         */
+        public void setId(int id) {
+            this.id = id;
+        }
+
+        /**
+         * @return Name.
+         */
+        public String getName() {
+            return name;
+        }
+
+        /**
+         * @param name Name.
+         */
+        public void setName(String name) {
+            this.name = name;
+        }
+
+        /** {@inheritDoc} */
+        @Override public String toString() {
+            return "Organization{" +
+                "id=" + id +
+                ", name='" + name + '\'' +
+                '}';
+        }
+
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/727afc87/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteCacheTestSuite3.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteCacheTestSuite3.java b/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteCacheTestSuite3.java
index 8f3cf12..0785714 100644
--- a/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteCacheTestSuite3.java
+++ b/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteCacheTestSuite3.java
@@ -18,6 +18,7 @@
 package org.apache.ignite.testsuites;
 
 import junit.framework.TestSuite;
+import org.apache.ignite.internal.processors.cache.CacheStartupInDeploymentModesTest;
 import org.apache.ignite.internal.processors.cache.GridCacheAtomicEntryProcessorDeploymentSelfTest;
 import org.apache.ignite.internal.processors.cache.GridCacheConditionalDeploymentSelfTest;
 import org.apache.ignite.internal.processors.cache.GridCacheDeploymentOffHeapSelfTest;
@@ -126,6 +127,7 @@ public class IgniteCacheTestSuite3 extends TestSuite {
         suite.addTestSuite(GridCacheSyncReplicatedPreloadSelfTest.class);
 
         suite.addTestSuite(GridCacheDeploymentSelfTest.class);
+        suite.addTestSuite(CacheStartupInDeploymentModesTest.class);
         suite.addTestSuite(GridCacheDeploymentOffHeapSelfTest.class);
         suite.addTestSuite(GridCacheDeploymentOffHeapValuesSelfTest.class);
         suite.addTestSuite(GridCacheConditionalDeploymentSelfTest.class);


[17/17] ignite git commit: Merge remote-tracking branch 'remotes/community/gridgain-7.6.1'

Posted by dm...@apache.org.
Merge remote-tracking branch 'remotes/community/gridgain-7.6.1'


Project: http://git-wip-us.apache.org/repos/asf/ignite/repo
Commit: http://git-wip-us.apache.org/repos/asf/ignite/commit/271f9eea
Tree: http://git-wip-us.apache.org/repos/asf/ignite/tree/271f9eea
Diff: http://git-wip-us.apache.org/repos/asf/ignite/diff/271f9eea

Branch: refs/heads/master
Commit: 271f9eea4e762e3fcde6c08e97825e253cfe7c1a
Parents: 57a630e e274d44
Author: Denis Magda <dm...@gridgain.com>
Authored: Fri May 27 14:30:19 2016 +0300
Committer: Denis Magda <dm...@gridgain.com>
Committed: Fri May 27 14:30:19 2016 +0300

----------------------------------------------------------------------
 .../apache/ignite/IgniteSystemProperties.java   |  14 +
 .../ignite/internal/IgniteNodeAttributes.java   |   3 +
 .../discovery/GridDiscoveryManager.java         |  33 +-
 .../processors/cache/GridCacheProcessor.java    |   7 +-
 .../service/GridServiceAssignments.java         |  10 +-
 .../service/GridServiceProcessor.java           | 215 ++++-
 .../service/LazyServiceConfiguration.java       | 129 +++
 .../service/ServiceDescriptorImpl.java          |  17 +-
 .../ignite/services/ServiceConfiguration.java   |  14 +-
 .../ignite/spi/discovery/tcp/ServerImpl.java    |  72 ++
 .../binary/BinaryMarshallerSelfTest.java        |  15 +
 .../GridDiscoveryManagerAttributesSelfTest.java |  63 ++
 .../CacheStartupInDeploymentModesTest.java      | 230 +++++
 .../CacheKeepBinaryWithInterceptorTest.java     |  36 +-
 .../CacheContinuousQueryVariationsTest.java     | 949 +++++++++++++++++++
 ...yment2ClassLoadersDefaultMarshallerTest.java | 259 +++++
 ...eployment2ClassLoadersJdkMarshallerTest.java |  31 +
 ...ent2ClassLoadersOptimizedMarshallerTest.java |  31 +
 ...oymentClassLoadingDefaultMarshallerTest.java | 212 +++++
 ...DeploymentClassLoadingJdkMarshallerTest.java |  31 +
 ...mentClassLoadingOptimizedMarshallerTest.java |  31 +
 .../testsuites/IgniteCacheTestSuite3.java       |   2 +
 ...iteContinuousQueryConfigVariationsSuite.java |  60 ++
 .../testsuites/IgniteKernalSelfTestSuite.java   |  13 +
 .../apache/ignite/tests/p2p/NoopService.java    |  41 +
 .../apache/ignite/tests/p2p/NoopService2.java   |  41 +
 26 files changed, 2507 insertions(+), 52 deletions(-)
----------------------------------------------------------------------



[04/17] ignite git commit: IGNITE-3175 BigDecimal fields are not supported if query is executed from IgniteRDD (cherry picked from commit f2b390a)

Posted by dm...@apache.org.
IGNITE-3175 BigDecimal fields are not supported if query is executed from IgniteRDD
(cherry picked from commit f2b390a)


Project: http://git-wip-us.apache.org/repos/asf/ignite/repo
Commit: http://git-wip-us.apache.org/repos/asf/ignite/commit/40a27e71
Tree: http://git-wip-us.apache.org/repos/asf/ignite/tree/40a27e71
Diff: http://git-wip-us.apache.org/repos/asf/ignite/diff/40a27e71

Branch: refs/heads/master
Commit: 40a27e714d0bf62a26a35c90c68a020dbf0256c7
Parents: 1ebbd57
Author: sboikov <sb...@gridgain.com>
Authored: Mon May 23 07:28:55 2016 +0300
Committer: tledkov-gridgain <tl...@gridgain.com>
Committed: Mon May 23 10:39:44 2016 +0300

----------------------------------------------------------------------
 .../org/apache/ignite/spark/IgniteRDD.scala     |  1 +
 .../spark/JavaStandaloneIgniteRDDSelfTest.java  | 60 +++++++++++++++++++-
 .../ignite/spark/EntityTestAllTypeFields.scala  | 57 +++++++++++++++++++
 3 files changed, 116 insertions(+), 2 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/40a27e71/modules/spark/src/main/scala/org/apache/ignite/spark/IgniteRDD.scala
----------------------------------------------------------------------
diff --git a/modules/spark/src/main/scala/org/apache/ignite/spark/IgniteRDD.scala b/modules/spark/src/main/scala/org/apache/ignite/spark/IgniteRDD.scala
index 2146acb..9112040 100644
--- a/modules/spark/src/main/scala/org/apache/ignite/spark/IgniteRDD.scala
+++ b/modules/spark/src/main/scala/org/apache/ignite/spark/IgniteRDD.scala
@@ -220,6 +220,7 @@ class IgniteRDD[K, V] (
         case "java.lang.Long" \u21d2 LongType
         case "java.lang.Float" \u21d2 FloatType
         case "java.lang.Double" \u21d2 DoubleType
+        case "java.math.BigDecimal" \u21d2 DecimalType.SYSTEM_DEFAULT
         case "java.lang.String" \u21d2 StringType
         case "java.util.Date" \u21d2 DateType
         case "java.sql.Timestamp" \u21d2 TimestampType

http://git-wip-us.apache.org/repos/asf/ignite/blob/40a27e71/modules/spark/src/test/java/org/apache/ignite/spark/JavaStandaloneIgniteRDDSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/spark/src/test/java/org/apache/ignite/spark/JavaStandaloneIgniteRDDSelfTest.java b/modules/spark/src/test/java/org/apache/ignite/spark/JavaStandaloneIgniteRDDSelfTest.java
index faa8fda..e600c6c 100644
--- a/modules/spark/src/test/java/org/apache/ignite/spark/JavaStandaloneIgniteRDDSelfTest.java
+++ b/modules/spark/src/test/java/org/apache/ignite/spark/JavaStandaloneIgniteRDDSelfTest.java
@@ -17,7 +17,6 @@
 
 package org.apache.ignite.spark;
 
-import java.util.List;
 import org.apache.ignite.Ignite;
 import org.apache.ignite.IgniteCache;
 import org.apache.ignite.Ignition;
@@ -28,6 +27,7 @@ import org.apache.ignite.lang.IgniteOutClosure;
 import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi;
 import org.apache.ignite.spi.discovery.tcp.ipfinder.TcpDiscoveryIpFinder;
 import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder;
+import org.apache.ignite.testframework.GridTestUtils;
 import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
 import org.apache.spark.api.java.JavaRDD;
 import org.apache.spark.api.java.JavaSparkContext;
@@ -39,6 +39,10 @@ import org.apache.spark.sql.DataFrame;
 import org.apache.spark.sql.Row;
 import scala.Tuple2;
 
+import java.lang.reflect.Field;
+import java.math.BigDecimal;
+import java.util.List;
+
 /**
  * Tests for {@link JavaIgniteRDD} (standalone mode).
  */
@@ -85,6 +89,14 @@ public class JavaStandaloneIgniteRDDSelfTest extends GridCommonAbstractTest {
             }
         };
 
+    /** */
+    private static final PairFunction<Integer, String, EntityTestAllTypeFields> INT_TO_ENTITY_ALL_FIELDS_F =
+        new PairFunction<Integer, String, EntityTestAllTypeFields>() {
+            @Override public Tuple2<String, EntityTestAllTypeFields> call(Integer i) throws Exception {
+                return new Tuple2<>(String.valueOf(i), new EntityTestAllTypeFields(i));
+            }
+        };
+
     /** {@inheritDoc} */
     @Override protected void beforeTest() throws Exception {
         Ignition.ignite("grid-0").cache(PARTITIONED_CACHE_NAME).removeAll();
@@ -234,7 +246,50 @@ public class JavaStandaloneIgniteRDDSelfTest extends GridCommonAbstractTest {
         finally {
             sc.stop();
         }
+    }
 
+    /**
+     * @throws Exception If failed.
+     */
+    public void testAllFieldsTypes() throws Exception {
+        JavaSparkContext sc = new JavaSparkContext("local[*]", "test");
+
+        final int cnt = 100;
+
+        try {
+            JavaIgniteContext<String, EntityTestAllTypeFields> ic = new JavaIgniteContext<>(sc, new IgniteConfigProvider());
+
+            JavaIgniteRDD<String, EntityTestAllTypeFields> cache = ic.fromCache(PARTITIONED_CACHE_NAME);
+
+            cache.savePairs(sc.parallelize(F.range(0, cnt), 2).mapToPair(INT_TO_ENTITY_ALL_FIELDS_F));
+
+            EntityTestAllTypeFields e = new EntityTestAllTypeFields(cnt / 2);
+            for(Field f : EntityTestAllTypeFields.class.getDeclaredFields()) {
+                String fieldName = f.getName();
+
+                Object val = GridTestUtils.getFieldValue(e, fieldName);
+
+                DataFrame df = cache.sql(
+                    String.format("select %s from EntityTestAllTypeFields where %s = ?", fieldName, fieldName),
+                    val);
+
+                if (val instanceof BigDecimal) {
+                    Object res = df.collect()[0].get(0);
+
+                    assertTrue(String.format("+++ Fail on %s field", fieldName),
+                        ((Comparable<BigDecimal>)val).compareTo((BigDecimal)res) == 0);
+                }
+                else if (val.getClass().isArray())
+                    assertTrue(String.format("+++ Fail on %s field", fieldName), 1 <= df.count());
+                else
+                    assertEquals(String.format("+++ Fail on %s field", fieldName), val, df.collect()[0].get(0));
+
+                info(String.format("+++ Query on the filed: %s : %s passed", fieldName, f.getType().getSimpleName()));
+            }
+        }
+        finally {
+            sc.stop();
+        }
     }
 
     /**
@@ -269,7 +324,8 @@ public class JavaStandaloneIgniteRDDSelfTest extends GridCommonAbstractTest {
 
         ccfg.setName(PARTITIONED_CACHE_NAME);
 
-        ccfg.setIndexedTypes(String.class, Entity.class);
+        ccfg.setIndexedTypes(String.class, Entity.class,
+            String.class, EntityTestAllTypeFields.class);
 
         return ccfg;
     }

http://git-wip-us.apache.org/repos/asf/ignite/blob/40a27e71/modules/spark/src/test/scala/org/apache/ignite/spark/EntityTestAllTypeFields.scala
----------------------------------------------------------------------
diff --git a/modules/spark/src/test/scala/org/apache/ignite/spark/EntityTestAllTypeFields.scala b/modules/spark/src/test/scala/org/apache/ignite/spark/EntityTestAllTypeFields.scala
new file mode 100644
index 0000000..a936091
--- /dev/null
+++ b/modules/spark/src/test/scala/org/apache/ignite/spark/EntityTestAllTypeFields.scala
@@ -0,0 +1,57 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ignite.spark
+
+import java.lang.Boolean
+import java.sql.Timestamp
+import java.util.Date
+
+import org.apache.ignite.spark.IgniteRDDSpec.ScalarCacheQuerySqlField
+
+class EntityTestAllTypeFields(
+    @ScalarCacheQuerySqlField(index = true) val boolVal: Boolean,
+    @ScalarCacheQuerySqlField(index = true) val byteVal: Byte,
+    @ScalarCacheQuerySqlField(index = true) val shortVal: Short,
+    @ScalarCacheQuerySqlField(index = true) val intVal: Int,
+    @ScalarCacheQuerySqlField(index = true) val longVal: Long,
+    @ScalarCacheQuerySqlField(index = true) val floatVal: Float,
+    @ScalarCacheQuerySqlField(index = true) val doubleVal: Double,
+    @ScalarCacheQuerySqlField(index = true) val strVal: String,
+    @ScalarCacheQuerySqlField(index = true) val dateVal: Date,
+    @ScalarCacheQuerySqlField(index = true) val timestampVal: Timestamp,
+    @ScalarCacheQuerySqlField(index = true) val byteArrVal: Array[Byte],
+    @ScalarCacheQuerySqlField(index = true) val bigDecVal: java.math.BigDecimal
+) extends Serializable {
+    def this(
+        i: Int
+    ) {
+        this(
+            i % 2 == 0,     // Boolean
+            i.toByte,       // Byte
+            i.toShort,      // Short
+            i,              // Int
+            i.toLong,       // Long
+            i,              // Float
+            i,              // Double
+            "name" + i,     // String
+            new Date(i),
+            new Timestamp(i),
+            Array(i.toByte, i.toByte),
+            new java.math.BigDecimal(i.toString))
+    }
+}


[07/17] ignite git commit: ignite-2620 Fixed entry expiration handling (cherry picked from commit 46892c7)

Posted by dm...@apache.org.
ignite-2620 Fixed entry expiration handling
(cherry picked from commit 46892c7)


Project: http://git-wip-us.apache.org/repos/asf/ignite/repo
Commit: http://git-wip-us.apache.org/repos/asf/ignite/commit/07611bd1
Tree: http://git-wip-us.apache.org/repos/asf/ignite/tree/07611bd1
Diff: http://git-wip-us.apache.org/repos/asf/ignite/diff/07611bd1

Branch: refs/heads/master
Commit: 07611bd19beaf73a54f0627a6d8a71c3a1a09874
Parents: 8e49e70
Author: sboikov <sb...@gridgain.com>
Authored: Tue May 24 00:07:05 2016 +0300
Committer: sboikov <sb...@gridgain.com>
Committed: Tue May 24 00:13:12 2016 +0300

----------------------------------------------------------------------
 .../processors/cache/GridCacheEntryEx.java      |   5 +-
 .../processors/cache/GridCacheMapEntry.java     | 393 +++++++++--------
 .../processors/cache/GridCacheSwapManager.java  |  11 +-
 .../processors/cache/GridCacheTtlManager.java   |  21 +-
 .../distributed/dht/GridDhtLocalPartition.java  |   2 +-
 .../continuous/CacheContinuousQueryManager.java |   5 +-
 ...niteCacheExpireAndUpdateConsistencyTest.java | 437 +++++++++++++++++++
 .../IgniteCacheExpiryPolicyAbstractTest.java    |   3 +-
 .../IgniteCacheExpiryPolicyTestSuite.java       |   3 +
 .../CacheOperationsWithExpirationTest.java      | 355 +++++++++++++++
 .../cache/GridCacheOffheapIndexGetSelfTest.java |  48 ++
 .../IgniteCacheWithIndexingTestSuite.java       |   2 +
 12 files changed, 1088 insertions(+), 197 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/07611bd1/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheEntryEx.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheEntryEx.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheEntryEx.java
index e679dfd..da9108c 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheEntryEx.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheEntryEx.java
@@ -910,9 +910,10 @@ public interface GridCacheEntryEx {
      * Callback from ttl processor to cache entry indicating that entry is expired.
      *
      * @param obsoleteVer Version to set obsolete if entry is expired.
-     * @return {@code True} if this entry was obsolete or became obsolete as a result of this call.
+     * @throws GridCacheEntryRemovedException If entry was removed.
+     * @return {@code True} if this entry was expired as a result of this call.
      */
-    public boolean onTtlExpired(GridCacheVersion obsoleteVer);
+    public boolean onTtlExpired(GridCacheVersion obsoleteVer) throws GridCacheEntryRemovedException;
 
     /**
      * @return Time to live, without accounting for transactions or removals.

http://git-wip-us.apache.org/repos/asf/ignite/blob/07611bd1/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheMapEntry.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheMapEntry.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheMapEntry.java
index 718e8a0..4fbe0e6 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheMapEntry.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheMapEntry.java
@@ -479,6 +479,12 @@ public abstract class GridCacheMapEntry extends GridMetadataAwareAdapter impleme
         return unswap(true);
     }
 
+    /** {@inheritDoc} */
+    @Nullable @Override public CacheObject unswap(boolean needVal)
+        throws IgniteCheckedException, GridCacheEntryRemovedException {
+        return unswap(needVal, true);
+    }
+
     /**
      * Unswaps an entry.
      *
@@ -486,13 +492,15 @@ public abstract class GridCacheMapEntry extends GridMetadataAwareAdapter impleme
      * @return Value.
      * @throws IgniteCheckedException If failed.
      */
-    @Nullable @Override public CacheObject unswap(boolean needVal)
+    @Nullable private CacheObject unswap(boolean needVal, boolean checkExpire)
         throws IgniteCheckedException, GridCacheEntryRemovedException {
-        boolean swapEnabled = cctx.swap().swapEnabled();
-
-        if (!swapEnabled && !cctx.isOffHeapEnabled())
+        if (!cctx.isSwapOrOffheapEnabled())
             return null;
 
+        boolean obsolete = false;
+        boolean deferred = false;
+        GridCacheVersion ver0 = null;
+
         synchronized (this) {
             checkObsolete();
 
@@ -509,7 +517,7 @@ public abstract class GridCacheMapEntry extends GridMetadataAwareAdapter impleme
                             flags |= IS_OFFHEAP_PTR_MASK;
 
                             if (needVal) {
-                                CacheObject val = cctx.fromOffheap(offHeapPointer(), false);
+                                CacheObject val = cctx.fromOffheap(e.offheapPointer(), false);
 
                                 e.value(val);
                             }
@@ -528,28 +536,49 @@ public abstract class GridCacheMapEntry extends GridMetadataAwareAdapter impleme
 
                 // If there is a value.
                 if (e != null) {
-                    long delta = e.expireTime() == 0 ? 0 : e.expireTime() - U.currentTimeMillis();
+                    long delta = checkExpire ? (e.expireTime() == 0 ? 0 : e.expireTime() - U.currentTimeMillis()) : 0;
 
-                    if (delta >= 0) {
-                        CacheObject val = e.value();
+                    CacheObject val = e.value();
 
-                        val = cctx.kernalContext().cacheObjects().prepareForCache(val, cctx);
+                    val = cctx.kernalContext().cacheObjects().prepareForCache(val, cctx);
 
-                        // Set unswapped value.
-                        update(val, e.expireTime(), e.ttl(), e.version(), false);
+                    // Set unswapped value.
+                    update(val, e.expireTime(), e.ttl(), e.version(), false);
 
-                        // Must update valPtr again since update() will reset it.
-                        if (cctx.offheapTiered() && e.offheapPointer() > 0)
-                            offHeapPointer(e.offheapPointer());
+                    // Must update valPtr again since update() will reset it.
+                    if (cctx.offheapTiered() && e.offheapPointer() > 0)
+                        offHeapPointer(e.offheapPointer());
 
+                    if (delta >= 0)
                         return val;
+                    else {
+                        CacheObject expiredVal = rawGetOrUnmarshal(false);
+
+                        if (onExpired(expiredVal, null)) {
+                            if (cctx.deferredDelete()) {
+                                deferred = true;
+                                ver0 = ver;
+                            }
+                            else
+                                obsolete = true;
+                        }
                     }
-                    else
-                        clearIndex(e.value());
                 }
             }
         }
 
+        if (obsolete) {
+            onMarkedObsolete();
+
+            cctx.cache().removeEntry(this);
+        }
+
+        if (deferred) {
+            assert ver0 != null;
+
+            cctx.onDeferredDelete(this, ver0);
+        }
+
         return null;
     }
 
@@ -562,20 +591,9 @@ public abstract class GridCacheMapEntry extends GridMetadataAwareAdapter impleme
         if (cctx.isSwapOrOffheapEnabled() && !deletedUnlocked() && (hasValueUnlocked() || swapNeeded) && !detached()) {
             assert Thread.holdsLock(this);
 
-            long expireTime = expireTimeExtras();
+            boolean offheapPtr = hasOffHeapPointer();
 
-            if (expireTime > 0 && U.currentTimeMillis() >= expireTime) { // Don't swap entry if it's expired.
-                // Entry might have been updated.
-                if (cctx.offheapTiered()) {
-                    cctx.swap().removeOffheap(key);
-
-                    offHeapPointer(0);
-                }
-
-                return;
-            }
-
-            if (cctx.offheapTiered() && hasOffHeapPointer() && !swapNeeded) {
+            if (cctx.offheapTiered() && offheapPtr && !swapNeeded) {
                 if (log.isDebugEnabled())
                     log.debug("Value did not change, skip write swap entry: " + this);
 
@@ -605,9 +623,10 @@ public abstract class GridCacheMapEntry extends GridMetadataAwareAdapter impleme
                 valBytes.get2(),
                 ver,
                 ttlExtras(),
-                expireTime,
+                expireTimeExtras(),
                 keyClsLdrId,
-                valClsLdrId);
+                valClsLdrId,
+                !offheapPtr);
 
             flags &= ~IS_SWAPPING_REQUIRED;
 
@@ -646,9 +665,9 @@ public abstract class GridCacheMapEntry extends GridMetadataAwareAdapter impleme
      */
     protected final void releaseSwap() throws IgniteCheckedException {
         if (cctx.isSwapOrOffheapEnabled()) {
-            synchronized (this) {
-                cctx.swap().remove(key());
-            }
+            assert Thread.holdsLock(this);
+
+            cctx.swap().remove(key(), partition());
 
             if (log.isDebugEnabled())
                 log.debug("Removed swap entry [entry=" + this + ']');
@@ -758,132 +777,74 @@ public abstract class GridCacheMapEntry extends GridMetadataAwareAdapter impleme
 
         GridCacheMvccCandidate owner;
 
-        CacheObject old;
-        CacheObject ret = null;
+        CacheObject ret;
 
         GridCacheVersion startVer;
         GridCacheVersion resVer = null;
 
-        boolean expired = false;
-
-        CacheObject expiredVal = null;
-
-        boolean hasOldBytes;
+        boolean obsolete = false;
+        boolean deferred = false;
+        GridCacheVersion ver0 = null;
 
         synchronized (this) {
             checkObsolete();
 
-            // Cache version for optimistic check.
-            startVer = ver;
-
             GridCacheMvcc mvcc = mvccExtras();
 
             owner = mvcc == null ? null : mvcc.anyOwner();
 
-            double delta;
-
-            long expireTime = expireTimeExtras();
-
-            if (expireTime > 0) {
-                delta = expireTime - U.currentTimeMillis();
-
-                if (log.isDebugEnabled())
-                    log.debug("Checked expiration time for entry [timeLeft=" + delta + ", entry=" + this + ']');
-
-                if (delta <= 0)
-                    expired = true;
-            }
-
-            CacheObject val = this.val;
+            boolean valid = valid(tx != null ? tx.topologyVersion() : cctx.affinity().affinityTopologyVersion());
 
-            hasOldBytes = hasOffHeapPointer();
+            CacheObject val;
 
-            if ((unmarshal || isOffHeapValuesOnly()) && !expired && val == null && hasOldBytes)
+            if (valid) {
                 val = rawGetOrUnmarshalUnlocked(tmp);
 
-            boolean valid = valid(tx != null ? tx.topologyVersion() : cctx.affinity().affinityTopologyVersion());
-
-            // Attempt to load from swap.
-            if (val == null && !hasOldBytes && readSwap) {
-                // Only promote when loading initial state.
-                if (isNew() || !valid) {
-                    // If this entry is already expired (expiration time was too low),
-                    // we simply remove from swap and clear index.
-                    if (expired) {
-                        releaseSwap();
-
-                        // Previous value is guaranteed to be null
-                        clearIndex(null);
-                    }
-                    else {
-                        // Read and remove swap entry.
+                if (val == null && readSwap) {
+                    if (isStartVersion()) {
                         if (tmp) {
-                            unswap(false);
+                            unswap(false, false);
 
                             val = rawGetOrUnmarshalUnlocked(true);
                         }
                         else
-                            val = unswap();
+                            val = unswap(true, false);
+                    }
+                }
 
-                        // Recalculate expiration after swap read.
-                        if (expireTime > 0) {
-                            delta = expireTime - U.currentTimeMillis();
+                if (val != null) {
+                    long expireTime = expireTimeExtras();
 
-                            if (log.isDebugEnabled())
-                                log.debug("Checked expiration time for entry [timeLeft=" + delta +
-                                    ", entry=" + this + ']');
+                    if (expireTime > 0 && (expireTime - U.currentTimeMillis() <= 0)) {
+                        if (onExpired((CacheObject)cctx.unwrapTemporary(val), null)) {
+                            val = null;
+                            evt = false;
 
-                            if (delta <= 0)
-                                expired = true;
+                            if (cctx.deferredDelete()) {
+                                deferred = true;
+                                ver0 = ver;
+                            }
+                            else
+                                obsolete = true;
                         }
                     }
                 }
             }
+            else
+                val = null;
 
-            old = expired || !valid ? null : val;
-
-            if (expired) {
-                expiredVal = val;
+            ret = val;
 
-                value(null);
-            }
-
-            if (old == null && !hasOldBytes) {
+            if (ret == null) {
                 if (updateMetrics && cctx.cache().configuration().isStatisticsEnabled())
                     cctx.cache().metrics0().onRead(false);
             }
             else {
                 if (updateMetrics && cctx.cache().configuration().isStatisticsEnabled())
                     cctx.cache().metrics0().onRead(true);
-
-                // Set retVal here for event notification.
-                ret = old;
-            }
-
-            if (evt && expired) {
-                if (cctx.events().isRecordable(EVT_CACHE_OBJECT_EXPIRED)) {
-                    cctx.events().addEvent(partition(),
-                        key,
-                        tx,
-                        owner,
-                        EVT_CACHE_OBJECT_EXPIRED,
-                        null,
-                        false,
-                        expiredVal,
-                        expiredVal != null || hasOldBytes,
-                        subjId,
-                        null,
-                        taskName,
-                        keepBinary);
-                }
-
-                cctx.continuousQueries().onEntryExpired(this, key, expiredVal);
-
-                // No more notifications.
-                evt = false;
             }
 
-            if (evt && !expired && cctx.events().isRecordable(EVT_CACHE_OBJECT_READ)) {
+            if (evt && cctx.events().isRecordable(EVT_CACHE_OBJECT_READ)) {
                 cctx.events().addEvent(
                     partition(),
                     key,
@@ -892,8 +853,8 @@ public abstract class GridCacheMapEntry extends GridMetadataAwareAdapter impleme
                     EVT_CACHE_OBJECT_READ,
                     ret,
                     ret != null,
-                    old,
-                    hasOldBytes || old != null,
+                    ret,
+                    ret != null,
                     subjId,
                     transformClo != null ? transformClo.getClass().getName() : null,
                     taskName,
@@ -912,18 +873,30 @@ public abstract class GridCacheMapEntry extends GridMetadataAwareAdapter impleme
                 if (resVer == null)
                     ret = null;
             }
+
+            // Cache version for optimistic check.
+            startVer = ver;
         }
 
         if (ret != null) {
             assert tmp || !(ret instanceof BinaryObjectOffheapImpl);
+            assert !obsolete;
+            assert !deferred;
 
             // If return value is consistent, then done.
             return retVer ? new T2<>(ret, resVer) : ret;
         }
 
-        boolean loadedFromStore = false;
+        if (obsolete) {
+            onMarkedObsolete();
+
+            throw new GridCacheEntryRemovedException();
+        }
+
+        if (deferred)
+            cctx.onDeferredDelete(this, ver0);
 
-        if (ret == null && readThrough) {
+        if (readThrough) {
             IgniteInternalTx tx0 = null;
 
             if (tx != null && tx.local()) {
@@ -939,10 +912,11 @@ public abstract class GridCacheMapEntry extends GridMetadataAwareAdapter impleme
             Object storeVal = readThrough(tx0, key, false, subjId, taskName);
 
             ret = cctx.toCacheObject(storeVal);
-
-            loadedFromStore = true;
         }
 
+        if (ret == null && !evt)
+            return null;
+
         synchronized (this) {
             long ttl = ttlExtras();
 
@@ -958,9 +932,8 @@ public abstract class GridCacheMapEntry extends GridMetadataAwareAdapter impleme
 
                     long expTime = CU.toExpireTime(ttl);
 
-                    if (loadedFromStore)
-                        // Update indexes before actual write to entry.
-                        updateIndex(ret, expTime, nextVer, prevVal);
+                    // Update indexes before actual write to entry.
+                    updateIndex(ret, expTime, nextVer, prevVal);
 
                     boolean hadValPtr = hasOffHeapPointer();
 
@@ -982,8 +955,8 @@ public abstract class GridCacheMapEntry extends GridMetadataAwareAdapter impleme
                         EVT_CACHE_OBJECT_READ,
                         ret,
                         ret != null,
-                        old,
-                        hasOldBytes,
+                        null,
+                        false,
                         subjId,
                         transformClo != null ? transformClo.getClass().getName() : null,
                         taskName,
@@ -1143,7 +1116,7 @@ public abstract class GridCacheMapEntry extends GridMetadataAwareAdapter impleme
             boolean startVer = isStartVersion();
 
             if (startVer)
-                unswap(retval);
+                unswap(retval, false);
 
             newVer = explicitVer != null ? explicitVer : tx == null ?
                 nextVersion() : tx.writeVersion();
@@ -1558,7 +1531,7 @@ public abstract class GridCacheMapEntry extends GridMetadataAwareAdapter impleme
 
             // Load and remove from swap if it is new.
             if (isNew())
-                unswap(retval);
+                unswap(retval, false);
 
             // Possibly get old value form store.
             old = needVal ? rawGetOrUnmarshalUnlocked(!retval && !isOffHeapValuesOnly()) : val;
@@ -1918,8 +1891,8 @@ public abstract class GridCacheMapEntry extends GridMetadataAwareAdapter impleme
             checkObsolete();
 
             // Load and remove from swap if it is new.
-            if (isNew())
-                unswap(retval);
+            if (isStartVersion())
+                unswap(retval, false);
 
             Object transformClo = null;
 
@@ -2755,19 +2728,31 @@ public abstract class GridCacheMapEntry extends GridMetadataAwareAdapter impleme
     }
 
     /** {@inheritDoc} */
-    @Override public boolean markObsoleteIfEmpty(@Nullable GridCacheVersion ver) throws IgniteCheckedException {
+    @Override public boolean markObsoleteIfEmpty(@Nullable GridCacheVersion obsoleteVer) throws IgniteCheckedException {
         boolean obsolete = false;
         boolean deferred = false;
+        GridCacheVersion ver0 = null;
 
         try {
             synchronized (this) {
                 if (obsoleteVersionExtras() != null)
                     return false;
 
-                if (!hasValueUnlocked() || checkExpired()) {
-                    if (ver == null)
-                        ver = nextVersion();
+                if (hasValueUnlocked()) {
+                    long expireTime = expireTimeExtras();
 
+                    if (expireTime > 0 && (expireTime - U.currentTimeMillis() <= 0)) {
+                        if (onExpired(rawGetOrUnmarshal(false), obsoleteVer)) {
+                            if (cctx.deferredDelete()) {
+                                deferred = true;
+                                ver0 = ver;
+                            }
+                            else
+                                obsolete = true;
+                        }
+                    }
+                }
+                else {
                     if (cctx.deferredDelete() && !isStartVersion() && !detached() && !isInternal()) {
                         if (!deletedUnlocked()) {
                             update(null, 0L, 0L, ver, true);
@@ -2775,10 +2760,15 @@ public abstract class GridCacheMapEntry extends GridMetadataAwareAdapter impleme
                             deletedUnlocked(true);
 
                             deferred = true;
+                            ver0 = ver;
                         }
                     }
-                    else
-                        obsolete = markObsolete0(ver, true, null);
+                    else {
+                        if (obsoleteVer == null)
+                            obsoleteVer = nextVersion();
+
+                        obsolete = markObsolete0(obsoleteVer, true, null);
+                    }
                 }
             }
         }
@@ -2787,7 +2777,7 @@ public abstract class GridCacheMapEntry extends GridMetadataAwareAdapter impleme
                 onMarkedObsolete();
 
             if (deferred)
-                cctx.onDeferredDelete(this, ver);
+                cctx.onDeferredDelete(this, ver0);
         }
 
         return obsolete;
@@ -3412,7 +3402,7 @@ public abstract class GridCacheMapEntry extends GridMetadataAwareAdapter impleme
         throws IgniteCheckedException, GridCacheEntryRemovedException {
         boolean isNew = isStartVersion();
 
-        CacheObject val = isNew ? unswap(true) : rawGetOrUnmarshalUnlocked(false);
+        CacheObject val = isNew ? unswap(true, false) : rawGetOrUnmarshalUnlocked(false);
 
         return new GridCachePlainVersionedEntry<>(cctx.unwrapBinaryIfNeeded(key, keepBinary, true),
             cctx.unwrapBinaryIfNeeded(val, keepBinary, true),
@@ -3655,57 +3645,34 @@ public abstract class GridCacheMapEntry extends GridMetadataAwareAdapter impleme
     }
 
     /** {@inheritDoc} */
-    @Override public boolean onTtlExpired(GridCacheVersion obsoleteVer) {
+    @Override public boolean onTtlExpired(GridCacheVersion obsoleteVer) throws GridCacheEntryRemovedException {
+        assert obsoleteVer != null;
+
         boolean obsolete = false;
         boolean deferred = false;
         GridCacheVersion ver0 = null;
 
         try {
             synchronized (this) {
-                CacheObject expiredVal = saveOldValueUnlocked(false);
-
-                boolean hasOldBytes = hasOffHeapPointer();
-
-                boolean expired = checkExpired();
-
-                if (expired) {
-                    if (!obsolete()) {
-                        if (cctx.deferredDelete() && !detached() && !isInternal()) {
-                            if (!deletedUnlocked()) {
-                                update(null, 0L, 0L, ver0 = ver, true);
+                checkObsolete();
 
-                                deletedUnlocked(true);
+                if (isStartVersion())
+                    unswap(true, false);
 
-                                deferred = true;
-                            }
-                        }
-                        else {
-                            if (markObsolete0(obsoleteVer, true, null))
-                                obsolete = true; // Success, will return "true".
-                        }
-                    }
+                long expireTime = expireTimeExtras();
 
-                    clearIndex(expiredVal);
+                if (expireTime == 0 || (expireTime - U.currentTimeMillis() > 0))
+                    return false;
 
-                    releaseSwap();
+                CacheObject expiredVal = rawGetOrUnmarshal(false);
 
-                    if (cctx.events().isRecordable(EVT_CACHE_OBJECT_EXPIRED)) {
-                        cctx.events().addEvent(partition(),
-                            key,
-                            cctx.localNodeId(),
-                            null,
-                            EVT_CACHE_OBJECT_EXPIRED,
-                            null,
-                            false,
-                            expiredVal,
-                            expiredVal != null || hasOldBytes,
-                            null,
-                            null,
-                            null,
-                            true);
+                if (onExpired(expiredVal, obsoleteVer)) {
+                    if (cctx.deferredDelete()) {
+                        deferred = true;
+                        ver0 = ver;
                     }
-
-                    cctx.continuousQueries().onEntryExpired(this, key, expiredVal);
+                    else
+                        obsolete = true;
                 }
             }
         }
@@ -3729,7 +3696,63 @@ public abstract class GridCacheMapEntry extends GridMetadataAwareAdapter impleme
                 cctx.cache().metrics0().onEvict();
         }
 
-        return obsolete;
+        return true;
+    }
+
+    /**
+     * @param expiredVal Expired value.
+     * @param obsoleteVer Version.
+     * @return {@code True} if entry was marked as removed.
+     * @throws IgniteCheckedException If failed.
+     */
+    private boolean onExpired(CacheObject expiredVal, GridCacheVersion obsoleteVer) throws IgniteCheckedException {
+        assert expiredVal != null;
+
+        boolean rmvd = false;
+
+        if (mvccExtras() != null)
+            return false;
+
+        if (cctx.deferredDelete() && !detached() && !isInternal()) {
+            if (!deletedUnlocked() && !isStartVersion()) {
+                update(null, 0L, 0L, ver, true);
+
+                deletedUnlocked(true);
+
+                rmvd = true;
+            }
+        }
+        else {
+            if (obsoleteVer == null)
+                obsoleteVer = nextVersion();
+
+            if (markObsolete0(obsoleteVer, true, null))
+                rmvd = true;
+        }
+
+        clearIndex(expiredVal);
+
+        releaseSwap();
+
+        if (cctx.events().isRecordable(EVT_CACHE_OBJECT_EXPIRED)) {
+            cctx.events().addEvent(partition(),
+                key,
+                cctx.localNodeId(),
+                null,
+                EVT_CACHE_OBJECT_EXPIRED,
+                null,
+                false,
+                expiredVal,
+                expiredVal != null,
+                null,
+                null,
+                null,
+                true);
+        }
+
+        cctx.continuousQueries().onEntryExpired(this, key, expiredVal);
+
+        return rmvd;
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/07611bd1/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheSwapManager.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheSwapManager.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheSwapManager.java
index 98251dd..f4786be 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheSwapManager.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheSwapManager.java
@@ -1224,9 +1224,10 @@ public class GridCacheSwapManager extends GridCacheManagerAdapter {
 
     /**
      * @param key Key to remove.
+     * @param part Partition.
      * @throws IgniteCheckedException If failed.
      */
-    public void remove(final KeyCacheObject key) throws IgniteCheckedException {
+    public void remove(final KeyCacheObject key, int part) throws IgniteCheckedException {
         if (!offheapEnabled && !swapEnabled)
             return;
 
@@ -1234,8 +1235,6 @@ public class GridCacheSwapManager extends GridCacheManagerAdapter {
 
         final GridCacheQueryManager qryMgr = cctx.queries();
 
-        int part = cctx.affinity().partition(key);
-
         // First try offheap.
         if (offheapEnabled) {
             byte[] keyBytes = key.valueBytes(cctx.cacheObjectContext());
@@ -1282,6 +1281,7 @@ public class GridCacheSwapManager extends GridCacheManagerAdapter {
      * @param expireTime Swap entry expiration time.
      * @param keyClsLdrId Class loader ID for entry key.
      * @param valClsLdrId Class loader ID for entry value.
+     * @param wasUnswapped {@code True} if currently value is removed from swap.
      * @throws IgniteCheckedException If failed.
      */
     void write(KeyCacheObject key,
@@ -1291,7 +1291,8 @@ public class GridCacheSwapManager extends GridCacheManagerAdapter {
         long ttl,
         long expireTime,
         @Nullable IgniteUuid keyClsLdrId,
-        @Nullable IgniteUuid valClsLdrId)
+        @Nullable IgniteUuid valClsLdrId,
+        boolean wasUnswapped)
         throws IgniteCheckedException {
         if (!offheapEnabled && !swapEnabled)
             return;
@@ -1323,7 +1324,7 @@ public class GridCacheSwapManager extends GridCacheManagerAdapter {
 
         GridCacheQueryManager qryMgr = cctx.queries();
 
-        if (qryMgr.enabled())
+        if (wasUnswapped && qryMgr.enabled())
             qryMgr.onSwap(key);
     }
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/07611bd1/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheTtlManager.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheTtlManager.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheTtlManager.java
index 4e1fc6d..3e4561b 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheTtlManager.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheTtlManager.java
@@ -128,7 +128,26 @@ public class GridCacheTtlManager extends GridCacheManagerAdapter {
                 if (log.isTraceEnabled())
                     log.trace("Trying to remove expired entry from cache: " + e);
 
-                e.entry.onTtlExpired(obsoleteVer);
+                GridCacheEntryEx entry = e.entry;
+
+                boolean touch = false;
+
+                while (true) {
+                    try {
+                        if (entry.onTtlExpired(obsoleteVer))
+                            touch = false;
+
+                        break;
+                    }
+                    catch (GridCacheEntryRemovedException e0) {
+                        entry = entry.context().cache().entryEx(entry.key());
+
+                        touch = true;
+                    }
+                }
+
+                if (touch)
+                    entry.context().evicts().touch(entry, null);
             }
         }
     }

http://git-wip-us.apache.org/repos/asf/ignite/blob/07611bd1/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtLocalPartition.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtLocalPartition.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtLocalPartition.java
index 3ac4a41..f587adb 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtLocalPartition.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtLocalPartition.java
@@ -584,7 +584,7 @@ public class GridDhtLocalPartition implements Comparable<GridDhtLocalPartition>,
 
                     KeyCacheObject key = cctx.toCacheKeyObject(keyBytes);
 
-                    cctx.swap().remove(key);
+                    cctx.swap().remove(key, id);
 
                     if (isLocStore)
                         cctx.store().remove(null, key.value(cctx.cacheObjectContext(), false));

http://git-wip-us.apache.org/repos/asf/ignite/blob/07611bd1/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/continuous/CacheContinuousQueryManager.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/continuous/CacheContinuousQueryManager.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/continuous/CacheContinuousQueryManager.java
index fafb830..b042249 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/continuous/CacheContinuousQueryManager.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/continuous/CacheContinuousQueryManager.java
@@ -363,8 +363,9 @@ public class CacheContinuousQueryManager extends GridCacheManagerAdapter {
         if (F.isEmpty(lsnrCol))
             return;
 
-        if (cctx.isReplicated() || cctx.affinity().primary(cctx.localNode(), key, AffinityTopologyVersion.NONE)) {
-            boolean primary = cctx.affinity().primary(cctx.localNode(), key, AffinityTopologyVersion.NONE);
+        boolean primary = cctx.affinity().primary(cctx.localNode(), e.partition(), AffinityTopologyVersion.NONE);
+
+        if (cctx.isReplicated() || primary) {
             boolean recordIgniteEvt = cctx.gridEvents().isRecordable(EVT_CACHE_QUERY_OBJECT_READ);
 
             boolean initialized = false;

http://git-wip-us.apache.org/repos/asf/ignite/blob/07611bd1/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCacheExpireAndUpdateConsistencyTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCacheExpireAndUpdateConsistencyTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCacheExpireAndUpdateConsistencyTest.java
new file mode 100644
index 0000000..7f54a83
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCacheExpireAndUpdateConsistencyTest.java
@@ -0,0 +1,437 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ignite.internal.processors.cache;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.atomic.AtomicInteger;
+import javax.cache.event.CacheEntryEvent;
+import javax.cache.event.CacheEntryUpdatedListener;
+import javax.cache.expiry.CreatedExpiryPolicy;
+import javax.cache.expiry.Duration;
+import org.apache.ignite.Ignite;
+import org.apache.ignite.IgniteCache;
+import org.apache.ignite.IgniteTransactions;
+import org.apache.ignite.cache.CacheAtomicityMode;
+import org.apache.ignite.cache.CacheMemoryMode;
+import org.apache.ignite.cache.query.ContinuousQuery;
+import org.apache.ignite.configuration.CacheConfiguration;
+import org.apache.ignite.configuration.IgniteConfiguration;
+import org.apache.ignite.internal.util.typedef.F;
+import org.apache.ignite.internal.util.typedef.PA;
+import org.apache.ignite.internal.util.typedef.T2;
+import org.apache.ignite.internal.util.typedef.internal.S;
+import org.apache.ignite.internal.util.typedef.internal.U;
+import org.apache.ignite.lang.IgniteInClosure;
+import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi;
+import org.apache.ignite.spi.discovery.tcp.ipfinder.TcpDiscoveryIpFinder;
+import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder;
+import org.apache.ignite.testframework.GridTestUtils;
+import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
+import org.apache.ignite.transactions.Transaction;
+
+import static java.util.concurrent.TimeUnit.SECONDS;
+import static org.apache.ignite.cache.CacheAtomicityMode.ATOMIC;
+import static org.apache.ignite.cache.CacheAtomicityMode.TRANSACTIONAL;
+import static org.apache.ignite.cache.CacheMemoryMode.OFFHEAP_TIERED;
+import static org.apache.ignite.cache.CacheMemoryMode.ONHEAP_TIERED;
+import static org.apache.ignite.cache.CacheMode.PARTITIONED;
+import static org.apache.ignite.cache.CacheWriteSynchronizationMode.FULL_SYNC;
+import static org.apache.ignite.transactions.TransactionConcurrency.PESSIMISTIC;
+import static org.apache.ignite.transactions.TransactionIsolation.REPEATABLE_READ;
+
+/**
+ *
+ */
+public class IgniteCacheExpireAndUpdateConsistencyTest extends GridCommonAbstractTest {
+    /** */
+    private static final TcpDiscoveryIpFinder IP_FINDER = new TcpDiscoveryVmIpFinder(true);
+
+    /** */
+    private boolean client;
+
+    /** */
+    private static final int NODES = 5;
+
+    /** {@inheritDoc} */
+    @Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception {
+        IgniteConfiguration cfg = super.getConfiguration(gridName);
+
+        ((TcpDiscoverySpi)cfg.getDiscoverySpi()).setIpFinder(IP_FINDER);
+
+        cfg.setClientMode(client);
+
+        return cfg;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void beforeTestsStarted() throws Exception {
+        super.beforeTestsStarted();
+
+        startGridsMultiThreaded(4);
+
+        client = true;
+
+        Ignite client = startGrid(4);
+
+        assertTrue(client.configuration().isClientMode());
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testAtomic1() throws Exception {
+        updateAndEventConsistencyTest(cacheConfiguration(ATOMIC, ONHEAP_TIERED, 0));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testAtomic2() throws Exception {
+        updateAndEventConsistencyTest(cacheConfiguration(ATOMIC, ONHEAP_TIERED, 1));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testAtomic3() throws Exception {
+        updateAndEventConsistencyTest(cacheConfiguration(ATOMIC, ONHEAP_TIERED, 2));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testAtomicOffheap() throws Exception {
+        updateAndEventConsistencyTest(cacheConfiguration(ATOMIC, OFFHEAP_TIERED, 1));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testTx1() throws Exception {
+        updateAndEventConsistencyTest(cacheConfiguration(TRANSACTIONAL, ONHEAP_TIERED, 0));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testTx2() throws Exception {
+        updateAndEventConsistencyTest(cacheConfiguration(TRANSACTIONAL, ONHEAP_TIERED, 1));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testTx3() throws Exception {
+        updateAndEventConsistencyTest(cacheConfiguration(TRANSACTIONAL, ONHEAP_TIERED, 2));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testTxOffheap() throws Exception {
+        updateAndEventConsistencyTest(cacheConfiguration(TRANSACTIONAL, OFFHEAP_TIERED, 1));
+    }
+
+    /**
+     * @param ccfg Cache configuration.
+     * @throws Exception If failed.
+     */
+    @SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter")
+    private void updateAndEventConsistencyTest(CacheConfiguration<TestKey, TestValue> ccfg) throws Exception {
+        ignite(0).createCache(ccfg);
+
+        try {
+            List<ConcurrentMap<TestKey, List<T2<TestValue, TestValue>>>> nodesEvts = new ArrayList<>();
+
+            for (int i = 0; i < NODES; i++) {
+                Ignite ignite = ignite(i);
+
+                IgniteCache<TestKey, TestValue> cache = ignite.cache(ccfg.getName());
+
+                ContinuousQuery<TestKey, TestValue> qry = new ContinuousQuery<>();
+
+                final ConcurrentMap<TestKey, List<T2<TestValue, TestValue>>> allEvts = new ConcurrentHashMap<>();
+
+                qry.setLocalListener(new CacheEntryUpdatedListener<TestKey, TestValue>() {
+                    @Override public void onUpdated(Iterable<CacheEntryEvent<? extends TestKey, ? extends TestValue>> evts) {
+                        for (CacheEntryEvent<? extends TestKey, ? extends TestValue> e : evts) {
+                            List<T2<TestValue, TestValue>> keyEvts = allEvts.get(e.getKey());
+
+                            if (keyEvts == null) {
+                                List<T2<TestValue, TestValue>> old =
+                                    allEvts.putIfAbsent(e.getKey(), keyEvts = new ArrayList<>());
+
+                                assertNull(old);
+                            }
+
+                            synchronized (keyEvts) {
+                                keyEvts.add(new T2<>(e.getValue(), e.getOldValue()));
+                            }
+                        }
+                    }
+                });
+
+                cache.query(qry);
+
+                nodesEvts.add(allEvts);
+            }
+
+            final AtomicInteger keyVal = new AtomicInteger();
+
+            for (int i = 0; i < NODES; i++) {
+                Ignite ignite = ignite(i);
+
+                log.info("Test with node: " + ignite.name());
+
+                updateAndEventConsistencyTest(ignite, ccfg.getName(), keyVal, nodesEvts, false);
+
+                if (ccfg.getAtomicityMode() == TRANSACTIONAL)
+                    updateAndEventConsistencyTest(ignite, ccfg.getName(), keyVal, nodesEvts, true);
+            }
+        }
+        finally {
+            ignite(0).destroyCache(ccfg.getName());
+        }
+    }
+
+    /**
+     * @param node Node.
+     * @param cacheName Cache name.
+     * @param keyVal Key counter.
+     * @param nodesEvts Events map.
+     * @param useTx If {@code true} executes update with explicit transaction.
+     * @throws Exception If failed.
+     */
+    private void updateAndEventConsistencyTest(final Ignite node,
+        String cacheName,
+        final AtomicInteger keyVal,
+        List<ConcurrentMap<TestKey, List<T2<TestValue, TestValue>>>> nodesEvts,
+        final boolean useTx) throws Exception {
+        final ConcurrentMap<TestKey, List<T2<TestValue, TestValue>>> updates = new ConcurrentHashMap<>();
+
+        final int THREADS = 5;
+        final int KEYS_PER_THREAD = 100;
+
+        final IgniteCache<TestKey, TestValue> cache = node.cache(cacheName);
+
+        final IgniteCache<TestKey, TestValue> expPlcCache =
+            cache.withExpiryPolicy(new CreatedExpiryPolicy(new Duration(SECONDS, 2)));
+
+        GridTestUtils.runMultiThreaded(new IgniteInClosure<Integer>() {
+            @Override public void apply(Integer idx) {
+                List<TestKey> keys = new ArrayList<>();
+
+                for (int i = 0; i < KEYS_PER_THREAD; i++)
+                    keys.add(new TestKey(keyVal.incrementAndGet()));
+
+                for (TestKey key : keys) {
+                    expPlcCache.put(key, new TestValue(0));
+
+                    List<T2<TestValue, TestValue>> keyUpdates = new ArrayList<>();
+
+                    keyUpdates.add(new T2<>(new TestValue(0), (TestValue)null));
+
+                    updates.put(key, keyUpdates);
+                }
+
+                long stopTime = U.currentTimeMillis() + 10_000;
+
+                int val = 0;
+
+                Set<TestKey> expired = new HashSet<>();
+
+                IgniteTransactions txs = node.transactions();
+
+                while (U.currentTimeMillis() < stopTime) {
+                    val++;
+
+                    TestValue newVal = new TestValue(val);
+
+                    for (TestKey key : keys) {
+                        Transaction tx = useTx ? txs.txStart(PESSIMISTIC, REPEATABLE_READ) : null;
+
+                        TestValue oldVal = cache.getAndPut(key, newVal);
+
+                        if (tx != null)
+                            tx.commit();
+
+                        List<T2<TestValue, TestValue>> keyUpdates = updates.get(key);
+
+                        keyUpdates.add(new T2<>(newVal, oldVal));
+
+                        if (oldVal == null)
+                            expired.add(key);
+                    }
+
+                    if (expired.size() == keys.size())
+                        break;
+                }
+
+                assertEquals(keys.size(), expired.size());
+            }
+        }, THREADS, "update-thread");
+
+        for (ConcurrentMap<TestKey, List<T2<TestValue, TestValue>>> evts : nodesEvts)
+            checkEvents(updates, evts);
+
+        nodesEvts.clear();
+    }
+
+    /**
+     * @param updates Cache update.
+     * @param evts Received events.
+     * @throws Exception If failed.
+     */
+    @SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter")
+    private void checkEvents(ConcurrentMap<TestKey, List<T2<TestValue, TestValue>>> updates,
+        final ConcurrentMap<TestKey, List<T2<TestValue, TestValue>>> evts) throws Exception {
+        for (final TestKey key : updates.keySet()) {
+            final List<T2<TestValue, TestValue>> keyUpdates = updates.get(key);
+
+            assert(!F.isEmpty(keyUpdates));
+
+            GridTestUtils.waitForCondition(new PA() {
+                @Override public boolean apply() {
+                    List<T2<TestValue, TestValue>> keyEvts = evts.get(key);
+
+                    if (keyEvts == null)
+                        return false;
+
+                    synchronized (keyEvts) {
+                        return keyEvts.size() == keyUpdates.size();
+                    }
+                }
+            }, 5000);
+
+            List<T2<TestValue, TestValue>> keyEvts = evts.get(key);
+
+            assertNotNull(keyEvts);
+
+            for (int i = 0; i < keyUpdates.size(); i++) {
+                T2<TestValue, TestValue> update = keyUpdates.get(i);
+                T2<TestValue, TestValue> evt = keyEvts.get(i);
+
+                assertEquals(update.get1(), evt.get1());
+                assertEquals(update.get2(), evt.get2());
+            }
+        }
+    }
+
+    /**
+     * @param atomicityMode Cache atomicity mode.
+     * @param memoryMode Cache memory mode.
+     * @param backups Number of backups.
+     * @return Cache configuration.
+     */
+    private CacheConfiguration<TestKey, TestValue> cacheConfiguration(CacheAtomicityMode atomicityMode,
+        CacheMemoryMode memoryMode,
+        int backups) {
+        CacheConfiguration<TestKey, TestValue> ccfg = new CacheConfiguration<>();
+
+        ccfg.setCacheMode(PARTITIONED);
+        ccfg.setAtomicityMode(atomicityMode);
+        ccfg.setMemoryMode(memoryMode);
+        ccfg.setWriteSynchronizationMode(FULL_SYNC);
+        ccfg.setBackups(backups);
+
+        return ccfg;
+    }
+
+    /**
+     *
+     */
+    static class TestKey implements Serializable {
+        /** */
+        private int key;
+
+        /**
+         * @param key Key.
+         */
+        public TestKey(int key) {
+            this.key = key;
+        }
+
+        /** {@inheritDoc} */
+        @Override public boolean equals(Object o) {
+            if (this == o)
+                return true;
+
+            if (o == null || getClass() != o.getClass())
+                return false;
+
+            TestKey testKey = (TestKey)o;
+
+            return key == testKey.key;
+
+        }
+
+        /** {@inheritDoc} */
+        @Override public int hashCode() {
+            return key;
+        }
+
+        /** {@inheritDoc} */
+        @Override public String toString() {
+            return S.toString(TestKey.class, this);
+        }
+    }
+
+    /**
+     *
+     */
+    static class TestValue implements Serializable {
+        /** */
+        private int val;
+
+        /**
+         * @param val Value.
+         */
+        public TestValue(int val) {
+            this.val = val;
+        }
+
+        /** {@inheritDoc} */
+        @Override public String toString() {
+            return S.toString(TestValue.class, this);
+        }
+
+        /** {@inheritDoc} */
+        @Override public boolean equals(Object o) {
+            if (this == o)
+                return true;
+
+            if (o == null || getClass() != o.getClass())
+                return false;
+
+            TestValue testVal = (TestValue)o;
+
+            return val == testVal.val;
+        }
+
+        /** {@inheritDoc} */
+        @Override public int hashCode() {
+            return val;
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/07611bd1/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/expiry/IgniteCacheExpiryPolicyAbstractTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/expiry/IgniteCacheExpiryPolicyAbstractTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/expiry/IgniteCacheExpiryPolicyAbstractTest.java
index f4cc025..794519a 100644
--- a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/expiry/IgniteCacheExpiryPolicyAbstractTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/expiry/IgniteCacheExpiryPolicyAbstractTest.java
@@ -1124,7 +1124,8 @@ public abstract class IgniteCacheExpiryPolicyAbstractTest extends IgniteCacheAbs
                     if (e != null && e.deleted()) {
                         assertEquals(0, e.ttl());
 
-                        assertFalse(cache.affinity().isPrimaryOrBackup(grid.localNode(), key));
+                        assertFalse("Invalid entry [e=" + e + ", node=" + i + ']',
+                            cache.affinity().isPrimaryOrBackup(grid.localNode(), key));
 
                         continue;
                     }

http://git-wip-us.apache.org/repos/asf/ignite/blob/07611bd1/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/expiry/IgniteCacheExpiryPolicyTestSuite.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/expiry/IgniteCacheExpiryPolicyTestSuite.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/expiry/IgniteCacheExpiryPolicyTestSuite.java
index aa3339f..21935e5 100644
--- a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/expiry/IgniteCacheExpiryPolicyTestSuite.java
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/expiry/IgniteCacheExpiryPolicyTestSuite.java
@@ -20,6 +20,7 @@ package org.apache.ignite.internal.processors.cache.expiry;
 import junit.framework.TestSuite;
 import org.apache.ignite.cache.store.IgniteCacheExpiryStoreLoadSelfTest;
 import org.apache.ignite.internal.processors.cache.IgniteCacheEntryListenerExpiredEventsTest;
+import org.apache.ignite.internal.processors.cache.IgniteCacheExpireAndUpdateConsistencyTest;
 
 /**
  *
@@ -68,6 +69,8 @@ public class IgniteCacheExpiryPolicyTestSuite extends TestSuite {
 
         suite.addTestSuite(IgniteCacheEntryListenerExpiredEventsTest.class);
 
+        suite.addTestSuite(IgniteCacheExpireAndUpdateConsistencyTest.class);
+
         return suite;
     }
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ignite/blob/07611bd1/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/CacheOperationsWithExpirationTest.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/CacheOperationsWithExpirationTest.java b/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/CacheOperationsWithExpirationTest.java
new file mode 100644
index 0000000..6c60586
--- /dev/null
+++ b/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/CacheOperationsWithExpirationTest.java
@@ -0,0 +1,355 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ignite.internal.processors.cache;
+
+import java.io.Serializable;
+import java.util.Date;
+import java.util.List;
+import java.util.Set;
+import java.util.TreeSet;
+import java.util.concurrent.ThreadLocalRandom;
+import javax.cache.expiry.Duration;
+import javax.cache.expiry.ModifiedExpiryPolicy;
+import org.apache.ignite.Ignite;
+import org.apache.ignite.IgniteCache;
+import org.apache.ignite.cache.CacheAtomicityMode;
+import org.apache.ignite.cache.CacheMemoryMode;
+import org.apache.ignite.cache.query.SqlFieldsQuery;
+import org.apache.ignite.cache.query.annotations.QuerySqlField;
+import org.apache.ignite.configuration.CacheConfiguration;
+import org.apache.ignite.internal.util.typedef.F;
+import org.apache.ignite.internal.util.typedef.internal.U;
+import org.apache.ignite.lang.IgniteInClosure;
+import org.apache.ignite.testframework.GridTestUtils;
+import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
+
+import static java.util.concurrent.TimeUnit.MILLISECONDS;
+import static org.apache.ignite.cache.CacheAtomicWriteOrderMode.PRIMARY;
+import static org.apache.ignite.cache.CacheAtomicityMode.ATOMIC;
+import static org.apache.ignite.cache.CacheAtomicityMode.TRANSACTIONAL;
+import static org.apache.ignite.cache.CacheMemoryMode.OFFHEAP_TIERED;
+import static org.apache.ignite.cache.CacheMemoryMode.ONHEAP_TIERED;
+import static org.apache.ignite.cache.CacheWriteSynchronizationMode.PRIMARY_SYNC;
+
+/**
+ *
+ */
+public class CacheOperationsWithExpirationTest extends GridCommonAbstractTest {
+    /** */
+    private static final int KEYS = 10_000;
+
+    /**
+     * @param atomicityMode Atomicity mode.
+     * @param memoryMode Memory mode.
+     * @param offheapMem Offheap memory size.
+     * @param idx Indexing enabled flag.
+     * @return Cache configuration.
+     */
+    private CacheConfiguration<String, TestIndexedType> cacheConfiguration(CacheAtomicityMode atomicityMode,
+        CacheMemoryMode memoryMode,
+        long offheapMem,
+        boolean idx) {
+        CacheConfiguration<String, TestIndexedType> ccfg = new CacheConfiguration<>();
+
+        ccfg.setAtomicityMode(atomicityMode);
+        ccfg.setMemoryMode(memoryMode);
+        ccfg.setOffHeapMaxMemory(offheapMem);
+        ccfg.setSwapEnabled(false);
+        ccfg.setBackups(1);
+        ccfg.setAtomicWriteOrderMode(PRIMARY);
+        ccfg.setWriteSynchronizationMode(PRIMARY_SYNC);
+        ccfg.setStatisticsEnabled(true);
+
+        if (idx)
+            ccfg.setIndexedTypes(String.class, TestIndexedType.class);
+
+        return ccfg;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void beforeTestsStarted() throws Exception {
+        super.beforeTestsStarted();
+
+        startGrid(0);
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void afterTestsStopped() throws Exception {
+        stopAllGrids();
+
+        super.afterTestsStopped();
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testAtomicOffheapLimitedIndexEnabled() throws Exception {
+        concurrentPutGetRemoveExpireAndQuery(cacheConfiguration(ATOMIC, OFFHEAP_TIERED, 1024 * 1024, true));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testAtomicOffheapIndexEnabled() throws Exception {
+        concurrentPutGetRemoveExpireAndQuery(cacheConfiguration(ATOMIC, OFFHEAP_TIERED, 0, true));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testAtomicIndexEnabled() throws Exception {
+        concurrentPutGetRemoveExpireAndQuery(cacheConfiguration(ATOMIC, ONHEAP_TIERED, 0, true));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testTxOffheapLimitedIndexEnabled() throws Exception {
+        concurrentPutGetRemoveExpireAndQuery(cacheConfiguration(TRANSACTIONAL, OFFHEAP_TIERED, 1024 * 1024, true));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testTxOffheapIndexEnabled() throws Exception {
+        concurrentPutGetRemoveExpireAndQuery(cacheConfiguration(TRANSACTIONAL, OFFHEAP_TIERED, 0, true));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testAtomicOffheapLimited() throws Exception {
+        concurrentPutGetRemoveExpireAndQuery(cacheConfiguration(ATOMIC, OFFHEAP_TIERED, 1024 * 1024, false));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testAtomicOffheap() throws Exception {
+        concurrentPutGetRemoveExpireAndQuery(cacheConfiguration(ATOMIC, OFFHEAP_TIERED, 0, false));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testAtomic() throws Exception {
+        concurrentPutGetRemoveExpireAndQuery(cacheConfiguration(ATOMIC, ONHEAP_TIERED, 0, false));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testTxOffheapLimited() throws Exception {
+        concurrentPutGetRemoveExpireAndQuery(cacheConfiguration(TRANSACTIONAL, OFFHEAP_TIERED, 1024 * 1024, false));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testTxOffheap() throws Exception {
+        concurrentPutGetRemoveExpireAndQuery(cacheConfiguration(TRANSACTIONAL, OFFHEAP_TIERED, 0, false));
+    }
+
+    /**
+     * @param ccfg Cache configuration.
+     * @throws Exception If failed.
+     */
+    private void concurrentPutGetRemoveExpireAndQuery(CacheConfiguration<String, TestIndexedType> ccfg)
+        throws Exception {
+        Ignite ignite = ignite(0);
+
+        final IgniteCache<String, TestIndexedType> cache = ignite.createCache(ccfg);
+
+        final boolean qryEnabled = !F.isEmpty(ccfg.getQueryEntities());
+
+        try {
+            final long stopTime = U.currentTimeMillis() + 30_000;
+
+            GridTestUtils.runMultiThreaded(new IgniteInClosure<Integer>() {
+                @Override public void apply(Integer idx) {
+                    while (U.currentTimeMillis() < stopTime) {
+                        if (!qryEnabled || idx % 2 == 0)
+                            putGet(cache);
+                        else
+                            query(cache);
+                    }
+                }
+
+                void putGet(IgniteCache<String, TestIndexedType> cache) {
+                    ThreadLocalRandom rnd = ThreadLocalRandom.current();
+
+                    cache = cache.withExpiryPolicy(new ModifiedExpiryPolicy(
+                        new Duration(MILLISECONDS, rnd.nextLong(100) + 1)));
+
+                    for (int i = 0; i < KEYS; i++) {
+                        String key = String.valueOf(rnd.nextInt(KEYS));
+
+                        cache.put(key, testValue(rnd));
+                    }
+
+                    Set<String> s = new TreeSet<>();
+
+                    for (int i = 0; i < 1000; i++) {
+                        String key = String.valueOf(rnd.nextInt(KEYS));
+
+                        s.add(key);
+                    }
+
+                    cache.getAll(s);
+
+                    cache.removeAll(s);
+                }
+
+                void query(IgniteCache<String, TestIndexedType> cache) {
+                    ThreadLocalRandom rnd = ThreadLocalRandom.current();
+
+                    String k = String.valueOf(rnd.nextInt(KEYS));
+
+                    SqlFieldsQuery qry1;
+
+                    if (rnd.nextBoolean()) {
+                        qry1 = new SqlFieldsQuery("select _key, _val from TestIndexedType where key1=? and intVal=?");
+
+                        qry1.setArgs(k, k);
+                    }
+                    else
+                        qry1 = new SqlFieldsQuery("select _key, _val from TestIndexedType");
+
+                    List res = cache.query(qry1).getAll();
+
+                    assertNotNull(res);
+                }
+            }, 10, "test-thread");
+        }
+        finally {
+            ignite.destroyCache(cache.getName());
+        }
+    }
+
+    /**
+     * @param rnd Random.
+     * @return Test value.
+     */
+    private TestIndexedType testValue(ThreadLocalRandom rnd) {
+        StringBuilder builder = new StringBuilder();
+
+        for (int i = 0; i < rnd.nextInt(100); i++)
+            builder.append("string");
+
+        return new TestIndexedType(rnd.nextInt(KEYS), builder.toString());
+    }
+
+    /**
+     *
+     */
+    public enum EnumType1 {
+        /** */
+        TYPE1,
+        /** */
+        TYPE2,
+        /** */
+        TYPE3;
+
+        /** */
+        static final EnumType1[] vals = EnumType1.values();
+    }
+
+    /**
+     *
+     */
+    public enum EnumType2 {
+        /** */
+        TYPE1,
+        /** */
+        TYPE2,
+        /** */
+        TYPE3,
+        /** */
+        TYPE4;
+
+        /** */
+        static final EnumType2[] vals = EnumType2.values();
+    }
+
+    /**
+     *
+     */
+    public static class TestIndexedType implements Serializable {
+        /** */
+        private static final long serialVersionUID = 1L;
+
+        /** */
+        @QuerySqlField
+        private final String key;
+
+        /** */
+        @QuerySqlField(index = true)
+        private final String key1;
+
+        /** */
+        @QuerySqlField(index = true)
+        private final String key2;
+
+        /** */
+        @QuerySqlField(index = true)
+        private final String key3;
+
+        /** */
+        @QuerySqlField(index = true)
+        private final int intVal;
+
+        /** */
+        private final EnumType1 type1;
+
+        /** */
+        @QuerySqlField(index = true)
+        private final EnumType2 type2;
+
+        /** */
+        @QuerySqlField(index = true)
+        private final Date date1;
+
+        /** */
+        @QuerySqlField(index = true)
+        private final Date date2;
+
+        /** */
+        private final Byte byteVal1;
+
+        /** */
+        private final Byte byteVal2;
+
+        /**
+         * @param rnd Random value.
+         * @param strVal Random string value.
+         */
+        public TestIndexedType(int rnd, String strVal) {
+            intVal = rnd;
+            key = String.valueOf(rnd);
+            key1 = key;
+            key2 = strVal;
+            key3 = strVal;
+            date1 = new Date(rnd);
+            date2 = new Date(U.currentTimeMillis());
+            type1 = EnumType1.vals[rnd % EnumType1.vals.length];
+            type2 = EnumType2.vals[rnd % EnumType2.vals.length];
+            byteVal1 = (byte)rnd;
+            byteVal2 = (byte)rnd;
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/07611bd1/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/GridCacheOffheapIndexGetSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/GridCacheOffheapIndexGetSelfTest.java b/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/GridCacheOffheapIndexGetSelfTest.java
index 02c4312..2fbde41 100644
--- a/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/GridCacheOffheapIndexGetSelfTest.java
+++ b/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/GridCacheOffheapIndexGetSelfTest.java
@@ -22,6 +22,8 @@ import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 import javax.cache.Cache;
+import javax.cache.expiry.Duration;
+import javax.cache.expiry.ExpiryPolicy;
 import org.apache.ignite.IgniteCache;
 import org.apache.ignite.cache.query.SqlQuery;
 import org.apache.ignite.cache.query.annotations.QuerySqlField;
@@ -156,6 +158,52 @@ public class GridCacheOffheapIndexGetSelfTest extends GridCommonAbstractTest {
     }
 
     /**
+     * @throws Exception If failed.
+     */
+    public void testWithExpiryPolicy() throws Exception {
+        IgniteCache<Long, Long> cache = grid(0).cache(null);
+
+        cache = cache.withExpiryPolicy(new TestExiryPolicy());
+
+        for (long i = 0; i < 100; i++)
+            cache.put(i, i);
+
+        for (long i = 0; i < 100; i++)
+            assertEquals((Long)i, cache.get(i));
+
+        SqlQuery<Long, Long> qry = new SqlQuery<>(Long.class, "_val >= 90");
+
+        List<Cache.Entry<Long, Long>> res = cache.query(qry).getAll();
+
+        assertEquals(10, res.size());
+
+        for (Cache.Entry<Long, Long> e : res) {
+            assertNotNull(e.getKey());
+            assertNotNull(e.getValue());
+        }
+    }
+
+    /**
+     *
+     */
+    private static class TestExiryPolicy implements ExpiryPolicy {
+        /** {@inheritDoc} */
+        @Override public Duration getExpiryForCreation() {
+            return Duration.ONE_MINUTE;
+        }
+
+        /** {@inheritDoc} */
+        @Override public Duration getExpiryForAccess() {
+            return Duration.FIVE_MINUTES;
+        }
+
+        /** {@inheritDoc} */
+        @Override public Duration getExpiryForUpdate() {
+            return Duration.TWENTY_MINUTES;
+        }
+    }
+
+    /**
      * Test entry class.
      */
     private static class TestEntity implements Serializable {

http://git-wip-us.apache.org/repos/asf/ignite/blob/07611bd1/modules/indexing/src/test/java/org/apache/ignite/testsuites/IgniteCacheWithIndexingTestSuite.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/test/java/org/apache/ignite/testsuites/IgniteCacheWithIndexingTestSuite.java b/modules/indexing/src/test/java/org/apache/ignite/testsuites/IgniteCacheWithIndexingTestSuite.java
index 929fb37..a85b7a6 100644
--- a/modules/indexing/src/test/java/org/apache/ignite/testsuites/IgniteCacheWithIndexingTestSuite.java
+++ b/modules/indexing/src/test/java/org/apache/ignite/testsuites/IgniteCacheWithIndexingTestSuite.java
@@ -20,6 +20,7 @@ package org.apache.ignite.testsuites;
 import junit.framework.TestSuite;
 import org.apache.ignite.internal.processors.cache.CacheConfigurationP2PTest;
 import org.apache.ignite.internal.processors.cache.CacheIndexStreamerTest;
+import org.apache.ignite.internal.processors.cache.CacheOperationsWithExpirationTest;
 import org.apache.ignite.internal.processors.cache.CacheRandomOperationsMultithreadedTest;
 import org.apache.ignite.internal.processors.cache.GridCacheOffHeapAndSwapSelfTest;
 import org.apache.ignite.internal.processors.cache.GridCacheOffHeapSelfTest;
@@ -74,6 +75,7 @@ public class IgniteCacheWithIndexingTestSuite extends TestSuite {
         suite.addTestSuite(IgniteClientReconnectQueriesTest.class);
         suite.addTestSuite(CacheRandomOperationsMultithreadedTest.class);
         suite.addTestSuite(IgniteCacheStarvationOnRebalanceTest.class);
+        suite.addTestSuite(CacheOperationsWithExpirationTest.class);
 
         return suite;
     }


[06/17] ignite git commit: ignite-2899 Fixed issues with 'keepBinary' handling. This closes #593. (cherry picked from commit ee7e2c7)

Posted by dm...@apache.org.
ignite-2899 Fixed issues with 'keepBinary' handling. This closes #593.
(cherry picked from commit ee7e2c7)


Project: http://git-wip-us.apache.org/repos/asf/ignite/repo
Commit: http://git-wip-us.apache.org/repos/asf/ignite/commit/8e49e701
Tree: http://git-wip-us.apache.org/repos/asf/ignite/tree/8e49e701
Diff: http://git-wip-us.apache.org/repos/asf/ignite/diff/8e49e701

Branch: refs/heads/master
Commit: 8e49e7013ea378c3040e1aa2d9494196d0833e40
Parents: 40a27e7
Author: sboikov <sb...@gridgain.com>
Authored: Mon May 23 19:42:45 2016 +0300
Committer: sboikov <sb...@gridgain.com>
Committed: Mon May 23 19:50:16 2016 +0300

----------------------------------------------------------------------
 .../processors/cache/GridCacheAdapter.java      |   30 +-
 .../processors/cache/GridCacheMapEntry.java     |   13 +-
 .../processors/cache/GridCacheReturn.java       |   10 +-
 .../distributed/dht/GridDhtTxPrepareFuture.java |    2 +-
 .../dht/atomic/GridDhtAtomicCache.java          |   15 +-
 .../dht/colocated/GridDhtColocatedCache.java    |    2 +-
 .../local/atomic/GridLocalAtomicCache.java      |    2 +-
 .../cache/transactions/IgniteTxEntry.java       |    3 +-
 .../transactions/IgniteTxLocalAdapter.java      |    4 +-
 ...GetEntryOptimisticReadCommittedSeltTest.java |    2 +-
 .../IgniteCacheConfigVariationsFullApiTest.java |   50 +-
 ...rceptorCacheConfigVariationsFullApiTest.java |  118 ++
 ...terceptorWithKeepBinaryCacheFullApiTest.java |  124 ++
 .../cache/WithKeepBinaryCacheFullApiTest.java   | 1234 ++++++++++++++++++
 ...gniteComputeConfigVariationsFullApiTest.java |   12 +-
 .../ConfigVariationsTestSuiteBuilder.java       |    9 +
 ...IgniteCacheConfigVariationsAbstractTest.java |   16 +-
 .../IgniteConfigVariationsAbstractTest.java     |  158 ++-
 ...orCacheConfigVariationsFullApiTestSuite.java |   41 +
 ...ryCacheConfigVariationsFullApiTestSuite.java |   71 +
 20 files changed, 1838 insertions(+), 78 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/8e49e701/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheAdapter.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheAdapter.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheAdapter.java
index 9ea688d..b68a8ca 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheAdapter.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheAdapter.java
@@ -1407,9 +1407,16 @@ public abstract class GridCacheAdapter<K, V> implements IgniteInternalCache<K, V
 
         long start = statsEnabled ? System.nanoTime() : 0L;
 
+        if (ctx.keepBinary())
+            key = (K)ctx.toCacheKeyObject(key);
+
         T2<V, GridCacheVersion> t = (T2<V, GridCacheVersion>)get(key, !ctx.keepBinary(), true);
 
-        CacheEntry<K, V> val = t != null ? new CacheEntryImplEx<>(key, t.get1(), t.get2()) : null;
+        CacheEntry<K, V> val = t != null ? new CacheEntryImplEx<>(
+            ctx.keepBinary() ? (K)ctx.unwrapBinaryIfNeeded(key, true, false) : key,
+            t.get1(),
+            t.get2())
+            : null;
 
         if (ctx.config().getInterceptor() != null) {
             V val0 = (V)ctx.config().getInterceptor().onGet(key, t != null ? val.getValue() : null);
@@ -1454,8 +1461,10 @@ public abstract class GridCacheAdapter<K, V> implements IgniteInternalCache<K, V
 
         final long start = statsEnabled ? System.nanoTime() : 0L;
 
+        final K key0 = ctx.keepBinary() ? (K)ctx.toCacheKeyObject(key) : key;
+
         IgniteInternalFuture<T2<V, GridCacheVersion>> fut =
-            (IgniteInternalFuture<T2<V, GridCacheVersion>>)getAsync(key, !ctx.keepBinary(), true);
+            (IgniteInternalFuture<T2<V, GridCacheVersion>>)getAsync(key0, !ctx.keepBinary(), true);
 
         final boolean intercept = ctx.config().getInterceptor() != null;
 
@@ -1465,16 +1474,21 @@ public abstract class GridCacheAdapter<K, V> implements IgniteInternalCache<K, V
                     throws IgniteCheckedException {
                     T2<V, GridCacheVersion> t = f.get();
 
-                    CacheEntry<K, V> val = t != null ? new CacheEntryImplEx<>(key, t.get1(), t.get2()) : null;
+                    CacheEntry val = t != null ? new CacheEntryImplEx<>(
+                        ctx.keepBinary() ? (K)ctx.unwrapBinaryIfNeeded(key0, true, false) : key0,
+                        t.get1(),
+                        t.get2())
+                        : null;
+
                     if (intercept) {
-                        V val0 = (V)ctx.config().getInterceptor().onGet(key, t != null ? val.getValue() : null);
+                        V val0 = (V)ctx.config().getInterceptor().onGet(key0, t != null ? val.getValue() : null);
 
-                        return new CacheEntryImplEx<>(key, val0, t != null ? t.get2() : null);
+                        return val0 != null ? new CacheEntryImplEx(key0, val0, t != null ? t.get2() : null) : null;
                     }
                     else
                         return val;
-                }
-            });
+            }
+        });
 
         if (statsEnabled)
             fut.listen(new UpdateGetTimeStatClosure<T2<V, GridCacheVersion>>(metrics0(), start));
@@ -1720,7 +1734,7 @@ public abstract class GridCacheAdapter<K, V> implements IgniteInternalCache<K, V
                         return (V)(val);
                     }
 
-                    return map.get(key);
+                    return F.firstValue(map);
                 }
             });
     }

http://git-wip-us.apache.org/repos/asf/ignite/blob/8e49e701/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheMapEntry.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheMapEntry.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheMapEntry.java
index cb51a8c..718e8a0 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheMapEntry.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheMapEntry.java
@@ -1159,7 +1159,7 @@ public abstract class GridCacheMapEntry extends GridMetadataAwareAdapter impleme
                 rawGetOrUnmarshalUnlocked(!retval && !isOffHeapValuesOnly()) : this.val;
 
             if (intercept) {
-                val0 = CU.value(val, cctx, false);
+                val0 = cctx.unwrapBinaryIfNeeded(val, keepBinary, false);
 
                 CacheLazyEntry e = new CacheLazyEntry(cctx, key, old, keepBinary);
 
@@ -1677,14 +1677,14 @@ public abstract class GridCacheMapEntry extends GridMetadataAwareAdapter impleme
                 CacheLazyEntry e;
 
                 if (op == GridCacheOperation.UPDATE) {
-                    updated0 = value(updated0, updated, false);
+                    updated0 = value(updated0, updated, keepBinary, false);
 
                     e = new CacheLazyEntry(cctx, key, key0, old, old0, keepBinary);
 
                     Object interceptorVal = cctx.config().getInterceptor().onBeforePut(e, updated0);
 
                     if (interceptorVal == null)
-                        return new GridTuple3<>(false, cctx.unwrapTemporary(value(old0, old, false)), invokeRes);
+                        return new GridTuple3<>(false, cctx.unwrapTemporary(value(old0, old, keepBinary, false)), invokeRes);
                     else {
                         updated0 = cctx.unwrapTemporary(interceptorVal);
 
@@ -2333,7 +2333,7 @@ public abstract class GridCacheMapEntry extends GridMetadataAwareAdapter impleme
             // Actual update.
             if (op == GridCacheOperation.UPDATE) {
                 if (intercept) {
-                    updated0 = value(updated0, updated, false);
+                    updated0 = value(updated0, updated, keepBinary, false);
 
                     Object interceptorVal = cctx.config().getInterceptor()
                         .onBeforePut(new CacheLazyEntry(cctx, key, key0, oldVal, old0, keepBinary), updated0);
@@ -2572,14 +2572,15 @@ public abstract class GridCacheMapEntry extends GridMetadataAwareAdapter impleme
     /**
      * @param val Value.
      * @param cacheObj Cache object.
+     * @param keepBinary Keep binary flag.
      * @param cpy Copy flag.
      * @return Cache object value.
      */
-    @Nullable private Object value(@Nullable Object val, @Nullable CacheObject cacheObj, boolean cpy) {
+    @Nullable private Object value(@Nullable Object val, @Nullable CacheObject cacheObj, boolean keepBinary, boolean cpy) {
         if (val != null)
             return val;
 
-        return cacheObj != null ? cacheObj.value(cctx.cacheObjectContext(), cpy) : null;
+        return cctx.unwrapBinaryIfNeeded(cacheObj, keepBinary, cpy);
     }
 
     /**

http://git-wip-us.apache.org/repos/asf/ignite/blob/8e49e701/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheReturn.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheReturn.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheReturn.java
index b3bce09..29e74db 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheReturn.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheReturn.java
@@ -28,6 +28,7 @@ import java.util.HashMap;
 import java.util.Map;
 import javax.cache.processor.EntryProcessorResult;
 import org.apache.ignite.IgniteCheckedException;
+import org.apache.ignite.binary.BinaryObject;
 import org.apache.ignite.internal.GridDirectCollection;
 import org.apache.ignite.internal.GridDirectTransient;
 import org.apache.ignite.internal.util.tostring.GridToStringInclude;
@@ -218,6 +219,7 @@ public class GridCacheReturn implements Externalizable, Message {
      * @param key0 Key value.
      * @param res Result.
      * @param err Error.
+     * @param keepBinary Keep binary.
      */
     @SuppressWarnings("unchecked")
     public synchronized void addEntryProcessResult(
@@ -225,7 +227,8 @@ public class GridCacheReturn implements Externalizable, Message {
         KeyCacheObject key,
         @Nullable Object key0,
         @Nullable Object res,
-        @Nullable Exception err) {
+        @Nullable Exception err,
+        boolean keepBinary) {
         assert v == null || v instanceof Map : v;
         assert key != null;
         assert res != null || err != null;
@@ -243,7 +246,10 @@ public class GridCacheReturn implements Externalizable, Message {
 
             CacheInvokeResult res0 = err == null ? CacheInvokeResult.fromResult(res) : CacheInvokeResult.fromError(err);
 
-            resMap.put(key0 != null ? key0 : CU.value(key, cctx, true), res0);
+            Object resKey = key0 != null ? key0 :
+                ((keepBinary && key instanceof BinaryObject) ? key : CU.value(key, cctx, true));
+
+            resMap.put(resKey, res0);
         }
         else {
             assert v == null;

http://git-wip-us.apache.org/repos/asf/ignite/blob/8e49e701/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtTxPrepareFuture.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtTxPrepareFuture.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtTxPrepareFuture.java
index b8fee2d..e1baabb 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtTxPrepareFuture.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtTxPrepareFuture.java
@@ -432,7 +432,7 @@ public final class GridDhtTxPrepareFuture extends GridCompoundFuture<IgniteInter
 
                             if (retVal) {
                                 if (err != null || procRes != null)
-                                    ret.addEntryProcessResult(txEntry.context(), key, null, procRes, err);
+                                    ret.addEntryProcessResult(txEntry.context(), key, null, procRes, err, keepBinary);
                                 else
                                     ret.invokeResult(true);
                             }

http://git-wip-us.apache.org/repos/asf/ignite/blob/8e49e701/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridDhtAtomicCache.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridDhtAtomicCache.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridDhtAtomicCache.java
index 6a30f7f..7460495 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridDhtAtomicCache.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridDhtAtomicCache.java
@@ -1874,7 +1874,10 @@ public class GridDhtAtomicCache<K, V> extends GridDhtCacheAdapter<K, V> {
                             if (invokeRes == null)
                                 invokeRes = new GridCacheReturn(node.isLocal());
 
-                            invokeRes.addEntryProcessResult(ctx, entry.key(), invokeEntry.key(), computed, null);
+                            computed = ctx.unwrapTemporary(computed);
+
+                            invokeRes.addEntryProcessResult(ctx, entry.key(), invokeEntry.key(), computed, null,
+                                req.keepBinary());
                         }
 
                         if (!invokeEntry.modified())
@@ -1888,7 +1891,7 @@ public class GridDhtAtomicCache<K, V> extends GridDhtCacheAdapter<K, V> {
                         if (invokeRes == null)
                             invokeRes = new GridCacheReturn(node.isLocal());
 
-                        invokeRes.addEntryProcessResult(ctx, entry.key(), invokeEntry.key(), null, e);
+                        invokeRes.addEntryProcessResult(ctx, entry.key(), invokeEntry.key(), null, e, req.keepBinary());
 
                         updated = old;
                     }
@@ -2022,8 +2025,9 @@ public class GridDhtAtomicCache<K, V> extends GridDhtCacheAdapter<K, V> {
                                 entry.key(),
                                 old,
                                 req.keepBinary()),
-                            updated.value(
-                                ctx.cacheObjectContext(),
+                            ctx.unwrapBinaryIfNeeded(
+                                updated, 
+                                req.keepBinary(), 
                                 false));
 
                         if (val == null)
@@ -2366,7 +2370,8 @@ public class GridDhtAtomicCache<K, V> extends GridDhtCacheAdapter<K, V> {
                             k,
                             null,
                             compRes.get1(),
-                            compRes.get2());
+                            compRes.get2(),
+                            req.keepBinary());
                     }
                 }
                 else {

http://git-wip-us.apache.org/repos/asf/ignite/blob/8e49e701/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/colocated/GridDhtColocatedCache.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/colocated/GridDhtColocatedCache.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/colocated/GridDhtColocatedCache.java
index 0ae434a..d0850e7 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/colocated/GridDhtColocatedCache.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/colocated/GridDhtColocatedCache.java
@@ -236,7 +236,7 @@ public class GridDhtColocatedCache<K, V> extends GridDhtTransactionalCacheAdapte
                                 return (V)(val);
                             }
 
-                            return (V)map.get(key);
+                            return (V)F.firstValue(map);
                         }
                     });
                 }

http://git-wip-us.apache.org/repos/asf/ignite/blob/8e49e701/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/local/atomic/GridLocalAtomicCache.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/local/atomic/GridLocalAtomicCache.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/local/atomic/GridLocalAtomicCache.java
index cb6152d..e1d12b6 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/local/atomic/GridLocalAtomicCache.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/local/atomic/GridLocalAtomicCache.java
@@ -412,7 +412,7 @@ public class GridLocalAtomicCache<K, V> extends GridLocalCache<K, V> {
 
         assert m.isEmpty() || m.size() == 1 : m.size();
 
-        return m.get(key);
+        return F.firstValue(m);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/8e49e701/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/IgniteTxEntry.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/IgniteTxEntry.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/IgniteTxEntry.java
index 45a3fff..8d50e2b 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/IgniteTxEntry.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/IgniteTxEntry.java
@@ -40,7 +40,6 @@ import org.apache.ignite.internal.processors.cache.GridCacheSharedContext;
 import org.apache.ignite.internal.processors.cache.KeyCacheObject;
 import org.apache.ignite.internal.processors.cache.distributed.IgniteExternalizableExpiryPolicy;
 import org.apache.ignite.internal.processors.cache.version.GridCacheVersion;
-import org.apache.ignite.internal.processors.cache.version.GridCacheVersion;
 import org.apache.ignite.internal.util.lang.GridPeerDeployAware;
 import org.apache.ignite.internal.util.tostring.GridToStringBuilder;
 import org.apache.ignite.internal.util.tostring.GridToStringExclude;
@@ -943,7 +942,7 @@ public class IgniteTxEntry implements GridPeerDeployAware, Message {
      * @param ver Entry version.
      */
     public void entryReadVersion(GridCacheVersion ver) {
-        assert this.serReadVer == null;
+        assert this.serReadVer == null: "Wrong version [serReadVer=" + serReadVer + ", ver=" + ver + "]";
         assert ver != null;
 
         this.serReadVer = ver;

http://git-wip-us.apache.org/repos/asf/ignite/blob/8e49e701/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/IgniteTxLocalAdapter.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/IgniteTxLocalAdapter.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/IgniteTxLocalAdapter.java
index d492051..f9ef423 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/IgniteTxLocalAdapter.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/IgniteTxLocalAdapter.java
@@ -2824,10 +2824,10 @@ public abstract class IgniteTxLocalAdapter extends IgniteTxAdapter implements Ig
             }
 
             if (res != null)
-                ret.addEntryProcessResult(ctx, txEntry.key(), key0, res, null);
+                ret.addEntryProcessResult(ctx, txEntry.key(), key0, res, null, txEntry.keepBinary());
         }
         catch (Exception e) {
-            ret.addEntryProcessResult(ctx, txEntry.key(), key0, null, e);
+            ret.addEntryProcessResult(ctx, txEntry.key(), key0, null, e, txEntry.keepBinary());
         }
     }
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/8e49e701/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/CacheGetEntryOptimisticReadCommittedSeltTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/CacheGetEntryOptimisticReadCommittedSeltTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/CacheGetEntryOptimisticReadCommittedSeltTest.java
index acc21df..c04612d 100644
--- a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/CacheGetEntryOptimisticReadCommittedSeltTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/CacheGetEntryOptimisticReadCommittedSeltTest.java
@@ -33,4 +33,4 @@ public class CacheGetEntryOptimisticReadCommittedSeltTest extends CacheGetEntryA
     @Override protected TransactionIsolation isolation() {
         return TransactionIsolation.READ_COMMITTED;
     }
-}
\ No newline at end of file
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/8e49e701/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCacheConfigVariationsFullApiTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCacheConfigVariationsFullApiTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCacheConfigVariationsFullApiTest.java
index ded5a14..5e8f162 100644
--- a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCacheConfigVariationsFullApiTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCacheConfigVariationsFullApiTest.java
@@ -161,6 +161,9 @@ public class IgniteCacheConfigVariationsFullApiTest extends IgniteCacheConfigVar
             }
         };
 
+    /** */
+    public static final int CNT = 20;
+
     /** {@inheritDoc} */
     @Override protected long getTestTimeout() {
         return TEST_TIMEOUT;
@@ -2474,31 +2477,50 @@ public class IgniteCacheConfigVariationsFullApiTest extends IgniteCacheConfigVar
     /**
      * @throws Exception If failed.
      */
+    @SuppressWarnings("serial")
     public void testGetAndRemoveObject() throws Exception {
-        IgniteCache<String, SerializableObject> cache = ignite(0).cache(cacheName());
+        runInAllDataModes(new TestRunnable() {
+            @Override public void run() throws Exception {
+                IgniteCache<String, Object> cache = ignite(0).cache(cacheName());
 
-        SerializableObject val1 = new SerializableObject(1);
-        SerializableObject val2 = new SerializableObject(2);
+                Map<String, Object> map = new HashMap<String, Object>() {{
+                    for (int i = 0; i < CNT; i++)
+                        put("key" + i, value(i));
+                }};
 
-        cache.put("key1", val1);
-        cache.put("key2", val2);
+                for (Map.Entry<String, Object> e : map.entrySet()) {
+                    final String key = e.getKey();
+                    final Object val = e.getValue();
 
-        assert !cache.remove("key1", new SerializableObject(0));
+                    cache.put(key, val);
 
-        SerializableObject oldVal = cache.get("key1");
+                    assertFalse(cache.remove(key, new SerializableObject(-1)));
 
-        assert oldVal != null && F.eq(val1, oldVal);
+                    Object oldVal = cache.get(key);
 
-        assert cache.remove("key1");
+                    assertNotNull(oldVal);
+                    assertEquals(val, oldVal);
 
-        assert cache.get("key1") == null;
+                    assertTrue(cache.remove(key));
 
-        SerializableObject oldVal2 = cache.getAndRemove("key2");
+                    assertNull(cache.get(key));
+                }
 
-        assert F.eq(val2, oldVal2);
+                for (Map.Entry<String, Object> e : map.entrySet()) {
+                    final String key = e.getKey();
+                    final Object val = e.getValue();
 
-        assert cache.get("key2") == null;
-        assert cache.getAndRemove("key2") == null;
+                    cache.put(key, val);
+
+                    Object oldVal = cache.getAndRemove(key);
+
+                    assertEquals(val, oldVal);
+
+                    assertNull(cache.get(key));
+                    assertNull(cache.getAndRemove(key));
+                }
+            }
+        });
     }
 
     /**

http://git-wip-us.apache.org/repos/asf/ignite/blob/8e49e701/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/InterceptorCacheConfigVariationsFullApiTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/InterceptorCacheConfigVariationsFullApiTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/InterceptorCacheConfigVariationsFullApiTest.java
new file mode 100644
index 0000000..b6f5333
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/InterceptorCacheConfigVariationsFullApiTest.java
@@ -0,0 +1,118 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ignite.internal.processors.cache;
+
+import javax.cache.Cache;
+import org.apache.ignite.binary.BinaryObject;
+import org.apache.ignite.cache.CacheInterceptor;
+import org.apache.ignite.configuration.CacheConfiguration;
+import org.apache.ignite.lang.IgniteBiTuple;
+import org.jetbrains.annotations.Nullable;
+
+/**
+ * Full API cache test.
+ */
+@SuppressWarnings({"TransientFieldInNonSerializableClass", "unchecked"})
+public class InterceptorCacheConfigVariationsFullApiTest extends IgniteCacheConfigVariationsFullApiTest {
+    /** */
+    private static volatile boolean validate = true;
+
+    /** {@inheritDoc} */
+    @Override protected CacheConfiguration cacheConfiguration() {
+        CacheConfiguration cc = super.cacheConfiguration();
+
+        cc.setInterceptor(new TestInterceptor());
+
+        return cc;
+    }
+
+    /** {@inheritDoc} */
+    @Override public void testTtlNoTx() throws Exception {
+        // No-op.
+    }
+
+    /** {@inheritDoc} */
+    @Override public void testTtlNoTxOldEntry() throws Exception {
+        // No-op.
+    }
+
+    /** {@inheritDoc} */
+    @Override public void testTtlTx() throws Exception {
+        // No-op.
+    }
+
+    /**
+     *
+     */
+    private static class TestInterceptor<K, V> implements CacheInterceptor<K, V> {
+        /** */
+        private static final long serialVersionUID = 0L;
+
+        /** {@inheritDoc} */
+        @Nullable @Override public V onGet(K key, V val) {
+            if (validate && val != null)
+                assertFalse("Val: " + val, val instanceof BinaryObject);
+
+            return val;
+        }
+
+        /** {@inheritDoc} */
+        @Nullable @Override public V onBeforePut(Cache.Entry<K, V> e, V newVal) {
+            if (validate) {
+                validateEntry(e);
+
+                if (newVal != null)
+                    assertFalse("NewVal: " + newVal, newVal instanceof BinaryObject);
+            }
+
+            return newVal;
+        }
+
+        /** {@inheritDoc} */
+        @Override public void onAfterPut(Cache.Entry<K, V> entry) {
+            validateEntry(entry);
+        }
+
+        /** {@inheritDoc} */
+        @Nullable @Override public IgniteBiTuple<Boolean, V> onBeforeRemove(Cache.Entry<K, V> entry) {
+            validateEntry(entry);
+
+            return new IgniteBiTuple<>(false, entry.getValue());
+        }
+
+        /** {@inheritDoc} */
+        @Override public void onAfterRemove(Cache.Entry<K, V> entry) {
+            validateEntry(entry);
+        }
+
+        /**
+         * @param e Value.
+         */
+        private void validateEntry(Cache.Entry<K, V> e) {
+            assertNotNull(e);
+            assertNotNull(e.getKey());
+
+            if (validate) {
+                assertFalse("Key: " + e.getKey(), e.getKey() instanceof BinaryObject);
+
+                if (e.getValue() != null)
+                    assertFalse("Val: " + e.getValue(), e.getValue() instanceof BinaryObject);
+            }
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/8e49e701/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/InterceptorWithKeepBinaryCacheFullApiTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/InterceptorWithKeepBinaryCacheFullApiTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/InterceptorWithKeepBinaryCacheFullApiTest.java
new file mode 100644
index 0000000..d16e6e7
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/InterceptorWithKeepBinaryCacheFullApiTest.java
@@ -0,0 +1,124 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ignite.internal.processors.cache;
+
+import javax.cache.Cache;
+import org.apache.ignite.binary.BinaryObject;
+import org.apache.ignite.cache.CacheInterceptor;
+import org.apache.ignite.configuration.CacheConfiguration;
+import org.apache.ignite.configuration.IgniteConfiguration;
+import org.apache.ignite.lang.IgniteBiTuple;
+import org.jetbrains.annotations.Nullable;
+
+/**
+ *
+ */
+@SuppressWarnings("unchecked")
+public class InterceptorWithKeepBinaryCacheFullApiTest extends WithKeepBinaryCacheFullApiTest {
+    /** */
+    private static volatile boolean validate;
+
+    /** {@inheritDoc} */
+    @Override protected CacheConfiguration cacheConfiguration(IgniteConfiguration cfg, String cacheName) {
+        CacheConfiguration cc = super.cacheConfiguration(cfg, cacheName);
+
+        cc.setInterceptor(new TestInterceptor());
+
+        return cc;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void beforeTest() throws Exception {
+        super.beforeTest();
+
+        validate = true;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void afterTest() throws Exception {
+        validate = false;
+
+        super.afterTest();
+    }
+
+    /**
+     *
+     */
+    private static class TestInterceptor<K, V> implements CacheInterceptor<K, V> {
+        /** */
+        private static final long serialVersionUID = 0L;
+
+        /** {@inheritDoc} */
+        @Nullable @Override public V onGet(K key, V val) {
+            // TODO IGNITE-2973: should always validate key here, but cannot due to the bug.
+            validate(key, val, false, true);
+
+            return val;
+        }
+
+        /** {@inheritDoc} */
+        @Nullable @Override public V onBeforePut(Cache.Entry<K, V> e, V newVal) {
+            if (validate) {
+                validate(e.getKey(), e.getValue(), true, true);
+
+                if (newVal != null)
+                    assertEquals("NewVal: " + newVal, interceptorBinaryObjExp, newVal instanceof BinaryObject);
+            }
+
+            return newVal;
+        }
+
+        /** {@inheritDoc} */
+        @Override public void onAfterPut(Cache.Entry<K, V> entry) {
+            validate(entry.getKey(), entry.getValue(), true, false);
+        }
+
+        /** {@inheritDoc} */
+        @Nullable @Override public IgniteBiTuple<Boolean, V> onBeforeRemove(Cache.Entry<K, V> entry) {
+            validate(entry.getKey(), entry.getValue(), true, true);
+
+            return new IgniteBiTuple<>(false, entry.getValue());
+        }
+
+        /** {@inheritDoc} */
+        @Override public void onAfterRemove(Cache.Entry<K, V> entry) {
+            validate(entry.getKey(), entry.getValue(), true, true);
+        }
+
+        /**
+         * @param key Key.
+         * @param val Value.
+         * @param validateKey Validate key flag.
+         * @param validateVal Validate value flag.
+         */
+        private void validate(K key, V val, boolean validateKey, boolean validateVal) {
+            assertNotNull(key);
+
+            if (validate) {
+                if (validateKey)
+                    assertTrue("Key: " + key, key instanceof BinaryObject);
+
+                if (val != null) {
+                    // TODO IGNITE-2973: should always do this check, but cannot due to the bug.
+                    if (validateVal && interceptorBinaryObjExp)
+                        assertTrue("Val: " + val, val instanceof BinaryObject);
+                }
+            }
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/8e49e701/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/WithKeepBinaryCacheFullApiTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/WithKeepBinaryCacheFullApiTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/WithKeepBinaryCacheFullApiTest.java
new file mode 100644
index 0000000..1954a8d
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/WithKeepBinaryCacheFullApiTest.java
@@ -0,0 +1,1234 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ignite.internal.processors.cache;
+
+import java.util.Collection;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.Map;
+import java.util.Set;
+import javax.cache.processor.EntryProcessorException;
+import javax.cache.processor.EntryProcessorResult;
+import javax.cache.processor.MutableEntry;
+import org.apache.ignite.Ignite;
+import org.apache.ignite.IgniteCache;
+import org.apache.ignite.binary.BinaryObject;
+import org.apache.ignite.cache.CacheEntry;
+import org.apache.ignite.cache.CacheEntryProcessor;
+import org.apache.ignite.configuration.CacheConfiguration;
+import org.apache.ignite.testframework.junits.IgniteCacheConfigVariationsAbstractTest;
+import org.apache.ignite.transactions.Transaction;
+import org.apache.ignite.transactions.TransactionConcurrency;
+import org.apache.ignite.transactions.TransactionIsolation;
+
+import static org.apache.ignite.cache.CacheAtomicityMode.TRANSACTIONAL;
+import static org.apache.ignite.testframework.junits.IgniteConfigVariationsAbstractTest.DataMode.PLANE_OBJECT;
+import static org.apache.ignite.testframework.junits.IgniteConfigVariationsAbstractTest.DataMode.SERIALIZABLE;
+
+/**
+ *
+ */
+@SuppressWarnings("unchecked")
+public class WithKeepBinaryCacheFullApiTest extends IgniteCacheConfigVariationsAbstractTest {
+    /** */
+    protected static volatile boolean interceptorBinaryObjExp = true;
+
+    /** */
+    public static final int CNT = 10;
+
+    /** */
+    public static final CacheEntryProcessor NOOP_ENTRY_PROC = new CacheEntryProcessor() {
+        @Override public Object process(MutableEntry entry, Object... arguments) throws EntryProcessorException {
+            return null;
+        }
+    };
+
+    /** */
+    public static final CacheEntryProcessor INC_ENTRY_PROC_USER_OBJ = new CacheEntryProcessor() {
+        @Override public Object process(MutableEntry entry, Object... arguments) throws EntryProcessorException {
+            assertTrue(entry.getKey() instanceof BinaryObject);
+
+            Object val = entry.getValue();
+
+            int valId = 0;
+
+            if (val != null) {
+                assertTrue(val instanceof BinaryObject);
+
+                valId = valueOf(((BinaryObject)val).deserialize()) + 1;
+            }
+
+            Object newVal = value(valId, (DataMode)arguments[0]);
+
+            assertFalse(newVal instanceof BinaryObject);
+
+            entry.setValue(newVal);
+
+            return val == null ? null : ((BinaryObject)val).deserialize();
+        }
+    };
+
+    /** */
+    public static final CacheEntryProcessor INC_ENTRY_PROC_BINARY_OBJ = new CacheEntryProcessor() {
+        @Override public Object process(MutableEntry entry, Object... arguments) throws EntryProcessorException {
+            assertTrue(entry.getKey() instanceof BinaryObject);
+
+            Object val = entry.getValue();
+
+            int valId = 0;
+
+            if (val != null) {
+                assertTrue(val instanceof BinaryObject);
+
+                valId = valueOf(((BinaryObject)val).deserialize()) + 1;
+            }
+
+            Object newVal = value(valId, (DataMode)arguments[0]);
+
+            Object newBinaryVal = ((Ignite)entry.unwrap(Ignite.class)).binary().toBinary(newVal);
+
+            entry.setValue(newBinaryVal);
+
+            return val;
+        }
+    };
+
+    /** {@inheritDoc} */
+    @SuppressWarnings("unchecked")
+    @Override protected CacheConfiguration cacheConfiguration() {
+        CacheConfiguration cc = super.cacheConfiguration();
+
+        cc.setStoreKeepBinary(true);
+
+        return cc;
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    @SuppressWarnings("serial")
+    public void testRemovePutGet() throws Exception {
+        runInAllDataModes(new TestRunnable() {
+            @Override public void run() throws Exception {
+                final IgniteCache cache = jcache().withKeepBinary();
+
+                final Set keys = new LinkedHashSet() {{
+                    for (int i = 0; i < CNT; i++)
+                        add(key(i));
+                }};
+
+                runInAllTxModes(new TestRunnable() {
+                    @Override public void run() throws Exception {
+                        for (Object key : keys)
+                            cache.remove(key);
+                    }
+                });
+
+                runInAllTxModes(new TestRunnable() {
+                    @Override public void run() throws Exception {
+                        for (Object key : keys) {
+                            assertNull(cache.get(key));
+                            assertNull(cache.getEntry(key));
+                        }
+                    }
+                });
+
+                for (final Object key : keys) {
+                    runInAllTxModes(new TestRunnable() {
+                        @Override public void run() throws Exception {
+                            Object val = value(valueOf(key));
+
+                            cache.put(key, val);
+
+                            BinaryObject retVal = (BinaryObject)cache.get(key);
+
+                            assertEquals(val, retVal.deserialize());
+
+                            CacheEntry<BinaryObject, BinaryObject> entry = cache.getEntry(key);
+
+                            assertTrue(entry.getKey() instanceof BinaryObject);
+
+                            assertEquals(val, entry.getValue().deserialize());
+
+                            assertTrue(cache.remove(key));
+                        }
+                    });
+                }
+            }
+        }, PLANE_OBJECT, SERIALIZABLE);
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    @SuppressWarnings("serial")
+    public void testRemovePutGetAsync() throws Exception {
+        runInAllDataModes(new TestRunnable() {
+            @Override public void run() throws Exception {
+                final IgniteCache cache = jcache().withKeepBinary().withAsync();
+
+                final Set keys = new LinkedHashSet() {{
+                    for (int i = 0; i < CNT; i++)
+                        add(key(i));
+                }};
+
+                runInAllTxModes(new TestRunnable() {
+                    @Override public void run() throws Exception {
+                        for (Object key : keys) {
+                            cache.remove(key);
+
+                            cache.future().get();
+                        }
+                    }
+                });
+
+                runInAllTxModes(new TestRunnable() {
+                    @Override public void run() throws Exception {
+                        for (Object key : keys) {
+                            cache.get(key);
+                            assertNull(cache.future().get());
+
+                            cache.getEntry(key);
+                            assertNull(cache.future().get());
+                        }
+                    }
+                });
+
+
+                for (final Object key : keys) {
+                    runInAllTxModes(new TestRunnable() {
+                        @Override public void run() throws Exception {
+                            Object val = value(valueOf(key));
+
+                            cache.put(key, val);
+
+                            cache.future().get();
+
+                            cache.get(key);
+                            BinaryObject retVal = (BinaryObject)cache.future().get();
+
+                            assertEquals(val, retVal.deserialize());
+
+                            cache.getEntry(key);
+                            CacheEntry<BinaryObject, BinaryObject> e = (CacheEntry<BinaryObject, BinaryObject>)cache.future().get();
+
+                            assertEquals(key, deserializeBinary(e.getKey()));
+
+                            assertEquals(val, e.getValue().deserialize());
+                        }
+                    });
+                }
+            }
+        }, PLANE_OBJECT, SERIALIZABLE);
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    @SuppressWarnings("serial")
+    public void testPutAllGetAll() throws Exception {
+        runInAllDataModes(new TestRunnable() {
+            @Override public void run() throws Exception {
+                final IgniteCache cache = jcache().withKeepBinary();
+
+                final Set keys = new LinkedHashSet() {{
+                    for (int i = 0; i < CNT; i++)
+                        add(key(i));
+                }};
+
+                runInAllTxModes(new TestRunnable() {
+                    @Override public void run() throws Exception {
+                        for (Object val : cache.getAll(keys).values())
+                            assertNull(val);
+                    }
+                });
+
+                runInAllTxModes(new TestRunnable() {
+                    @Override public void run() throws Exception {
+                        Collection<CacheEntry> entries = cache.<CacheEntry>getEntries(keys);
+
+                        for (CacheEntry e : entries)
+                            assertNull(e.getValue());
+                    }
+                });
+
+                runInAllTxModes(new TestRunnable() {
+                    @Override public void run() throws Exception {
+                        Map keyValMap = new LinkedHashMap() {{
+                            for (Object key : keys) {
+                                Object val = value(valueOf(key));
+
+                                put(key, val);
+                            }
+                        }};
+
+                        cache.putAll(keyValMap);
+
+                        Set<Map.Entry<BinaryObject, BinaryObject>> set = cache.getAll(keys).entrySet();
+
+                        for (Map.Entry<BinaryObject, BinaryObject> e : set) {
+                            Object expVal = value(valueOf(e.getKey().deserialize()));
+
+                            assertEquals(expVal, e.getValue().deserialize());
+                        }
+
+                        Collection<CacheEntry<BinaryObject, BinaryObject>> entries = cache.getEntries(keys);
+
+                        for (CacheEntry<BinaryObject, BinaryObject> e : entries) {
+                            assertTrue(e.getKey() instanceof BinaryObject);
+
+                            Object expVal = value(valueOf(e.getKey().deserialize()));
+
+                            assertEquals(expVal, e.getValue().deserialize());
+                        }
+
+                        cache.removeAll(keys);
+                    }
+                });
+            }
+        }, PLANE_OBJECT, SERIALIZABLE);
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    @SuppressWarnings("serial")
+    public void testPutAllGetAllAsync() throws Exception {
+        runInAllDataModes(new TestRunnable() {
+            @Override public void run() throws Exception {
+                final IgniteCache cache = jcache().withKeepBinary().withAsync();
+
+                final Set keys = new LinkedHashSet() {{
+                    for (int i = 0; i < CNT; i++)
+                        add(key(i));
+                }};
+
+                runInAllTxModes(new TestRunnable() {
+                    @Override public void run() throws Exception {
+                        cache.getAll(keys);
+                        Map res = (Map)cache.future().get();
+
+                        for (Object val : res.values())
+                            assertNull(val);
+                    }
+                });
+
+                runInAllTxModes(new TestRunnable() {
+                    @Override public void run() throws Exception {
+                        cache.<CacheEntry>getEntries(keys);
+
+                        Collection<CacheEntry> entries = (Collection<CacheEntry>)cache.future().get();
+
+                        for (CacheEntry e : entries)
+                            assertNull(e.getValue());
+                    }
+                });
+
+                runInAllTxModes(new TestRunnable() {
+                    @Override public void run() throws Exception {
+                        Map keyValMap = new LinkedHashMap() {{
+                            for (Object key : keys) {
+                                Object val = value(valueOf(key));
+
+                                put(key, val);
+                            }
+                        }};
+
+                        cache.putAll(keyValMap);
+
+                        cache.future().get();
+
+                        cache.getAll(keys);
+                        Set<Map.Entry<BinaryObject, BinaryObject>> set = ((Map)cache.future().get()).entrySet();
+
+                        for (Map.Entry<BinaryObject, BinaryObject> e : set) {
+                            Object expVal = value(valueOf(e.getKey().deserialize()));
+
+                            assertEquals(expVal, e.getValue().deserialize());
+                        }
+
+                        cache.getEntries(keys);
+
+                        Collection<CacheEntry<BinaryObject, BinaryObject>> entries =
+                            (Collection<CacheEntry<BinaryObject, BinaryObject>>)cache.future().get();
+
+                        for (CacheEntry<BinaryObject, BinaryObject> e : entries) {
+                            assertTrue(e.getKey() instanceof BinaryObject);
+
+                            Object expVal = value(valueOf(e.getKey().deserialize()));
+
+                            assertEquals(expVal, e.getValue().deserialize());
+                        }
+
+                        cache.removeAll(keys);
+
+                        cache.future().get();
+                    }
+                });
+            }
+        }, PLANE_OBJECT, SERIALIZABLE);
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    @SuppressWarnings("serial")
+    public void testInvoke() throws Exception {
+        runInAllDataModes(new TestRunnable() {
+            @Override public void run() throws Exception {
+                final IgniteCache cache = jcache().withKeepBinary();
+
+                Set keys = new LinkedHashSet() {{
+                    for (int i = 0; i < CNT; i++)
+                        add(key(i));
+                }};
+
+                for (final Object key : keys) {
+                    Object res = cache.invoke(key, NOOP_ENTRY_PROC);
+
+                    assertNull(res);
+
+                    assertNull(cache.get(key));
+                }
+
+                for (final Object key : keys) {
+                    Object res = cache.invoke(key, INC_ENTRY_PROC_BINARY_OBJ, dataMode);
+
+                    assertNull(res);
+
+                    assertEquals(value(0), deserializeBinary(cache.get(key)));
+
+                    res = cache.invoke(key, INC_ENTRY_PROC_BINARY_OBJ, dataMode);
+
+                    assertEquals(value(0), deserializeBinary(res));
+
+                    assertEquals(value(1), deserializeBinary(cache.get(key)));
+
+                    assertTrue(cache.remove(key));
+                }
+
+                // TODO IGNITE-2973: should be always false.
+                interceptorBinaryObjExp = atomicityMode() == TRANSACTIONAL;
+
+                try {
+                    for (final Object key : keys) {
+                        Object res = cache.invoke(key, INC_ENTRY_PROC_USER_OBJ, dataMode);
+
+                        assertNull(res);
+
+                        assertEquals(value(0), deserializeBinary(cache.get(key)));
+
+                        res = cache.invoke(key, INC_ENTRY_PROC_USER_OBJ, dataMode);
+
+                        // TODO IGNITE-2953: uncomment the following assert when the issue will be fixed.
+//                               assertEquals(value(0), res);
+
+                        assertEquals(value(1), deserializeBinary(cache.get(key)));
+
+                        assertTrue(cache.remove(key));
+                    }
+                }
+                finally {
+                    interceptorBinaryObjExp = true;
+                }
+            }
+        }, PLANE_OBJECT, SERIALIZABLE);
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testInvokeTx() throws Exception {
+        if (!txShouldBeUsed())
+            return;
+
+        for (TransactionConcurrency conc : TransactionConcurrency.values()) {
+            for (TransactionIsolation isolation : TransactionIsolation.values()) {
+                // TODO IGNITE-2971: delete this if when the issue will be fixed.
+                if (conc == TransactionConcurrency.OPTIMISTIC && isolation == TransactionIsolation.SERIALIZABLE)
+                    continue;
+
+                info(">>>>> Executing test using explicite txs [concurrency=" + conc + ", isolation=" + isolation + "]");
+
+                checkInvokeTx(conc, isolation);
+
+                jcache().removeAll();
+            }
+        }
+    }
+
+    /**
+     * @param conc Concurrency
+     * @param isolation Isolation.
+     * @throws Exception If failed.
+     */
+    @SuppressWarnings("serial")
+    public void checkInvokeTx(final TransactionConcurrency conc, final TransactionIsolation isolation) throws Exception {
+        runInAllDataModes(new TestRunnable() {
+            @Override public void run() throws Exception {
+                final IgniteCache cache = jcache().withKeepBinary();
+
+                Set keys = new LinkedHashSet() {{
+                    for (int i = 0; i < CNT; i++)
+                        add(key(i));
+                }};
+
+                try (Transaction tx = testedGrid().transactions().txStart(conc, isolation)) {
+                    for (final Object key : keys) {
+                        Object res = cache.invoke(key, NOOP_ENTRY_PROC);
+
+                        assertNull(res);
+
+                        assertNull(cache.get(key));
+                    }
+
+                    tx.commit();
+                }
+
+                for (final Object key : keys) {
+                    Object res;
+
+                    try (Transaction tx = testedGrid().transactions().txStart(conc, isolation)) {
+                        res = cache.invoke(key, INC_ENTRY_PROC_BINARY_OBJ, dataMode);
+
+                        tx.commit();
+                    }
+
+                    assertNull(res);
+
+                    assertEquals(value(0), deserializeBinary(cache.get(key)));
+
+                    try (Transaction tx = testedGrid().transactions().txStart(conc, isolation)) {
+                        res = cache.invoke(key, INC_ENTRY_PROC_BINARY_OBJ, dataMode);
+
+                        tx.commit();
+                    }
+
+                    assertEquals(value(0), deserializeBinary(res));
+
+                    assertEquals(value(1), deserializeBinary(cache.get(key)));
+
+                    try (Transaction tx = testedGrid().transactions().txStart(conc, isolation)) {
+                        assertTrue(cache.remove(key));
+
+                        tx.commit();
+                    }
+                }
+
+                // TODO IGNITE-2973: should be always false.
+                interceptorBinaryObjExp = atomicityMode() == TRANSACTIONAL;
+
+                try {
+                    for (final Object key : keys) {
+                        Object res;
+
+                        try (Transaction tx = testedGrid().transactions().txStart(conc, isolation)) {
+                            res = cache.invoke(key, INC_ENTRY_PROC_USER_OBJ, dataMode);
+
+                            tx.commit();
+                        }
+
+                        assertNull(res);
+
+                        assertEquals(value(0), deserializeBinary(cache.get(key)));
+
+                        try (Transaction tx = testedGrid().transactions().txStart(conc, isolation)) {
+                            res = cache.invoke(key, INC_ENTRY_PROC_USER_OBJ, dataMode);
+
+                            tx.commit();
+                        }
+
+                        // TODO IGNITE-2953: uncomment the following assert when the issue will be fixed.
+//                               assertEquals(value(0), res);
+
+                        assertEquals(value(1), deserializeBinary(cache.get(key)));
+
+                        try (Transaction tx = testedGrid().transactions().txStart(conc, isolation)) {
+                            assertTrue(cache.remove(key));
+
+                            tx.commit();
+                        }
+                    }
+                }
+                finally {
+                    interceptorBinaryObjExp = true;
+                }
+            }
+        }, PLANE_OBJECT, SERIALIZABLE);
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    @SuppressWarnings("serial")
+    public void testInvokeAsync() throws Exception {
+        runInAllDataModes(new TestRunnable() {
+            @Override public void run() throws Exception {
+                final IgniteCache cache = jcache().withKeepBinary().withAsync();
+
+                Set keys = new LinkedHashSet() {{
+                    for (int i = 0; i < CNT; i++)
+                        add(key(i));
+                }};
+
+                for (final Object key : keys) {
+                    cache.invoke(key, NOOP_ENTRY_PROC);
+
+                    Object res = cache.future().get();
+
+                    assertNull(res);
+
+                    cache.get(key);
+
+                    assertNull(cache.future().get());
+                }
+
+                for (final Object key : keys) {
+                    cache.invoke(key, INC_ENTRY_PROC_BINARY_OBJ, dataMode);
+
+                    Object res = cache.future().get();
+
+                    assertNull(res);
+
+                    cache.get(key);
+
+                    assertEquals(value(0), deserializeBinary(cache.future().get()));
+
+                    cache.invoke(key, INC_ENTRY_PROC_BINARY_OBJ, dataMode);
+
+                    res = cache.future().get();
+
+                    assertEquals(value(0), deserializeBinary(res));
+
+                    cache.get(key);
+
+                    assertEquals(value(1), deserializeBinary(cache.future().get()));
+
+                    cache.remove(key);
+
+                    assertTrue((Boolean)cache.future().get());
+                }
+
+                // TODO IGNITE-2973: should be always false.
+                interceptorBinaryObjExp = atomicityMode() == TRANSACTIONAL;
+
+                try {
+                    for (final Object key : keys) {
+                        cache.invoke(key, INC_ENTRY_PROC_USER_OBJ, dataMode);
+
+                        Object res = cache.future().get();
+
+                        assertNull(res);
+
+                        cache.get(key);
+
+                        assertEquals(value(0), deserializeBinary(cache.future().get()));
+
+                        cache.invoke(key, INC_ENTRY_PROC_USER_OBJ, dataMode);
+
+                        res = cache.future().get();
+
+                        // TODO IGNITE-2953: uncomment the following assert when the issue will be fixed.
+//                              assertEquals(value(0), res);
+
+                        cache.get(key);
+
+                        assertEquals(value(1), deserializeBinary(cache.future().get()));
+
+                        cache.remove(key);
+
+                        assertTrue((Boolean)cache.future().get());
+                    }
+                }
+                finally {
+                    interceptorBinaryObjExp = true;
+                }
+            }
+        }, PLANE_OBJECT, SERIALIZABLE);
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testInvokeAsyncTx() throws Exception {
+        if (!txShouldBeUsed())
+            return;
+
+        for (TransactionConcurrency conc : TransactionConcurrency.values()) {
+            for (TransactionIsolation isolation : TransactionIsolation.values()) {
+                // TODO IGNITE-2971: delete this if when the issue will be fixed.
+                if (conc == TransactionConcurrency.OPTIMISTIC && isolation == TransactionIsolation.SERIALIZABLE)
+                    continue;
+
+                checkInvokeAsyncTx(conc, isolation);
+
+                jcache().removeAll();
+            }
+        }
+    }
+
+    /**
+     * @param conc Concurrency.
+     * @param isolation Isolation.
+     * @throws Exception If failed.
+     */
+    @SuppressWarnings("serial")
+    public void checkInvokeAsyncTx(final TransactionConcurrency conc, final TransactionIsolation isolation) throws Exception {
+        runInAllDataModes(new TestRunnable() {
+            @Override public void run() throws Exception {
+                final IgniteCache cache = jcache().withKeepBinary().withAsync();
+
+                Set keys = new LinkedHashSet() {{
+                    for (int i = 0; i < CNT; i++)
+                        add(key(i));
+                }};
+
+                try (Transaction tx = testedGrid().transactions().txStart(conc, isolation)) {
+                    for (final Object key : keys) {
+                        cache.invoke(key, NOOP_ENTRY_PROC);
+
+                        Object res = cache.future().get();
+
+                        assertNull(res);
+
+                        cache.get(key);
+
+                        assertNull(cache.future().get());
+                    }
+
+                    tx.commit();
+                }
+
+                for (final Object key : keys) {
+                    Object res;
+
+                    try (Transaction tx = testedGrid().transactions().txStart(conc, isolation)) {
+                        cache.invoke(key, INC_ENTRY_PROC_BINARY_OBJ, dataMode);
+
+                        res = cache.future().get();
+
+                        tx.commit();
+                    }
+
+                    assertNull(res);
+
+                    cache.get(key);
+
+                    assertEquals(value(0), deserializeBinary(cache.future().get()));
+
+                    try (Transaction tx = testedGrid().transactions().txStart(conc, isolation)) {
+                        cache.invoke(key, INC_ENTRY_PROC_BINARY_OBJ, dataMode);
+
+                        tx.commit();
+                    }
+
+                    res = cache.future().get();
+
+                    assertEquals(value(0), deserializeBinary(res));
+
+                    cache.get(key);
+
+                    assertEquals(value(1), deserializeBinary(cache.future().get()));
+
+                    try (Transaction tx = testedGrid().transactions().txStart(conc, isolation)) {
+                        cache.remove(key);
+
+                        assertTrue((Boolean)cache.future().get());
+
+                        tx.commit();
+                    }
+                }
+
+                // TODO IGNITE-2973: should be always false.
+                interceptorBinaryObjExp = atomicityMode() == TRANSACTIONAL;
+
+                try {
+                    for (final Object key : keys) {
+                        Object res;
+
+                        try (Transaction tx = testedGrid().transactions().txStart(conc, isolation)) {
+                            cache.invoke(key, INC_ENTRY_PROC_USER_OBJ, dataMode);
+
+                            res = cache.future().get();
+
+                            tx.commit();
+                        }
+
+                        assertNull(res);
+
+                        cache.get(key);
+
+                        assertEquals(value(0), deserializeBinary(cache.future().get()));
+
+                        try (Transaction tx = testedGrid().transactions().txStart(conc, isolation)) {
+                            cache.invoke(key, INC_ENTRY_PROC_USER_OBJ, dataMode);
+
+                            res = cache.future().get();
+
+                            tx.commit();
+                        }
+
+                        // TODO IGNITE-2953: uncomment the following assert when the issue will be fixed.
+//                              assertEquals(value(0), res);
+
+                        cache.get(key);
+
+                        assertEquals(value(1), deserializeBinary(cache.future().get()));
+
+                        try (Transaction tx = testedGrid().transactions().txStart(conc, isolation)) {
+                            cache.remove(key);
+
+                            assertTrue((Boolean)cache.future().get());
+
+                            tx.commit();
+                        }
+                    }
+                }
+                finally {
+                    interceptorBinaryObjExp = true;
+                }
+            }
+        }, PLANE_OBJECT, SERIALIZABLE);
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    @SuppressWarnings("serial")
+    public void testInvokeAll() throws Exception {
+        runInAllDataModes(new TestRunnable() {
+            @Override public void run() throws Exception {
+                final IgniteCache cache = jcache().withKeepBinary();
+
+                Set keys = new LinkedHashSet() {{
+                    for (int i = 0; i < CNT; i++)
+                        add(key(i));
+                }};
+
+                Map<Object, EntryProcessorResult<Object>> resMap = cache.invokeAll(keys, NOOP_ENTRY_PROC);
+
+                for (Map.Entry<Object, EntryProcessorResult<Object>> e : resMap.entrySet()) {
+                    assertTrue("Key:" + e.getKey(), e.getKey() instanceof BinaryObject);
+
+                    assertNull(e.getValue().get());
+                }
+
+                resMap = cache.invokeAll(keys, INC_ENTRY_PROC_BINARY_OBJ, dataMode);
+
+                checkInvokeAllResult(cache, resMap, null, value(0), true);
+
+                resMap = cache.invokeAll(keys, INC_ENTRY_PROC_BINARY_OBJ, dataMode);
+
+                checkInvokeAllResult(cache, resMap, value(0), value(1), true);
+
+                cache.removeAll(keys);
+
+                // TODO IGNITE-2973: should be always false.
+                interceptorBinaryObjExp = atomicityMode() == TRANSACTIONAL;
+
+                try {
+                    resMap = cache.invokeAll(keys, INC_ENTRY_PROC_USER_OBJ, dataMode);
+
+                    checkInvokeAllResult(cache, resMap, null, value(0), false);
+
+                    resMap = cache.invokeAll(keys, INC_ENTRY_PROC_USER_OBJ, dataMode);
+
+                    checkInvokeAllResult(cache, resMap, value(0), value(1), false);
+                }
+                finally {
+                    interceptorBinaryObjExp = true;
+                }
+            }
+        }, PLANE_OBJECT, SERIALIZABLE);
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    @SuppressWarnings("serial")
+    public void testInvokeAllTx() throws Exception {
+        if (!txShouldBeUsed())
+            return;
+
+        for (TransactionConcurrency conc : TransactionConcurrency.values()) {
+            for (TransactionIsolation isolation : TransactionIsolation.values()) {
+                checkInvokeAllTx(conc, isolation);
+
+                jcache().removeAll();
+            }
+        }
+    }
+
+    /**
+     * @param conc Concurrency.
+     * @param isol Isolation.
+     * @throws Exception If failed.
+     */
+    @SuppressWarnings("serial")
+    private void checkInvokeAllTx(final TransactionConcurrency conc, final TransactionIsolation isol) throws Exception {
+        if (!txShouldBeUsed())
+            return;
+
+        runInAllDataModes(new TestRunnable() {
+            @Override public void run() throws Exception {
+                final IgniteCache cache = jcache().withKeepBinary();
+
+                final Set keys = new LinkedHashSet() {{
+                    for (int i = 0; i < CNT; i++)
+                        add(key(i));
+                }};
+
+                try (Transaction tx = testedGrid().transactions().txStart(conc, isol)) {
+                    Map<Object, EntryProcessorResult<Object>> resMap = cache.invokeAll(keys, NOOP_ENTRY_PROC);
+
+                    for (Map.Entry<Object, EntryProcessorResult<Object>> e : resMap.entrySet()) {
+                        assertTrue("Key:" + e.getKey(), e.getKey() instanceof BinaryObject);
+
+                        assertNull(e.getValue().get());
+                    }
+
+                    tx.commit();
+                }
+
+                Map<Object, EntryProcessorResult<Object>> resMap;
+
+                try (Transaction tx = testedGrid().transactions().txStart(conc, isol)) {
+                    resMap = cache.invokeAll(keys, INC_ENTRY_PROC_BINARY_OBJ, dataMode);
+
+                    tx.commit();
+                }
+
+                checkInvokeAllResult(cache, resMap, null, value(0), true);
+
+                try (Transaction tx = testedGrid().transactions().txStart(conc, isol)) {
+                    resMap = cache.invokeAll(keys, INC_ENTRY_PROC_BINARY_OBJ, dataMode);
+
+                    tx.commit();
+                }
+
+                checkInvokeAllResult(cache, resMap, value(0), value(1), true);
+
+                try (Transaction tx = testedGrid().transactions().txStart(conc, isol)) {
+                    cache.removeAll(keys);
+
+                    tx.commit();
+                }
+
+                // TODO IGNITE-2973: should be always false.
+                interceptorBinaryObjExp = atomicityMode() == TRANSACTIONAL;
+
+                try {
+                    try (Transaction tx = testedGrid().transactions().txStart(conc, isol)) {
+                        resMap = cache.invokeAll(keys, INC_ENTRY_PROC_USER_OBJ, dataMode);
+
+                        tx.commit();
+                    }
+
+                    checkInvokeAllResult(cache, resMap, null, value(0), false);
+
+                    try (Transaction tx = testedGrid().transactions().txStart(conc, isol)) {
+                        resMap = cache.invokeAll(keys, INC_ENTRY_PROC_USER_OBJ, dataMode);
+
+                        tx.commit();
+                    }
+
+                    checkInvokeAllResult(cache, resMap, value(0), value(1), false);
+
+                    try (Transaction tx = testedGrid().transactions().txStart(conc, isol)) {
+                        cache.removeAll(keys);
+
+                        tx.commit();
+                    }
+                }
+                finally {
+                    interceptorBinaryObjExp = true;
+                }
+            }
+        }, PLANE_OBJECT, SERIALIZABLE);
+    }
+
+    /**
+     * @param cache Cache.
+     * @param resMap Result map.
+     * @param expRes Expected result.
+     * @param cacheVal Expected cache value for key.
+     * @param deserializeRes Deseriallize result flag.
+     */
+    private void checkInvokeAllResult(IgniteCache cache, Map<Object, EntryProcessorResult<Object>> resMap,
+        Object expRes, Object cacheVal, boolean deserializeRes) {
+        for (Map.Entry<Object, EntryProcessorResult<Object>> e : resMap.entrySet()) {
+            info("Key: " + e.getKey());
+
+            assertTrue("Wrong key type, binary object expected: " + e.getKey(), e.getKey() instanceof BinaryObject);
+
+            Object res = e.getValue().get();
+
+            // TODO IGNITE-2953: delete the following if when the issue wiil be fixed.
+            if (deserializeRes)
+                assertEquals(expRes, deserializeRes ? deserializeBinary(res) : res);
+
+            if (cache.get(e.getKey()) == null)
+                cache.get(e.getKey());
+
+            assertEquals(cacheVal, deserializeBinary(cache.get(e.getKey())));
+        }
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    @SuppressWarnings("serial")
+    public void testInvokeAllAsync() throws Exception {
+        runInAllDataModes(new TestRunnable() {
+            @Override public void run() throws Exception {
+                final IgniteCache cache = jcache().withKeepBinary().withAsync();
+
+                final Set keys = new LinkedHashSet() {{
+                    for (int i = 0; i < CNT; i++)
+                        add(key(i));
+                }};
+
+                cache.invokeAll(keys, NOOP_ENTRY_PROC);
+
+                Map<Object, EntryProcessorResult<Object>> resMap =
+                    (Map<Object, EntryProcessorResult<Object>>)cache.future().get();
+
+                for (Map.Entry<Object, EntryProcessorResult<Object>> e : resMap.entrySet()) {
+                    assertTrue("Wrong key type, binary object expected: " + e.getKey(), e.getKey() instanceof BinaryObject);
+
+                    assertNull(e.getValue().get());
+                }
+
+                cache.invokeAll(keys, INC_ENTRY_PROC_BINARY_OBJ, dataMode);
+
+                resMap = (Map<Object, EntryProcessorResult<Object>>)cache.future().get();
+
+                checkInvokeAllAsyncResult(cache, resMap, null, value(0), true);
+
+                cache.invokeAll(keys, INC_ENTRY_PROC_BINARY_OBJ, dataMode);
+
+                resMap = (Map<Object, EntryProcessorResult<Object>>)cache.future().get();
+
+                checkInvokeAllAsyncResult(cache, resMap, value(0), value(1), true);
+
+                cache.removeAll(keys);
+
+                cache.future().get();
+
+                // TODO IGNITE-2973: should be always false.
+                interceptorBinaryObjExp = atomicityMode() == TRANSACTIONAL;
+
+                try {
+                    cache.invokeAll(keys, INC_ENTRY_PROC_USER_OBJ, dataMode);
+
+                    resMap = (Map<Object, EntryProcessorResult<Object>>)cache.future().get();
+
+                    checkInvokeAllAsyncResult(cache, resMap, null, value(0), false);
+
+                    cache.invokeAll(keys, INC_ENTRY_PROC_USER_OBJ, dataMode);
+
+                    resMap = (Map<Object, EntryProcessorResult<Object>>)cache.future().get();
+
+                    checkInvokeAllAsyncResult(cache, resMap, value(0), value(1), false);
+
+                    cache.removeAll(keys);
+
+                    cache.future().get();
+                }
+                finally {
+                    interceptorBinaryObjExp = true;
+                }
+            }
+        }, PLANE_OBJECT, SERIALIZABLE);
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    @SuppressWarnings("serial")
+    public void testInvokeAllAsyncTx() throws Exception {
+        if (!txShouldBeUsed())
+            return;
+
+        for (TransactionConcurrency conc : TransactionConcurrency.values()) {
+            for (TransactionIsolation isolation : TransactionIsolation.values()) {
+                checkInvokeAllAsycnTx(conc, isolation);
+
+                jcache().removeAll();
+            }
+        }
+    }
+
+    /**
+     *
+     * @param conc Concurrency.
+     * @param isolation Isolation.
+     * @throws Exception
+     */
+    private void checkInvokeAllAsycnTx(final TransactionConcurrency conc, final TransactionIsolation isolation) throws Exception {
+        runInAllDataModes(new TestRunnable() {
+            @Override public void run() throws Exception {
+                final IgniteCache cache = jcache().withKeepBinary().withAsync();
+
+                final Set keys = new LinkedHashSet() {{
+                    for (int i = 0; i < CNT; i++)
+                        add(key(i));
+                }};
+
+                Map<Object, EntryProcessorResult<Object>> resMap;
+
+                try (Transaction tx = testedGrid().transactions().txStart(conc, isolation)) {
+                    cache.invokeAll(keys, NOOP_ENTRY_PROC);
+
+                    resMap = (Map<Object, EntryProcessorResult<Object>>)cache.future().get();
+
+                    tx.commit();
+                }
+
+                for (Map.Entry<Object, EntryProcessorResult<Object>> e : resMap.entrySet()) {
+                    assertTrue("Key:" + e.getKey(), e.getKey() instanceof BinaryObject);
+
+                    assertNull(e.getValue().get());
+                }
+
+                try (Transaction tx = testedGrid().transactions().txStart(conc, isolation)) {
+                    cache.invokeAll(keys, INC_ENTRY_PROC_BINARY_OBJ, dataMode);
+
+                    resMap = (Map<Object, EntryProcessorResult<Object>>)cache.future().get();
+
+                    tx.commit();
+                }
+
+                checkInvokeAllAsyncResult(cache, resMap, null, value(0), true);
+
+                try (Transaction tx = testedGrid().transactions().txStart(conc, isolation)) {
+                    cache.invokeAll(keys, INC_ENTRY_PROC_BINARY_OBJ, dataMode);
+
+                    resMap = (Map<Object, EntryProcessorResult<Object>>)cache.future().get();
+
+                    tx.commit();
+                }
+
+                checkInvokeAllAsyncResult(cache, resMap, value(0), value(1), true);
+
+                try (Transaction tx = testedGrid().transactions().txStart(conc, isolation)) {
+                    cache.removeAll(keys);
+
+                    cache.future().get();
+
+                    tx.commit();
+                }
+
+                // TODO IGNITE-2973: should be always false.
+                interceptorBinaryObjExp = atomicityMode() == TRANSACTIONAL;
+
+                try {
+                    try (Transaction tx = testedGrid().transactions().txStart(conc, isolation)) {
+                        cache.invokeAll(keys, INC_ENTRY_PROC_USER_OBJ, dataMode);
+
+                        resMap = (Map<Object, EntryProcessorResult<Object>>)cache.future().get();
+
+                        tx.commit();
+                    }
+
+                    checkInvokeAllAsyncResult(cache, resMap, null, value(0), false);
+
+                    try (Transaction tx = testedGrid().transactions().txStart(conc, isolation)) {
+                        cache.invokeAll(keys, INC_ENTRY_PROC_USER_OBJ, dataMode);
+
+                        resMap = (Map<Object, EntryProcessorResult<Object>>)cache.future().get();
+
+                        tx.commit();
+                    }
+
+                    checkInvokeAllAsyncResult(cache, resMap, value(0), value(1), false);
+
+                    try (Transaction tx = testedGrid().transactions().txStart(conc, isolation)) {
+                        cache.removeAll(keys);
+
+                        cache.future().get();
+
+                        tx.commit();
+                    }
+                }
+                finally {
+                    interceptorBinaryObjExp = true;
+                }
+            }
+        }, PLANE_OBJECT, SERIALIZABLE);
+    }
+
+    /**
+     * @param cache Cache.
+     * @param resMap Result map.
+     * @param expRes Expected result.
+     * @param cacheVal Expected cache value for key.
+     * @param deserializeRes Deseriallize result flag.
+     */
+    private void checkInvokeAllAsyncResult(IgniteCache cache, Map<Object, EntryProcessorResult<Object>> resMap,
+        Object expRes, Object cacheVal, boolean deserializeRes) {
+        for (Map.Entry<Object, EntryProcessorResult<Object>> e : resMap.entrySet()) {
+            info("Key: " + e.getKey());
+
+            assertTrue("Wrong key type, binary object expected: " + e.getKey(), e.getKey() instanceof BinaryObject);
+
+            Object res = e.getValue().get();
+
+            // TODO IGNITE-2953: delete the following if when the issue wiil be fixed.
+            if (deserializeRes)
+                assertEquals(expRes, deserializeRes ? deserializeBinary(res) : res);
+
+            cache.get(e.getKey());
+
+            assertEquals(cacheVal, deserializeBinary(cache.future().get()));
+        }
+    }
+
+    /**
+     * @param val Value
+     * @return User object.
+     */
+    private static Object deserializeBinary(Object val) {
+        assertTrue("Val: " + val, val instanceof BinaryObject);
+
+        return ((BinaryObject)val).deserialize();
+    }
+
+    /**
+     * @param task Task.
+     */
+    protected void runInAllTxModes(TestRunnable task) throws Exception {
+        info("Executing implicite tx");
+
+        task.run();
+
+        if (txShouldBeUsed()) {
+            for (TransactionConcurrency conc : TransactionConcurrency.values()) {
+                for (TransactionIsolation isolation : TransactionIsolation.values()) {
+                    try (Transaction tx = testedGrid().transactions().txStart(conc, isolation)) {
+                        info("Executing explicite tx [isolation" + isolation + ", concurrency=" + conc + "]");
+
+                        task.run();
+
+                        tx.commit();
+                    }
+                }
+            }
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/8e49e701/modules/core/src/test/java/org/apache/ignite/internal/processors/compute/IgniteComputeConfigVariationsFullApiTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/compute/IgniteComputeConfigVariationsFullApiTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/compute/IgniteComputeConfigVariationsFullApiTest.java
index 81cdb15..485e811 100644
--- a/modules/core/src/test/java/org/apache/ignite/internal/processors/compute/IgniteComputeConfigVariationsFullApiTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/compute/IgniteComputeConfigVariationsFullApiTest.java
@@ -361,16 +361,18 @@ public class IgniteComputeConfigVariationsFullApiTest extends IgniteConfigVariat
     public void testApplyForCollection() throws Exception {
         runTest(closureFactories, new ComputeTest() {
             @Override public void test(Factory factory, Ignite ignite) throws Exception {
-                Collection<TestObject> params = new ArrayList<>(MAX_JOB_COUNT);
+                Collection params = new ArrayList<>(MAX_JOB_COUNT);
 
                 for (int i = 0; i < MAX_JOB_COUNT; ++i) {
                     // value(i - 1): use negative argument of the value method to generate nullong value.
-                    // Use type casting to avoid ambiguous for apply(Callable, Object) vs apply(Callable, Collection<Object>).
-                    params.add((TestObject)value(i - 1));
+                    params.add(value(i - 1));
                 }
 
-                Collection<Object> results = ignite.compute()
-                    .apply((IgniteClosure<TestObject, Object>)factory.create(), params);
+                IgniteClosure c = (IgniteClosure)factory.create();
+
+                // Use type casting to avoid ambiguous for apply(Callable, Object) vs apply(Callable, Collection<Object>).
+                Collection<Object> results = ignite.compute().apply((IgniteClosure<TestObject, Object>)c,
+                    (Collection<TestObject>)params);
 
                 checkResultsClassCount(MAX_JOB_COUNT - 1, results, value(0).getClass());
                 assertCollectionsEquals("Results value mismatch", createGoldenResults(), results);

http://git-wip-us.apache.org/repos/asf/ignite/blob/8e49e701/modules/core/src/test/java/org/apache/ignite/testframework/configvariations/ConfigVariationsTestSuiteBuilder.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/testframework/configvariations/ConfigVariationsTestSuiteBuilder.java b/modules/core/src/test/java/org/apache/ignite/testframework/configvariations/ConfigVariationsTestSuiteBuilder.java
index b20cb0e..4a60671 100644
--- a/modules/core/src/test/java/org/apache/ignite/testframework/configvariations/ConfigVariationsTestSuiteBuilder.java
+++ b/modules/core/src/test/java/org/apache/ignite/testframework/configvariations/ConfigVariationsTestSuiteBuilder.java
@@ -246,6 +246,15 @@ public class ConfigVariationsTestSuiteBuilder {
     }
 
     /**
+     * All tests will be run for first {@code testedNodeCnt} grids. For {@code grid(0)}, {@code grid(1)}, ... ,
+     * {@code grid(testedNodeCnt - 1)}.
+     * <p>
+     * Usually it needs if you want to execute tests for both client and data nodes (see {@link #withClients()}).
+     * <ul>
+     * <li> If test-class extends {@link IgniteConfigVariationsAbstractTest} then use {@code testedNodesCount(2)}. </li>
+     * <li> if test-class extends {@link IgniteCacheConfigVariationsAbstractTest} then use {@code testedNodesCount(3)}. </li>
+     *</ul>
+     *
      * @param testedNodeCnt Tested node count.
      * @return {@code this} for chaining.
      */

http://git-wip-us.apache.org/repos/asf/ignite/blob/8e49e701/modules/core/src/test/java/org/apache/ignite/testframework/junits/IgniteCacheConfigVariationsAbstractTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/testframework/junits/IgniteCacheConfigVariationsAbstractTest.java b/modules/core/src/test/java/org/apache/ignite/testframework/junits/IgniteCacheConfigVariationsAbstractTest.java
index 6b52578..bcea603 100644
--- a/modules/core/src/test/java/org/apache/ignite/testframework/junits/IgniteCacheConfigVariationsAbstractTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/testframework/junits/IgniteCacheConfigVariationsAbstractTest.java
@@ -94,7 +94,7 @@ public abstract class IgniteCacheConfigVariationsAbstractTest extends IgniteConf
                     IgniteConfiguration cfg = optimize(getConfiguration(gridName));
 
                     if (i != CLIENT_NODE_IDX && i != CLIENT_NEAR_ONLY_IDX) {
-                        CacheConfiguration cc = testsCfg.configurationFactory().cacheConfiguration(gridName);
+                        CacheConfiguration cc = cacheConfiguration();
 
                         cc.setName(cacheName());
 
@@ -125,20 +125,20 @@ public abstract class IgniteCacheConfigVariationsAbstractTest extends IgniteConf
             info("Grid " + i + ": " + grid(i).localNode().id());
 
         if (testsCfg.withClients()) {
-            boolean testedNodeNearEnabled = grid(testedNodeIdx).cachex(cacheName()).context().isNear();
-
             if (testedNodeIdx != SERVER_NODE_IDX)
-                assertEquals(testedNodeIdx == CLIENT_NEAR_ONLY_IDX, testedNodeNearEnabled);
+                assertEquals(testedNodeIdx == CLIENT_NEAR_ONLY_IDX, nearEnabled());
 
             info(">>> Starting set of tests [testedNodeIdx=" + testedNodeIdx
                 + ", id=" + grid(testedNodeIdx).localNode().id()
                 + ", isClient=" + isClientMode()
-                + ", nearEnabled=" + testedNodeNearEnabled + "]");
+                + ", nearEnabled=" + nearEnabled() + "]");
         }
     }
 
     /**
-     * Starts caches dinamically.
+     * Starts caches dynamically.
+     *
+     * @throws Exception If failed.
      */
     private void startCachesDinamically() throws Exception {
         for (int i = 0; i < gridCount(); i++) {
@@ -147,14 +147,14 @@ public abstract class IgniteCacheConfigVariationsAbstractTest extends IgniteConf
             IgniteEx grid = grid(i);
 
             if (i != CLIENT_NODE_IDX && i != CLIENT_NEAR_ONLY_IDX) {
-                CacheConfiguration cc = testsCfg.configurationFactory().cacheConfiguration(grid.name());
+                CacheConfiguration cc = cacheConfiguration();
 
                 cc.setName(cacheName());
 
                 grid.getOrCreateCache(cc);
             }
 
-            if (testsCfg.withClients() && i == CLIENT_NEAR_ONLY_IDX)
+            if (testsCfg.withClients() && i == CLIENT_NEAR_ONLY_IDX && grid(i).configuration().isClientMode())
                 grid(CLIENT_NEAR_ONLY_IDX).createNearCache(cacheName(), new NearCacheConfiguration());
         }
 


[05/17] ignite git commit: ignite-2899 Fixed issues with 'keepBinary' handling. This closes #593. (cherry picked from commit ee7e2c7)

Posted by dm...@apache.org.
http://git-wip-us.apache.org/repos/asf/ignite/blob/8e49e701/modules/core/src/test/java/org/apache/ignite/testframework/junits/IgniteConfigVariationsAbstractTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/testframework/junits/IgniteConfigVariationsAbstractTest.java b/modules/core/src/test/java/org/apache/ignite/testframework/junits/IgniteConfigVariationsAbstractTest.java
index 51fcfcf..572a80e 100644
--- a/modules/core/src/test/java/org/apache/ignite/testframework/junits/IgniteConfigVariationsAbstractTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/testframework/junits/IgniteConfigVariationsAbstractTest.java
@@ -33,6 +33,7 @@ import org.apache.ignite.binary.BinaryWriter;
 import org.apache.ignite.binary.Binarylizable;
 import org.apache.ignite.configuration.IgniteConfiguration;
 import org.apache.ignite.internal.IgniteEx;
+import org.apache.ignite.internal.util.typedef.F;
 import org.apache.ignite.internal.util.typedef.internal.U;
 import org.apache.ignite.marshaller.jdk.JdkMarshaller;
 import org.apache.ignite.testframework.configvariations.VariationsTestsConfig;
@@ -144,6 +145,8 @@ public abstract class IgniteConfigVariationsAbstractTest extends GridCommonAbstr
 
     /** {@inheritDoc} */
     @Override protected String testClassDescription() {
+        assert testsCfg != null: "Tests should be run using test suite.";
+
         return super.testClassDescription() + '-' + testsCfg.description() + '-' + testsCfg.gridCount() + "-node(s)";
     }
 
@@ -220,17 +223,22 @@ public abstract class IgniteConfigVariationsAbstractTest extends GridCommonAbstr
 
     /**
      * Runs in all data modes.
+     *
+     * @throws Exception If failed.
      */
-    protected void runInAllDataModes(TestRunnable call) throws Exception {
-        for (int i = 0; i < DataMode.values().length; i++) {
-            dataMode = DataMode.values()[i];
+    protected void runInAllDataModes(TestRunnable call, DataMode... dataModes) throws Exception {
+        if (F.isEmpty(dataModes))
+            dataModes = DataMode.values();
+
+        for (int i = 0; i < dataModes.length; i++) {
+            dataMode = dataModes[i];
 
             if (!isCompatible()) {
                 info("Skipping test in data mode: " + dataMode);
 
                 continue;
             }
-            
+
             info("Running test in data mode: " + dataMode);
 
             if (i != 0)
@@ -239,6 +247,11 @@ public abstract class IgniteConfigVariationsAbstractTest extends GridCommonAbstr
             try {
                 call.run();
             }
+            catch (Throwable e) {
+                e.printStackTrace();
+
+                throw e;
+            }
             finally {
                 if (i + 1 != DataMode.values().length)
                     afterTest();
@@ -276,10 +289,12 @@ public abstract class IgniteConfigVariationsAbstractTest extends GridCommonAbstr
         switch (mode) {
             case SERIALIZABLE:
                 return new SerializableObject(keyId);
+            case CUSTOM_SERIALIZABLE:
+                return new CustomSerializableObject(keyId);
             case EXTERNALIZABLE:
                 return new ExternalizableObject(keyId);
             case PLANE_OBJECT:
-                return new TestObject(keyId);
+                return new PlaneObject(keyId);
             case BINARILIZABLE:
                 return new BinarylizableObject(keyId);
             default:
@@ -292,6 +307,8 @@ public abstract class IgniteConfigVariationsAbstractTest extends GridCommonAbstr
      * @return Value.
      */
     public static int valueOf(Object obj) {
+        assertNotNull(obj);
+
         if (obj instanceof TestObject)
             return ((TestObject)obj).value();
         else
@@ -310,10 +327,12 @@ public abstract class IgniteConfigVariationsAbstractTest extends GridCommonAbstr
         switch (mode) {
             case SERIALIZABLE:
                 return new SerializableObject(idx);
+            case CUSTOM_SERIALIZABLE:
+                return new CustomSerializableObject(idx);
             case EXTERNALIZABLE:
                 return new ExternalizableObject(idx);
             case PLANE_OBJECT:
-                return new TestObject(idx);
+                return new PlaneObject(idx);
             case BINARILIZABLE:
                 return new BinarylizableObject(idx);
             default:
@@ -324,7 +343,17 @@ public abstract class IgniteConfigVariationsAbstractTest extends GridCommonAbstr
     /**
      *
      */
-    public static class TestObject {
+    public static interface TestObject {
+        /**
+         * @return Value.
+         */
+        public int value();
+    }
+
+    /**
+     *
+     */
+    public static class PlaneObject implements TestObject {
         /** */
         protected int val;
 
@@ -337,14 +366,14 @@ public abstract class IgniteConfigVariationsAbstractTest extends GridCommonAbstr
         /**
          * Default constructor must be accessible for deserialize subclasses by JDK serialization API.
          */
-        TestObject() {
+        PlaneObject() {
             // No-op.
         }
 
         /**
          * @param val Value.
          */
-        TestObject(int val) {
+        PlaneObject(int val) {
             this.val = val;
             strVal = "val" + val;
 
@@ -352,10 +381,76 @@ public abstract class IgniteConfigVariationsAbstractTest extends GridCommonAbstr
             enumVal = values[Math.abs(val) % values.length];
         }
 
+        /** {@inheritDoc} */
+        @Override public int value() {
+            return val;
+        }
+
+        /** {@inheritDoc} */
+        @Override public boolean equals(Object o) {
+            if (this == o)
+                return true;
+
+            if (!(o instanceof PlaneObject))
+                return false;
+
+            PlaneObject val = (PlaneObject)o;
+
+            return getClass().equals(o.getClass()) && this.val == val.val && enumVal == val.enumVal
+                && strVal.equals(val.strVal);
+        }
+
+        /** {@inheritDoc} */
+        @Override public int hashCode() {
+            return val;
+        }
+
+        /** {@inheritDoc} */
+        @Override public String toString() {
+            return getClass().getSimpleName() + "[" +
+                "val=" + val +
+                ", strVal='" + strVal + '\'' +
+                ", enumVal=" + enumVal +
+                ']';
+        }
+    }
+
+    /**
+     *
+     */
+    protected static class SerializableObject implements Serializable, TestObject {
+        /** */
+        private static final long serialVersionUID = 0;
+
+        /** */
+        protected int val;
+
+        /** */
+        protected String strVal;
+
+        /** */
+        protected TestEnum enumVal;
+
+        /**
+         * Default constructor.
+         */
+        public SerializableObject() {
+            // No-op.
+        }
+
         /**
-         * @return Value.
+         * @param val Value.
          */
-        public int value() {
+        public SerializableObject(int val) {
+            this.val = val;
+            strVal = "val" + val;
+
+            TestEnum[] values = TestEnum.values();
+            enumVal = values[Math.abs(val) % values.length];
+        }
+
+        /** {@inheritDoc} */
+        @Override public int value() {
             return val;
         }
 
@@ -364,10 +459,10 @@ public abstract class IgniteConfigVariationsAbstractTest extends GridCommonAbstr
             if (this == o)
                 return true;
 
-            if (!(o instanceof TestObject))
+            if (!(o instanceof SerializableObject))
                 return false;
 
-            TestObject val = (TestObject)o;
+            SerializableObject val = (SerializableObject)o;
 
             return getClass().equals(o.getClass()) && this.val == val.val && enumVal == val.enumVal
                 && strVal.equals(val.strVal);
@@ -391,16 +486,26 @@ public abstract class IgniteConfigVariationsAbstractTest extends GridCommonAbstr
     /**
      *
      */
-    protected static class SerializableObject extends TestObject implements Serializable {
+    protected static class CustomSerializableObject extends PlaneObject implements Serializable {
+        /** */
+        private static final long serialVersionUID = 0;
+
+        /**
+         * Default constructor.
+         */
+        public CustomSerializableObject() {
+            // No-op.
+        }
+
         /**
          * @param val Value.
          */
-        public SerializableObject(int val) {
+        public CustomSerializableObject(int val) {
             super(val);
         }
 
         /**
-         * Custom serialization of superclass because {@link TestObject} is non-serializable.
+         * Custom serialization of superclass because {@link PlaneObject} is non-serializable.
          *
          * @param out output stream.
          * @throws IOException if de-serialization failed.
@@ -412,7 +517,7 @@ public abstract class IgniteConfigVariationsAbstractTest extends GridCommonAbstr
         }
 
         /**
-         * Custom deserialization of superclass because {@link TestObject} is non-serializable.
+         * Custom deserialization of superclass because {@link PlaneObject} is non-serializable.
          *
          * @param in input stream
          * @throws IOException if de-serialization failed.
@@ -428,11 +533,14 @@ public abstract class IgniteConfigVariationsAbstractTest extends GridCommonAbstr
     /**
      *
      */
-    private static class ExternalizableObject extends TestObject implements Externalizable {
+    private static class ExternalizableObject extends PlaneObject implements Externalizable {
+        /** */
+        private static final long serialVersionUID = 0;
+
         /**
          * Default constructor.
          */
-        ExternalizableObject() {
+        public ExternalizableObject() {
             super(-1);
         }
 
@@ -461,7 +569,7 @@ public abstract class IgniteConfigVariationsAbstractTest extends GridCommonAbstr
     /**
      *
      */
-    public static class BinarylizableObject extends TestObject implements Binarylizable {
+    public static class BinarylizableObject extends PlaneObject implements Binarylizable {
         /**
          * Default constructor.
          */
@@ -476,12 +584,14 @@ public abstract class IgniteConfigVariationsAbstractTest extends GridCommonAbstr
             super(val);
         }
 
+        /** {@inheritDoc} */
         @Override public void writeBinary(BinaryWriter writer) throws BinaryObjectException {
             writer.writeInt("val", val);
             writer.writeString("strVal", strVal);
             writer.writeEnum("enumVal", enumVal);
         }
 
+        /** {@inheritDoc} */
         @Override public void readBinary(BinaryReader reader) throws BinaryObjectException {
             val = reader.readInt("val");
             strVal = reader.readString("strVal");
@@ -496,6 +606,9 @@ public abstract class IgniteConfigVariationsAbstractTest extends GridCommonAbstr
         /** Serializable objects. */
         SERIALIZABLE,
 
+        /** Serializable objects with custom serialization. */
+        CUSTOM_SERIALIZABLE,
+
         /** Externalizable objects. */
         EXTERNALIZABLE,
 
@@ -532,8 +645,9 @@ public abstract class IgniteConfigVariationsAbstractTest extends GridCommonAbstr
 
     /**
      * Check test compatibility with current data mode
-     * @return true if incompatible
-     * @throws Exception
+     *
+     * @return {@code True} if compatible.
+     * @throws Exception If failed.
      */
     protected boolean isCompatible() throws Exception {
         switch (dataMode) {

http://git-wip-us.apache.org/repos/asf/ignite/blob/8e49e701/modules/core/src/test/java/org/apache/ignite/testsuites/InterceptorCacheConfigVariationsFullApiTestSuite.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/testsuites/InterceptorCacheConfigVariationsFullApiTestSuite.java b/modules/core/src/test/java/org/apache/ignite/testsuites/InterceptorCacheConfigVariationsFullApiTestSuite.java
new file mode 100644
index 0000000..31fd365
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/testsuites/InterceptorCacheConfigVariationsFullApiTestSuite.java
@@ -0,0 +1,41 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ignite.testsuites;
+
+import junit.framework.TestSuite;
+import org.apache.ignite.internal.processors.cache.InterceptorCacheConfigVariationsFullApiTest;
+import org.apache.ignite.testframework.configvariations.ConfigVariationsTestSuiteBuilder;
+
+/**
+ * Test suite for cache API.
+ */
+public class InterceptorCacheConfigVariationsFullApiTestSuite extends TestSuite {
+    /**
+     * @return Cache API test suite.
+     * @throws Exception If failed.
+     */
+    public static TestSuite suite() throws Exception {
+        return new ConfigVariationsTestSuiteBuilder(
+            "Cache New Full API Test Suite with Interceptor",
+            InterceptorCacheConfigVariationsFullApiTest.class)
+            .withBasicCacheParams()
+            .gridsCount(5).backups(1)
+            .testedNodesCount(3).withClients()
+            .build();
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/8e49e701/modules/core/src/test/java/org/apache/ignite/testsuites/WithKeepBinaryCacheConfigVariationsFullApiTestSuite.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/testsuites/WithKeepBinaryCacheConfigVariationsFullApiTestSuite.java b/modules/core/src/test/java/org/apache/ignite/testsuites/WithKeepBinaryCacheConfigVariationsFullApiTestSuite.java
new file mode 100644
index 0000000..e557d77
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/testsuites/WithKeepBinaryCacheConfigVariationsFullApiTestSuite.java
@@ -0,0 +1,71 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ignite.testsuites;
+
+import junit.framework.TestSuite;
+import org.apache.ignite.configuration.IgniteConfiguration;
+import org.apache.ignite.internal.binary.BinaryMarshaller;
+import org.apache.ignite.internal.processors.cache.WithKeepBinaryCacheFullApiTest;
+import org.apache.ignite.lang.IgnitePredicate;
+import org.apache.ignite.testframework.configvariations.ConfigVariationsTestSuiteBuilder;
+
+/**
+ * Test suite for cache API.
+ */
+public class WithKeepBinaryCacheConfigVariationsFullApiTestSuite extends TestSuite {
+    /**
+     * @return Cache API test suite.
+     * @throws Exception If failed.
+     */
+    @SuppressWarnings("serial")
+    public static TestSuite suite() throws Exception {
+        TestSuite suite = new TestSuite("With Keep Binary Cache Config Variations Full API Test Suite");
+
+        suite.addTest(new ConfigVariationsTestSuiteBuilder(
+            "With Keep Binary Cache Test Suite",
+            WithKeepBinaryCacheFullApiTest.class)
+            .withBasicCacheParams()
+            .withIgniteConfigFilters(new IgnitePredicate<IgniteConfiguration>() {
+                @Override public boolean apply(IgniteConfiguration cfg) {
+                    return cfg.getMarshaller() instanceof BinaryMarshaller;
+                }
+            })
+            .gridsCount(5)
+            .backups(1)
+            .testedNodesCount(3).withClients()
+            .build()
+        );
+
+        suite.addTest(new ConfigVariationsTestSuiteBuilder(
+            "With Keep Binary Cache with Interceptor Test Suite",
+            WithKeepBinaryCacheFullApiTest.class)
+            .withBasicCacheParams()
+            .withIgniteConfigFilters(new IgnitePredicate<IgniteConfiguration>() {
+                @Override public boolean apply(IgniteConfiguration cfg) {
+                    return cfg.getMarshaller() instanceof BinaryMarshaller;
+                }
+            })
+            .gridsCount(5)
+            .backups(1)
+            .testedNodesCount(3).withClients()
+            .build()
+        );
+
+        return suite;
+    }
+}


[14/17] ignite git commit: Added trace logging for entry/offheap updates. (cherry picked from commit 9b2767f)

Posted by dm...@apache.org.
Added trace logging for entry/offheap updates.
(cherry picked from commit 9b2767f)


Project: http://git-wip-us.apache.org/repos/asf/ignite/repo
Commit: http://git-wip-us.apache.org/repos/asf/ignite/commit/e2db87bb
Tree: http://git-wip-us.apache.org/repos/asf/ignite/tree/e2db87bb
Diff: http://git-wip-us.apache.org/repos/asf/ignite/diff/e2db87bb

Branch: refs/heads/master
Commit: e2db87bb1b6c71d7978af17e9f2005ba1c661ab4
Parents: 30aa287
Author: sboikov <sb...@gridgain.com>
Authored: Wed May 25 10:06:43 2016 +0300
Committer: sboikov <sb...@gridgain.com>
Committed: Wed May 25 10:28:41 2016 +0300

----------------------------------------------------------------------
 .../processors/cache/GridCacheMapEntry.java     | 192 ++++++++++++++++---
 .../processors/cache/GridCacheSwapManager.java  |   6 +
 .../distributed/dht/GridDhtCacheEntry.java      |   8 +
 .../dht/GridDhtOffHeapCacheEntry.java           |   8 +
 .../atomic/GridDhtAtomicOffHeapCacheEntry.java  |   8 +
 .../GridDhtColocatedOffHeapCacheEntry.java      |   8 +
 .../offheap/GridOffHeapProcessor.java           |  12 ++
 7 files changed, 220 insertions(+), 22 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/e2db87bb/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheMapEntry.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheMapEntry.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheMapEntry.java
index 288d964..ee615b8 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheMapEntry.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheMapEntry.java
@@ -454,6 +454,13 @@ public abstract class GridCacheMapEntry extends GridMetadataAwareAdapter impleme
             if (cctx.swap().onOffheapEvict(key, entry, partition(), evictVer)) {
                 assert !hasValueUnlocked() : this;
 
+                if (log.isTraceEnabled()) {
+                    log.trace("onOffheapEvict evicted [key=" + key +
+                        ", entry=" + System.identityHashCode(this) +
+                        ", ptr=" + offHeapPointer() +
+                        ']');
+                }
+
                 obsolete = markObsolete0(obsoleteVer, false, null);
 
                 assert obsolete : this;
@@ -464,8 +471,16 @@ public abstract class GridCacheMapEntry extends GridMetadataAwareAdapter impleme
                     clearIndex(val);
                 }
             }
-            else
+            else {
                 obsolete = false;
+
+                if (log.isTraceEnabled()) {
+                    log.trace("onOffheapEvict not evicted [key=" + key +
+                        ", entry=" + System.identityHashCode(this) +
+                        ", ptr=" + offHeapPointer() +
+                        ']');
+                }
+            }
         }
 
         if (obsolete)
@@ -514,6 +529,21 @@ public abstract class GridCacheMapEntry extends GridMetadataAwareAdapter impleme
                 if (cctx.offheapTiered()) {
                     e = cctx.swap().readOffheapPointer(this);
 
+                    if (log.isTraceEnabled()) {
+                        if (e != null) {
+                            log.trace("Read offheap pointer [key=" + key +
+                                ", entry=" + System.identityHashCode(this) +
+                                ", ptr=" + e.offheapPointer() +
+                                ']');
+                        }
+                        else {
+                            log.trace("Read offheap pointer [key=" + key +
+                                ", entry=" + System.identityHashCode(this) +
+                                ", val=" + null +
+                                ']');
+                        }
+                    }
+
                     if (e != null) {
                         if (e.offheapPointer() > 0) {
                             offHeapPointer(e.offheapPointer());
@@ -530,11 +560,16 @@ public abstract class GridCacheMapEntry extends GridMetadataAwareAdapter impleme
                             offHeapPointer(0);
                     }
                 }
-                else
+                else {
                     e = cctx.swap().readAndRemove(this);
 
-                if (log.isDebugEnabled())
-                    log.debug("Read swap entry [swapEntry=" + e + ", cacheEntry=" + this + ']');
+                    if (log.isTraceEnabled()) {
+                        log.trace("unswap readAndRemove [key=" + key +
+                            ", entry=" + System.identityHashCode(this) +
+                            ", found=" + (e != null) +
+                            ']');
+                    }
+                }
 
                 flags |= IS_UNSWAPPED_MASK;
 
@@ -598,11 +633,20 @@ public abstract class GridCacheMapEntry extends GridMetadataAwareAdapter impleme
             boolean offheapPtr = hasOffHeapPointer();
 
             if (cctx.offheapTiered() && offheapPtr && !swapNeeded) {
-                if (log.isDebugEnabled())
-                    log.debug("Value did not change, skip write swap entry: " + this);
+                if (cctx.swap().offheapEvictionEnabled()) {
+                    if (log.isTraceEnabled()) {
+                        log.trace("enableOffheapEviction [key=" + key +
+                            ", entry=" + System.identityHashCode(this) +
+                            ", ptr=" + offHeapPointer() +
+                            ']');
+                    }
 
-                if (cctx.swap().offheapEvictionEnabled())
                     cctx.swap().enableOffheapEviction(key(), partition());
+                }
+                else {
+                    if (log.isTraceEnabled())
+                        log.trace("Value did not change, skip write swap entry: " + this);
+                }
 
                 return;
             }
@@ -622,6 +666,13 @@ public abstract class GridCacheMapEntry extends GridMetadataAwareAdapter impleme
 
             IgniteBiTuple<byte[], Byte> valBytes = valueBytes0();
 
+            if (log.isTraceEnabled()) {
+                log.trace("writeToOffheap [key=" + key +
+                    ", entry=" + System.identityHashCode(this) +
+                    ", ptr=" + offHeapPointer() +
+                    ']');
+            }
+
             cctx.swap().write(key(),
                 ByteBuffer.wrap(valBytes.get1()),
                 valBytes.get2(),
@@ -633,9 +684,6 @@ public abstract class GridCacheMapEntry extends GridMetadataAwareAdapter impleme
                 !offheapPtr);
 
             flags &= ~IS_SWAPPING_REQUIRED;
-
-            if (log.isDebugEnabled())
-                log.debug("Wrote swap entry: " + this);
         }
     }
 
@@ -671,10 +719,14 @@ public abstract class GridCacheMapEntry extends GridMetadataAwareAdapter impleme
         if (cctx.isSwapOrOffheapEnabled()) {
             assert Thread.holdsLock(this);
 
-            cctx.swap().remove(key(), partition());
+            if (log.isTraceEnabled()) {
+                log.trace("removeFromSwap [key=" + key +
+                    ", entry=" + System.identityHashCode(this) +
+                    ", ptr=" + offHeapPointer() +
+                    ']');
+            }
 
-            if (log.isDebugEnabled())
-                log.debug("Removed swap entry [entry=" + this + ']');
+            cctx.swap().remove(key(), partition());
         }
     }
 
@@ -943,8 +995,15 @@ public abstract class GridCacheMapEntry extends GridMetadataAwareAdapter impleme
 
                     update(ret, expTime, ttl, nextVer, true);
 
-                    if (hadValPtr && cctx.offheapTiered())
+                    if (hadValPtr && cctx.offheapTiered()) {
+                        if (log.isTraceEnabled()) {
+                            log.trace("innerGet removeOffheap [key=" + key +
+                                ", entry=" + System.identityHashCode(this) +
+                                ", ptr=" + offHeapPointer() + ']');
+                        }
+
                         cctx.swap().removeOffheap(key);
+                    }
 
                     if (cctx.deferredDelete() && deletedUnlocked() && !isInternal() && !detached())
                         deletedUnlocked(false);
@@ -1014,10 +1073,17 @@ public abstract class GridCacheMapEntry extends GridMetadataAwareAdapter impleme
 
                 // If version matched, set value.
                 if (startVer.equals(ver)) {
-                    releaseSwap();
-
                     CacheObject old = rawGetOrUnmarshalUnlocked(false);
 
+                    if (log.isTraceEnabled()) {
+                        log.trace("innerReload releaseSwap [key=" + key +
+                            ", entry=" + System.identityHashCode(this) +
+                            ", old=" + old +
+                            ", ptr=" + offHeapPointer() + ']');
+                    }
+
+                    releaseSwap();
+
                     long expTime = CU.toExpireTime(ttl);
 
                     // Detach value before index update.
@@ -1319,6 +1385,13 @@ public abstract class GridCacheMapEntry extends GridMetadataAwareAdapter impleme
             boolean startVer = isStartVersion();
 
             if (startVer) {
+                if (log.isTraceEnabled()) {
+                    log.trace("innerRemove releaseSwap [key=" + key +
+                        ", entry=" + System.identityHashCode(this) +
+                        ", ptr=" + offHeapPointer() +
+                        ']');
+                }
+
                 // Release swap.
                 releaseSwap();
             }
@@ -1437,6 +1510,14 @@ public abstract class GridCacheMapEntry extends GridMetadataAwareAdapter impleme
             if (cctx.offheapTiered() && hadValPtr) {
                 boolean rmv = cctx.swap().removeOffheap(key);
 
+                if (log.isTraceEnabled()) {
+                    log.trace("innerRemove remove offheap [key=" + key +
+                        ", entry=" + System.identityHashCode(this) +
+                        ", rmv=" + rmv +
+                        ", ptr=" + offHeapPointer() +
+                        ']');
+                }
+
                 assert rmv;
             }
 
@@ -1815,6 +1896,14 @@ public abstract class GridCacheMapEntry extends GridMetadataAwareAdapter impleme
             if (op != GridCacheOperation.UPDATE && cctx.offheapTiered() && hasValPtr) {
                 boolean rmv = cctx.swap().removeOffheap(key);
 
+                if (log.isTraceEnabled()) {
+                    log.trace("innerUpdateLocal remove offheap [key=" + key +
+                        ", entry=" + System.identityHashCode(this) +
+                        ", rmv=" + rmv +
+                        ", ptr=" + offHeapPointer() +
+                        ']');
+                }
+
                 assert rmv;
             }
         }
@@ -2309,6 +2398,13 @@ public abstract class GridCacheMapEntry extends GridMetadataAwareAdapter impleme
 
             // Actual update.
             if (op == GridCacheOperation.UPDATE) {
+                if (log.isTraceEnabled()) {
+                    log.trace("innerUpdate [key=" + key +
+                        ", entry=" + System.identityHashCode(this) +
+                        ", ptr=" + offHeapPointer() +
+                        ']');
+                }
+
                 if (intercept) {
                     updated0 = value(updated0, updated, keepBinary, false);
 
@@ -2527,6 +2623,14 @@ public abstract class GridCacheMapEntry extends GridMetadataAwareAdapter impleme
             if (op != GridCacheOperation.UPDATE && cctx.offheapTiered() && hasValPtr) {
                 boolean rmv = cctx.swap().removeOffheap(key);
 
+                if (log.isTraceEnabled()) {
+                    log.trace("innerUpdate remove offheap [key=" + key +
+                        ", entry=" + System.identityHashCode(this) +
+                        ", rmv=" + rmv +
+                        ", ptr=" + offHeapPointer() +
+                        ']');
+                }
+
                 assert rmv;
             }
         }
@@ -2697,8 +2801,12 @@ public abstract class GridCacheMapEntry extends GridMetadataAwareAdapter impleme
                 return false;
             }
 
-            if (log.isDebugEnabled())
-                log.debug("Entry has been marked obsolete: " + this);
+            if (log.isTraceEnabled()) {
+                log.trace("entry clear [key=" + key +
+                    ", entry=" + System.identityHashCode(this) +
+                    ", val=" + val +
+                    ", ptr=" + offHeapPointer() + ']');
+            }
 
             clearIndex(val);
 
@@ -2851,6 +2959,14 @@ public abstract class GridCacheMapEntry extends GridMetadataAwareAdapter impleme
 
                 if (clear)
                     value(null);
+
+                if (log.isTraceEnabled()) {
+                    log.trace("markObsolete0 [key=" + key +
+                        ", entry=" + System.identityHashCode(this) +
+                        ", ptr=" + offHeapPointer() +
+                        ", clear=" + clear +
+                        ']');
+                }
             }
 
             return obsoleteVer != null;
@@ -2888,6 +3004,14 @@ public abstract class GridCacheMapEntry extends GridMetadataAwareAdapter impleme
 
             ver = newVer;
 
+            if (log.isTraceEnabled()) {
+                log.trace("invalidate releaseSwap [key=" + key +
+                    ", entry=" + System.identityHashCode(this) +
+                    ", val=" + val +
+                    ", ptr=" + offHeapPointer() +
+                    ']');
+            }
+
             releaseSwap();
 
             clearIndex(val);
@@ -3206,10 +3330,13 @@ public abstract class GridCacheMapEntry extends GridMetadataAwareAdapter impleme
         if (expireTime > 0) {
             long delta = expireTime - U.currentTimeMillis();
 
-            if (log.isDebugEnabled())
-                log.debug("Checked expiration time for entry [timeLeft=" + delta + ", entry=" + this + ']');
-
             if (delta <= 0) {
+                if (log.isTraceEnabled()) {
+                    log.trace("checkExpired clear [key=" + key +
+                        ", entry=" + System.identityHashCode(this) +
+                        ", ptr=" + offHeapPointer() + ']');
+                }
+
                 releaseSwap();
 
                 clearIndex(saveValueForIndexUnlocked());
@@ -3737,6 +3864,12 @@ public abstract class GridCacheMapEntry extends GridMetadataAwareAdapter impleme
                 rmvd = true;
         }
 
+        if (log.isTraceEnabled()) {
+            log.trace("onExpired clear [key=" + key +
+                ", entry=" + System.identityHashCode(this) +
+                ", ptr=" + offHeapPointer() + ']');
+        }
+
         clearIndex(expiredVal);
 
         releaseSwap();
@@ -4152,6 +4285,13 @@ public abstract class GridCacheMapEntry extends GridMetadataAwareAdapter impleme
             flags &= ~IS_OFFHEAP_PTR_MASK;
 
             if (prevVal != null) {
+                if (log.isTraceEnabled()) {
+                    log.trace("evictFailed [key=" + key +
+                        ", entry=" + System.identityHashCode(this) +
+                        ", ptr=" + offHeapPointer() +
+                        ']');
+                }
+
                 cctx.swap().removeOffheap(key());
 
                 value(prevVal);
@@ -4177,8 +4317,16 @@ public abstract class GridCacheMapEntry extends GridMetadataAwareAdapter impleme
             if (!hasReaders() && markObsolete0(obsoleteVer, false, null)) {
                 if (!isStartVersion() && hasValueUnlocked()) {
                     if (cctx.offheapTiered() && hasOffHeapPointer()) {
-                        if (cctx.swap().offheapEvictionEnabled())
+                        if (cctx.swap().offheapEvictionEnabled()) {
+                            if (log.isTraceEnabled()) {
+                                log.trace("enableOffheapEviction evictInBatchInternal [key=" + key +
+                                    ", entry=" + System.identityHashCode(this) +
+                                    ", ptr=" + offHeapPointer() +
+                                    ']');
+                            }
+
                             cctx.swap().enableOffheapEviction(key(), partition());
+                        }
 
                         return null;
                     }

http://git-wip-us.apache.org/repos/asf/ignite/blob/e2db87bb/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheSwapManager.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheSwapManager.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheSwapManager.java
index f4786be..7f6a83f 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheSwapManager.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheSwapManager.java
@@ -2121,6 +2121,9 @@ public class GridCacheSwapManager extends GridCacheManagerAdapter {
                             IgniteUuid valLdrId = swapEntry.valueClassLoaderId();
 
                             if (ldrId.equals(swapEntry.keyClassLoaderId())) {
+                                if (log.isTraceEnabled())
+                                    log.trace("onUndeploy remove key [ldrId=" + ldrId + ']');
+
                                 iter.removeX();
 
                                 undeployCnt++;
@@ -2138,6 +2141,9 @@ public class GridCacheSwapManager extends GridCacheManagerAdapter {
                                         valLdrId = cctx.deploy().getClassLoaderId(val.getClass().getClassLoader());
                                 }
 
+                                if (log.isTraceEnabled())
+                                    log.trace("onUndeploy remove value [ldrId=" + ldrId + ']');
+
                                 if (ldrId.equals(valLdrId)) {
                                     iter.removeX();
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/e2db87bb/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtCacheEntry.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtCacheEntry.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtCacheEntry.java
index 95ef10b..b0b0a7e 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtCacheEntry.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtCacheEntry.java
@@ -581,6 +581,14 @@ public class GridDhtCacheEntry extends GridDistributedCacheEntry {
                 if (log.isDebugEnabled())
                     log.debug("Entry has been marked obsolete: " + this);
 
+                if (log.isTraceEnabled()) {
+                    log.trace("clearInternal [key=" + key +
+                        ", entry=" + System.identityHashCode(this) +
+                        ", prev=" + prev +
+                        ", ptr=" + offHeapPointer() +
+                        ']');
+                }
+
                 clearIndex(prev);
 
                 // Give to GC.

http://git-wip-us.apache.org/repos/asf/ignite/blob/e2db87bb/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtOffHeapCacheEntry.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtOffHeapCacheEntry.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtOffHeapCacheEntry.java
index 07272ae..75ee45c 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtOffHeapCacheEntry.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtOffHeapCacheEntry.java
@@ -21,6 +21,7 @@ import org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion;
 import org.apache.ignite.internal.processors.cache.CacheObject;
 import org.apache.ignite.internal.processors.cache.GridCacheContext;
 import org.apache.ignite.internal.processors.cache.KeyCacheObject;
+import org.apache.ignite.internal.util.typedef.internal.S;
 
 /**
  * Replicated cache entry for off-heap tiered or off-heap values modes.
@@ -60,4 +61,11 @@ public class GridDhtOffHeapCacheEntry extends GridDhtCacheEntry {
     @Override protected void offHeapPointer(long valPtr) {
         this.valPtr = valPtr;
     }
+
+    /** {@inheritDoc} */
+    @Override public synchronized String toString() {
+        return S.toString(GridDhtOffHeapCacheEntry.class, this,
+            "entry", System.identityHashCode(this),
+            "super", super.toString());
+    }
 }

http://git-wip-us.apache.org/repos/asf/ignite/blob/e2db87bb/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridDhtAtomicOffHeapCacheEntry.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridDhtAtomicOffHeapCacheEntry.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridDhtAtomicOffHeapCacheEntry.java
index 85cfb80..c86d477 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridDhtAtomicOffHeapCacheEntry.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridDhtAtomicOffHeapCacheEntry.java
@@ -21,6 +21,7 @@ import org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion;
 import org.apache.ignite.internal.processors.cache.CacheObject;
 import org.apache.ignite.internal.processors.cache.GridCacheContext;
 import org.apache.ignite.internal.processors.cache.KeyCacheObject;
+import org.apache.ignite.internal.util.typedef.internal.S;
 
 /**
  * DHT atomic cache entry for off-heap tiered or off-heap values modes.
@@ -60,4 +61,11 @@ public class GridDhtAtomicOffHeapCacheEntry extends GridDhtAtomicCacheEntry {
     @Override protected void offHeapPointer(long valPtr) {
         this.valPtr = valPtr;
     }
+
+    /** {@inheritDoc} */
+    @Override public synchronized String toString() {
+        return S.toString(GridDhtAtomicOffHeapCacheEntry.class, this,
+            "entry", System.identityHashCode(this),
+            "super", super.toString());
+    }
 }

http://git-wip-us.apache.org/repos/asf/ignite/blob/e2db87bb/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/colocated/GridDhtColocatedOffHeapCacheEntry.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/colocated/GridDhtColocatedOffHeapCacheEntry.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/colocated/GridDhtColocatedOffHeapCacheEntry.java
index ea368d2..8080ca3 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/colocated/GridDhtColocatedOffHeapCacheEntry.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/colocated/GridDhtColocatedOffHeapCacheEntry.java
@@ -21,6 +21,7 @@ import org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion;
 import org.apache.ignite.internal.processors.cache.CacheObject;
 import org.apache.ignite.internal.processors.cache.GridCacheContext;
 import org.apache.ignite.internal.processors.cache.KeyCacheObject;
+import org.apache.ignite.internal.util.typedef.internal.S;
 
 /**
  * Cache entry for colocated cache for off-heap tiered or off-heap values modes.
@@ -60,4 +61,11 @@ public class GridDhtColocatedOffHeapCacheEntry extends GridDhtColocatedCacheEntr
     @Override protected void offHeapPointer(long valPtr) {
         this.valPtr = valPtr;
     }
+
+    /** {@inheritDoc} */
+    @Override public synchronized String toString() {
+        return S.toString(GridDhtColocatedOffHeapCacheEntry.class, this,
+            "entry", System.identityHashCode(this),
+            "super", super.toString());
+    }
 }

http://git-wip-us.apache.org/repos/asf/ignite/blob/e2db87bb/modules/core/src/main/java/org/apache/ignite/internal/processors/offheap/GridOffHeapProcessor.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/offheap/GridOffHeapProcessor.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/offheap/GridOffHeapProcessor.java
index a97427a..d9d4421 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/offheap/GridOffHeapProcessor.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/offheap/GridOffHeapProcessor.java
@@ -228,6 +228,9 @@ public class GridOffHeapProcessor extends GridProcessorAdapter {
     @Nullable public byte[] remove(@Nullable String spaceName, int part, KeyCacheObject key, byte[] keyBytes) throws IgniteCheckedException {
         GridOffHeapPartitionedMap m = offheap(spaceName);
 
+        if (log.isTraceEnabled())
+            log.trace("offheap remove [key=" + key + ']');
+
         return m == null ? null : m.remove(part, U.hash(key), keyBytes(key, keyBytes));
     }
 
@@ -249,6 +252,9 @@ public class GridOffHeapProcessor extends GridProcessorAdapter {
             throw new IgniteCheckedException("Failed to write data to off-heap space, no space registered for name: " +
                 spaceName);
 
+        if (log.isTraceEnabled())
+            log.trace("offheap put [key=" + key + ']');
+
         m.put(part, U.hash(key), keyBytes(key, keyBytes), valBytes);
     }
 
@@ -266,6 +272,9 @@ public class GridOffHeapProcessor extends GridProcessorAdapter {
         throws IgniteCheckedException {
         GridOffHeapPartitionedMap m = offheap(spaceName);
 
+        if (log.isTraceEnabled())
+            log.trace("offheap removex [key=" + key + ']');
+
         return m != null && m.removex(part, U.hash(key), keyBytes(key, keyBytes));
     }
 
@@ -287,6 +296,9 @@ public class GridOffHeapProcessor extends GridProcessorAdapter {
         IgniteBiPredicate<Long, Integer> p) throws IgniteCheckedException {
         GridOffHeapPartitionedMap m = offheap(spaceName);
 
+        if (log.isTraceEnabled())
+            log.trace("offheap removex [key=" + key + ']');
+
         return m != null && m.removex(part, U.hash(key), keyBytes(key, keyBytes), p);
     }