You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@ignite.apache.org by vk...@apache.org on 2015/08/27 02:11:26 UTC

[01/59] [abbrv] ignite git commit: ignite-1258: portable objects API support in Ignite

Repository: ignite
Updated Branches:
  refs/heads/ignite-884 794f2a00d -> 1a83d65ad


http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCacheOffHeapTieredAtomicPortableSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCacheOffHeapTieredAtomicPortableSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCacheOffHeapTieredAtomicPortableSelfTest.java
new file mode 100644
index 0000000..56c6c04
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCacheOffHeapTieredAtomicPortableSelfTest.java
@@ -0,0 +1,48 @@
+/*
+ * 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.portable.distributed.dht;
+
+import org.apache.ignite.configuration.*;
+import org.apache.ignite.internal.processors.cache.*;
+import org.apache.ignite.marshaller.portable.*;
+
+import java.util.*;
+
+/**
+ *
+ */
+public class GridCacheOffHeapTieredAtomicPortableSelfTest extends GridCacheOffHeapTieredAtomicSelfTest {
+    /** {@inheritDoc} */
+    @Override protected boolean portableEnabled() {
+        return true;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception {
+        // Enable portables.
+        IgniteConfiguration cfg = super.getConfiguration(gridName);
+
+        PortableMarshaller marsh = new PortableMarshaller();
+
+        marsh.setClassNames(Arrays.asList(TestValue.class.getName()));
+
+        cfg.setMarshaller(marsh);
+
+        return cfg;
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCacheOffHeapTieredEvictionAtomicPortableSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCacheOffHeapTieredEvictionAtomicPortableSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCacheOffHeapTieredEvictionAtomicPortableSelfTest.java
new file mode 100644
index 0000000..3865b4e
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCacheOffHeapTieredEvictionAtomicPortableSelfTest.java
@@ -0,0 +1,96 @@
+/*
+ * 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.portable.distributed.dht;
+
+import org.apache.ignite.configuration.*;
+import org.apache.ignite.internal.processors.cache.*;
+import org.apache.ignite.marshaller.portable.*;
+import org.apache.ignite.portable.*;
+
+import java.util.*;
+
+/**
+ *
+ */
+public class GridCacheOffHeapTieredEvictionAtomicPortableSelfTest extends GridCacheOffHeapTieredEvictionAtomicSelfTest {
+    /** {@inheritDoc} */
+    @Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception {
+        // Enable portables.
+        IgniteConfiguration cfg = super.getConfiguration(gridName);
+
+        PortableMarshaller marsh = new PortableMarshaller();
+
+        marsh.setClassNames(Arrays.asList(TestValue.class.getName()));
+
+        cfg.setMarshaller(marsh);
+
+        return cfg;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected TestPredicate testPredicate(String expVal, boolean acceptNull) {
+        return new PortableValuePredicate(expVal, acceptNull);
+    }
+
+    /** {@inheritDoc} */
+    @Override protected TestProcessor testClosure(String expVal, boolean acceptNull) {
+        return new PortableValueClosure(expVal, acceptNull);
+    }
+
+    /**
+     *
+     */
+    @SuppressWarnings("PackageVisibleInnerClass")
+    static class PortableValuePredicate extends TestPredicate {
+        /**
+         * @param expVal Expected value.
+         * @param acceptNull If {@code true} value can be null;
+         */
+        PortableValuePredicate(String expVal, boolean acceptNull) {
+            super(expVal, acceptNull);
+        }
+
+        /** {@inheritDoc} */
+        @Override public void checkValue(Object val) {
+            PortableObject obj = (PortableObject)val;
+
+            assertEquals(expVal, obj.field("val"));
+        }
+    }
+
+    /**
+     *
+     */
+    @SuppressWarnings("PackageVisibleInnerClass")
+    static class PortableValueClosure extends TestProcessor {
+        /**
+         * @param expVal Expected value.
+         * @param acceptNull If {@code true} value can be null;
+         */
+        PortableValueClosure(String expVal, boolean acceptNull) {
+            super(expVal, acceptNull);
+        }
+
+        /** {@inheritDoc} */
+        @Override public void checkValue(Object val) {
+            PortableObject obj = (PortableObject)val;
+
+            assertEquals(expVal, obj.field("val"));
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCacheOffHeapTieredEvictionPortableSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCacheOffHeapTieredEvictionPortableSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCacheOffHeapTieredEvictionPortableSelfTest.java
new file mode 100644
index 0000000..e237e88
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCacheOffHeapTieredEvictionPortableSelfTest.java
@@ -0,0 +1,96 @@
+/*
+ * 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.portable.distributed.dht;
+
+import org.apache.ignite.configuration.*;
+import org.apache.ignite.internal.processors.cache.*;
+import org.apache.ignite.marshaller.portable.*;
+import org.apache.ignite.portable.*;
+
+import java.util.*;
+
+/**
+ *
+ */
+public class GridCacheOffHeapTieredEvictionPortableSelfTest extends GridCacheOffHeapTieredEvictionSelfTest {
+    /** {@inheritDoc} */
+    @Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception {
+        // Enable portables.
+        IgniteConfiguration cfg = super.getConfiguration(gridName);
+
+        PortableMarshaller marsh = new PortableMarshaller();
+
+        marsh.setClassNames(Arrays.asList(TestValue.class.getName()));
+
+        cfg.setMarshaller(marsh);
+
+        return cfg;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected TestPredicate testPredicate(String expVal, boolean acceptNull) {
+        return new PortableValuePredicate(expVal, acceptNull);
+    }
+
+    /** {@inheritDoc} */
+    @Override protected TestProcessor testClosure(String expVal, boolean acceptNull) {
+        return new PortableValueClosure(expVal, acceptNull);
+    }
+
+    /**
+     *
+     */
+    @SuppressWarnings("PackageVisibleInnerClass")
+    static class PortableValuePredicate extends TestPredicate {
+        /**
+         * @param expVal Expected value.
+         * @param acceptNull If {@code true} value can be null;
+         */
+        PortableValuePredicate(String expVal, boolean acceptNull) {
+            super(expVal, acceptNull);
+        }
+
+        /** {@inheritDoc} */
+        @Override public void checkValue(Object val) {
+            PortableObject obj = (PortableObject)val;
+
+            assertEquals(expVal, obj.field("val"));
+        }
+    }
+
+    /**
+     *
+     */
+    @SuppressWarnings("PackageVisibleInnerClass")
+    static class PortableValueClosure extends TestProcessor {
+        /**
+         * @param expVal Expected value.
+         * @param acceptNull If {@code true} value can be null;
+         */
+        PortableValueClosure(String expVal, boolean acceptNull) {
+            super(expVal, acceptNull);
+        }
+
+        /** {@inheritDoc} */
+        @Override public void checkValue(Object val) {
+            PortableObject obj = (PortableObject)val;
+
+            assertEquals(expVal, obj.field("val"));
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCacheOffHeapTieredPortableSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCacheOffHeapTieredPortableSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCacheOffHeapTieredPortableSelfTest.java
new file mode 100644
index 0000000..56fc66e
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCacheOffHeapTieredPortableSelfTest.java
@@ -0,0 +1,48 @@
+/*
+ * 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.portable.distributed.dht;
+
+import org.apache.ignite.configuration.*;
+import org.apache.ignite.internal.processors.cache.*;
+import org.apache.ignite.marshaller.portable.*;
+
+import java.util.*;
+
+/**
+ *
+ */
+public class GridCacheOffHeapTieredPortableSelfTest extends GridCacheOffHeapTieredSelfTest {
+    /** {@inheritDoc} */
+    @Override protected boolean portableEnabled() {
+        return true;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception {
+        // Enable portables.
+        IgniteConfiguration cfg = super.getConfiguration(gridName);
+
+        PortableMarshaller marsh = new PortableMarshaller();
+
+        marsh.setClassNames(Arrays.asList(TestValue.class.getName()));
+
+        cfg.setMarshaller(marsh);
+
+        return cfg;
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCachePortableDuplicateIndexObjectPartitionedAtomicSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCachePortableDuplicateIndexObjectPartitionedAtomicSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCachePortableDuplicateIndexObjectPartitionedAtomicSelfTest.java
new file mode 100644
index 0000000..296d19a
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCachePortableDuplicateIndexObjectPartitionedAtomicSelfTest.java
@@ -0,0 +1,37 @@
+/*
+ * 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.portable.distributed.dht;
+
+import org.apache.ignite.cache.*;
+import org.apache.ignite.internal.processors.cache.portable.*;
+
+/**
+ * Test PARTITIONED ATOMIC.
+ */
+public class GridCachePortableDuplicateIndexObjectPartitionedAtomicSelfTest extends
+    GridPortableDuplicateIndexObjectsAbstractSelfTest {
+    /** {@inheritDoc} */
+    @Override public CacheAtomicityMode atomicityMode() {
+        return CacheAtomicityMode.ATOMIC;
+    }
+
+    /** {@inheritDoc} */
+    @Override public CacheMode cacheMode() {
+        return CacheMode.PARTITIONED;
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCachePortableDuplicateIndexObjectPartitionedTransactionalSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCachePortableDuplicateIndexObjectPartitionedTransactionalSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCachePortableDuplicateIndexObjectPartitionedTransactionalSelfTest.java
new file mode 100644
index 0000000..b7751f1
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCachePortableDuplicateIndexObjectPartitionedTransactionalSelfTest.java
@@ -0,0 +1,40 @@
+/*
+ * 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.portable.distributed.dht;
+
+import org.apache.ignite.cache.*;
+import org.apache.ignite.internal.processors.cache.portable.*;
+
+import static org.apache.ignite.cache.CacheAtomicityMode.*;
+import static org.apache.ignite.cache.CacheMode.*;
+
+/**
+ * Test PARTITIONED and TRANSACTIONAL.
+ */
+public class GridCachePortableDuplicateIndexObjectPartitionedTransactionalSelfTest extends
+    GridPortableDuplicateIndexObjectsAbstractSelfTest {
+    /** {@inheritDoc} */
+    @Override public CacheAtomicityMode atomicityMode() {
+        return TRANSACTIONAL;
+    }
+
+    /** {@inheritDoc} */
+    @Override public CacheMode cacheMode() {
+        return PARTITIONED;
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCachePortableObjectsAtomicNearDisabledOffheapTieredSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCachePortableObjectsAtomicNearDisabledOffheapTieredSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCachePortableObjectsAtomicNearDisabledOffheapTieredSelfTest.java
new file mode 100644
index 0000000..cf0da8e
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCachePortableObjectsAtomicNearDisabledOffheapTieredSelfTest.java
@@ -0,0 +1,29 @@
+/*
+ * 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.portable.distributed.dht;
+
+/**
+ *
+ */
+public class GridCachePortableObjectsAtomicNearDisabledOffheapTieredSelfTest
+    extends GridCachePortableObjectsAtomicNearDisabledSelfTest {
+    /** {@inheritDoc} */
+    @Override protected boolean offheapTiered() {
+        return true;
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCachePortableObjectsAtomicNearDisabledSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCachePortableObjectsAtomicNearDisabledSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCachePortableObjectsAtomicNearDisabledSelfTest.java
new file mode 100644
index 0000000..744ff4b
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCachePortableObjectsAtomicNearDisabledSelfTest.java
@@ -0,0 +1,50 @@
+/*
+ * 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.portable.distributed.dht;
+
+import org.apache.ignite.cache.*;
+import org.apache.ignite.configuration.*;
+import org.apache.ignite.internal.processors.cache.portable.*;
+
+import static org.apache.ignite.cache.CacheAtomicityMode.*;
+import static org.apache.ignite.cache.CacheMode.*;
+
+/**
+ * Test for portable objects stored in cache.
+ */
+public class GridCachePortableObjectsAtomicNearDisabledSelfTest extends GridCachePortableObjectsAbstractSelfTest {
+    /** {@inheritDoc} */
+    @Override protected CacheMode cacheMode() {
+        return PARTITIONED;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected CacheAtomicityMode atomicityMode() {
+        return ATOMIC;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected NearCacheConfiguration nearConfiguration() {
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected int gridCount() {
+        return 3;
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCachePortableObjectsAtomicOffheapTieredSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCachePortableObjectsAtomicOffheapTieredSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCachePortableObjectsAtomicOffheapTieredSelfTest.java
new file mode 100644
index 0000000..3584125
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCachePortableObjectsAtomicOffheapTieredSelfTest.java
@@ -0,0 +1,29 @@
+/*
+ * 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.portable.distributed.dht;
+
+/**
+ *
+ */
+public class GridCachePortableObjectsAtomicOffheapTieredSelfTest extends GridCachePortableObjectsAtomicSelfTest {
+    /** {@inheritDoc} */
+    @Override protected boolean offheapTiered() {
+        return true;
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCachePortableObjectsAtomicSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCachePortableObjectsAtomicSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCachePortableObjectsAtomicSelfTest.java
new file mode 100644
index 0000000..e6d7f09
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCachePortableObjectsAtomicSelfTest.java
@@ -0,0 +1,50 @@
+/*
+ * 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.portable.distributed.dht;
+
+import org.apache.ignite.cache.*;
+import org.apache.ignite.configuration.*;
+import org.apache.ignite.internal.processors.cache.portable.*;
+
+import static org.apache.ignite.cache.CacheAtomicityMode.*;
+import static org.apache.ignite.cache.CacheMode.*;
+
+/**
+ * Test for portable objects stored in cache.
+ */
+public class GridCachePortableObjectsAtomicSelfTest extends GridCachePortableObjectsAbstractSelfTest {
+    /** {@inheritDoc} */
+    @Override protected CacheMode cacheMode() {
+        return PARTITIONED;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected CacheAtomicityMode atomicityMode() {
+        return ATOMIC;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected NearCacheConfiguration nearConfiguration() {
+        return new NearCacheConfiguration();
+    }
+
+    /** {@inheritDoc} */
+    @Override protected int gridCount() {
+        return 3;
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCachePortableObjectsPartitionedNearDisabledOffheapTieredSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCachePortableObjectsPartitionedNearDisabledOffheapTieredSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCachePortableObjectsPartitionedNearDisabledOffheapTieredSelfTest.java
new file mode 100644
index 0000000..c5bbf9e
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCachePortableObjectsPartitionedNearDisabledOffheapTieredSelfTest.java
@@ -0,0 +1,30 @@
+/*
+ * 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.portable.distributed.dht;
+
+/**
+ *
+ */
+public class GridCachePortableObjectsPartitionedNearDisabledOffheapTieredSelfTest
+    extends GridCachePortableObjectsPartitionedNearDisabledSelfTest{
+    /** {@inheritDoc} */
+    @Override protected boolean offheapTiered() {
+        return true;
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCachePortableObjectsPartitionedNearDisabledSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCachePortableObjectsPartitionedNearDisabledSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCachePortableObjectsPartitionedNearDisabledSelfTest.java
new file mode 100644
index 0000000..d216be2
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCachePortableObjectsPartitionedNearDisabledSelfTest.java
@@ -0,0 +1,50 @@
+/*
+ * 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.portable.distributed.dht;
+
+import org.apache.ignite.cache.*;
+import org.apache.ignite.configuration.*;
+import org.apache.ignite.internal.processors.cache.portable.*;
+
+import static org.apache.ignite.cache.CacheAtomicityMode.*;
+import static org.apache.ignite.cache.CacheMode.*;
+
+/**
+ * Test for portable objects stored in cache.
+ */
+public class GridCachePortableObjectsPartitionedNearDisabledSelfTest extends GridCachePortableObjectsAbstractSelfTest {
+    /** {@inheritDoc} */
+    @Override protected CacheMode cacheMode() {
+        return PARTITIONED;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected CacheAtomicityMode atomicityMode() {
+        return TRANSACTIONAL;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected NearCacheConfiguration nearConfiguration() {
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected int gridCount() {
+        return 3;
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCachePortableObjectsPartitionedOffheapTieredSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCachePortableObjectsPartitionedOffheapTieredSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCachePortableObjectsPartitionedOffheapTieredSelfTest.java
new file mode 100644
index 0000000..cfcf959
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCachePortableObjectsPartitionedOffheapTieredSelfTest.java
@@ -0,0 +1,30 @@
+/*
+ * 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.portable.distributed.dht;
+
+/**
+ *
+ */
+public class GridCachePortableObjectsPartitionedOffheapTieredSelfTest
+    extends GridCachePortableObjectsPartitionedSelfTest {
+    /** {@inheritDoc} */
+    @Override protected boolean offheapTiered() {
+        return true;
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCachePortableObjectsPartitionedSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCachePortableObjectsPartitionedSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCachePortableObjectsPartitionedSelfTest.java
new file mode 100644
index 0000000..cf79900
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCachePortableObjectsPartitionedSelfTest.java
@@ -0,0 +1,50 @@
+/*
+ * 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.portable.distributed.dht;
+
+import org.apache.ignite.cache.*;
+import org.apache.ignite.configuration.*;
+import org.apache.ignite.internal.processors.cache.portable.*;
+
+import static org.apache.ignite.cache.CacheAtomicityMode.*;
+import static org.apache.ignite.cache.CacheMode.*;
+
+/**
+ * Test for portable objects stored in cache.
+ */
+public class GridCachePortableObjectsPartitionedSelfTest extends GridCachePortableObjectsAbstractSelfTest {
+    /** {@inheritDoc} */
+    @Override protected CacheMode cacheMode() {
+        return PARTITIONED;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected CacheAtomicityMode atomicityMode() {
+        return TRANSACTIONAL;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected NearCacheConfiguration nearConfiguration() {
+        return new NearCacheConfiguration();
+    }
+
+    /** {@inheritDoc} */
+    @Override protected int gridCount() {
+        return 3;
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCachePortablesNearPartitionedByteArrayValuesSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCachePortablesNearPartitionedByteArrayValuesSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCachePortablesNearPartitionedByteArrayValuesSelfTest.java
new file mode 100644
index 0000000..2342ca4
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCachePortablesNearPartitionedByteArrayValuesSelfTest.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.internal.processors.cache.portable.distributed.dht;
+
+import org.apache.ignite.configuration.*;
+import org.apache.ignite.internal.processors.cache.distributed.near.*;
+import org.apache.ignite.marshaller.portable.*;
+
+/**
+ *
+ */
+public class GridCachePortablesNearPartitionedByteArrayValuesSelfTest
+    extends GridCacheAbstractNearPartitionedByteArrayValuesSelfTest {
+    /** {@inheritDoc} */
+    @Override protected boolean peerClassLoading() {
+        return false;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception {
+        IgniteConfiguration cfg = super.getConfiguration(gridName);
+
+        cfg.setMarshaller(new PortableMarshaller());
+
+        return cfg;
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCachePortablesPartitionedOnlyByteArrayValuesSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCachePortablesPartitionedOnlyByteArrayValuesSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCachePortablesPartitionedOnlyByteArrayValuesSelfTest.java
new file mode 100644
index 0000000..668d89a
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCachePortablesPartitionedOnlyByteArrayValuesSelfTest.java
@@ -0,0 +1,42 @@
+/*
+ * 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.portable.distributed.dht;
+
+import org.apache.ignite.configuration.*;
+import org.apache.ignite.internal.processors.cache.distributed.dht.*;
+import org.apache.ignite.marshaller.portable.*;
+
+/**
+ *
+ */
+public class GridCachePortablesPartitionedOnlyByteArrayValuesSelfTest
+    extends GridCacheAbstractPartitionedOnlyByteArrayValuesSelfTest {
+    /** {@inheritDoc} */
+    @Override protected boolean peerClassLoading() {
+        return false;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception {
+        IgniteConfiguration cfg = super.getConfiguration(gridName);
+
+        cfg.setMarshaller(new PortableMarshaller());
+
+        return cfg;
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/replicated/GridCachePortableObjectsReplicatedSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/replicated/GridCachePortableObjectsReplicatedSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/replicated/GridCachePortableObjectsReplicatedSelfTest.java
new file mode 100644
index 0000000..da6b801
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/replicated/GridCachePortableObjectsReplicatedSelfTest.java
@@ -0,0 +1,50 @@
+/*
+ * 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.portable.distributed.replicated;
+
+import org.apache.ignite.cache.*;
+import org.apache.ignite.configuration.*;
+import org.apache.ignite.internal.processors.cache.portable.*;
+
+import static org.apache.ignite.cache.CacheAtomicityMode.*;
+import static org.apache.ignite.cache.CacheMode.*;
+
+/**
+ * Test for portable objects stored in cache.
+ */
+public class GridCachePortableObjectsReplicatedSelfTest extends GridCachePortableObjectsAbstractSelfTest {
+    /** {@inheritDoc} */
+    @Override protected CacheMode cacheMode() {
+        return REPLICATED;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected CacheAtomicityMode atomicityMode() {
+        return TRANSACTIONAL;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected NearCacheConfiguration nearConfiguration() {
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected int gridCount() {
+        return 3;
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/local/GridCachePortableObjectsAtomicLocalSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/local/GridCachePortableObjectsAtomicLocalSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/local/GridCachePortableObjectsAtomicLocalSelfTest.java
new file mode 100644
index 0000000..fd6c75d
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/local/GridCachePortableObjectsAtomicLocalSelfTest.java
@@ -0,0 +1,32 @@
+/*
+ * 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.portable.local;
+
+import org.apache.ignite.cache.*;
+
+import static org.apache.ignite.cache.CacheAtomicityMode.*;
+
+/**
+ *
+ */
+public class GridCachePortableObjectsAtomicLocalSelfTest extends GridCachePortableObjectsLocalSelfTest {
+    /** {@inheritDoc} */
+    @Override protected CacheAtomicityMode atomicityMode() {
+        return ATOMIC;
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/local/GridCachePortableObjectsLocalOffheapTieredSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/local/GridCachePortableObjectsLocalOffheapTieredSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/local/GridCachePortableObjectsLocalOffheapTieredSelfTest.java
new file mode 100644
index 0000000..faf654e
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/local/GridCachePortableObjectsLocalOffheapTieredSelfTest.java
@@ -0,0 +1,29 @@
+/*
+ * 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.portable.local;
+
+/**
+ *
+ */
+public class GridCachePortableObjectsLocalOffheapTieredSelfTest extends GridCachePortableObjectsLocalSelfTest {
+    /** {@inheritDoc} */
+    @Override protected boolean offheapTiered() {
+        return true;
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/local/GridCachePortableObjectsLocalSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/local/GridCachePortableObjectsLocalSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/local/GridCachePortableObjectsLocalSelfTest.java
new file mode 100644
index 0000000..7b58f35
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/local/GridCachePortableObjectsLocalSelfTest.java
@@ -0,0 +1,50 @@
+/*
+ * 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.portable.local;
+
+import org.apache.ignite.cache.*;
+import org.apache.ignite.configuration.*;
+import org.apache.ignite.internal.processors.cache.portable.*;
+
+import static org.apache.ignite.cache.CacheAtomicityMode.*;
+import static org.apache.ignite.cache.CacheMode.*;
+
+/**
+ * Test for portable objects stored in cache.
+ */
+public class GridCachePortableObjectsLocalSelfTest extends GridCachePortableObjectsAbstractSelfTest {
+    /** {@inheritDoc} */
+    @Override protected CacheMode cacheMode() {
+        return LOCAL;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected CacheAtomicityMode atomicityMode() {
+        return TRANSACTIONAL;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected NearCacheConfiguration nearConfiguration() {
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected int gridCount() {
+        return 1;
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/java/org/apache/ignite/testframework/junits/IgniteMock.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/testframework/junits/IgniteMock.java b/modules/core/src/test/java/org/apache/ignite/testframework/junits/IgniteMock.java
index 1471faa..c6645c7 100644
--- a/modules/core/src/test/java/org/apache/ignite/testframework/junits/IgniteMock.java
+++ b/modules/core/src/test/java/org/apache/ignite/testframework/junits/IgniteMock.java
@@ -248,6 +248,11 @@ public class IgniteMock implements Ignite {
     }
 
     /** {@inheritDoc} */
+    @Override public IgnitePortables portables() {
+        return null;
+    }
+
+    /** {@inheritDoc} */
     @Override public void close() {}
 
     @Nullable @Override public IgniteAtomicSequence atomicSequence(String name, long initVal, boolean create) {

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/java/org/apache/ignite/testframework/junits/multijvm/IgniteCacheProcessProxy.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/testframework/junits/multijvm/IgniteCacheProcessProxy.java b/modules/core/src/test/java/org/apache/ignite/testframework/junits/multijvm/IgniteCacheProcessProxy.java
index b15b6ef..5bcf397 100644
--- a/modules/core/src/test/java/org/apache/ignite/testframework/junits/multijvm/IgniteCacheProcessProxy.java
+++ b/modules/core/src/test/java/org/apache/ignite/testframework/junits/multijvm/IgniteCacheProcessProxy.java
@@ -137,6 +137,11 @@ public class IgniteCacheProcessProxy<K, V> implements IgniteCache<K, V> {
     }
 
     /** {@inheritDoc} */
+    @Override public <K1, V1> IgniteCache<K1, V1> withKeepPortable() {
+        throw new UnsupportedOperationException("Method should be supported.");
+    }
+
+    /** {@inheritDoc} */
     @Override public void loadCache(@Nullable IgniteBiPredicate<K, V> p, @Nullable Object... args) throws CacheException {
         throw new UnsupportedOperationException("Method should be supported.");
     }

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/java/org/apache/ignite/testframework/junits/multijvm/IgniteProcessProxy.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/testframework/junits/multijvm/IgniteProcessProxy.java b/modules/core/src/test/java/org/apache/ignite/testframework/junits/multijvm/IgniteProcessProxy.java
index 220424a..e116e5ab 100644
--- a/modules/core/src/test/java/org/apache/ignite/testframework/junits/multijvm/IgniteProcessProxy.java
+++ b/modules/core/src/test/java/org/apache/ignite/testframework/junits/multijvm/IgniteProcessProxy.java
@@ -509,6 +509,11 @@ public class IgniteProcessProxy implements IgniteEx {
     }
 
     /** {@inheritDoc} */
+    @Override public IgnitePortables portables() {
+        throw new UnsupportedOperationException("Operation isn't supported yet.");
+    }
+
+    /** {@inheritDoc} */
     @Override public void close() throws IgniteException {
         final CountDownLatch rmtNodeStoppedLatch = new CountDownLatch(1);
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/java/org/apache/ignite/testsuites/IgnitePortableCacheFullApiTestSuite.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/testsuites/IgnitePortableCacheFullApiTestSuite.java b/modules/core/src/test/java/org/apache/ignite/testsuites/IgnitePortableCacheFullApiTestSuite.java
new file mode 100644
index 0000000..81c45a7
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/testsuites/IgnitePortableCacheFullApiTestSuite.java
@@ -0,0 +1,38 @@
+/*
+ * 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 org.apache.ignite.marshaller.portable.*;
+import org.apache.ignite.testframework.config.*;
+
+import junit.framework.*;
+
+/**
+ * Cache full API suite with portable marshaller.
+ */
+public class IgnitePortableCacheFullApiTestSuite extends TestSuite {
+    /**
+     * @return Suite.
+     * @throws Exception In case of error.
+     */
+    public static TestSuite suite() throws Exception {
+        GridTestProperties.setProperty(GridTestProperties.MARSH_CLASS_NAME, PortableMarshaller.class.getName());
+
+        return IgniteCacheFullApiSelfTestSuite.suite();
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/java/org/apache/ignite/testsuites/IgnitePortableCacheTestSuite.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/testsuites/IgnitePortableCacheTestSuite.java b/modules/core/src/test/java/org/apache/ignite/testsuites/IgnitePortableCacheTestSuite.java
new file mode 100644
index 0000000..aadd188
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/testsuites/IgnitePortableCacheTestSuite.java
@@ -0,0 +1,86 @@
+/*
+ * 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 org.apache.ignite.internal.processors.cache.*;
+import org.apache.ignite.internal.processors.cache.expiry.*;
+import org.apache.ignite.internal.processors.cache.portable.*;
+import org.apache.ignite.internal.processors.cache.portable.datastreaming.*;
+import org.apache.ignite.internal.processors.cache.portable.distributed.dht.*;
+import org.apache.ignite.internal.processors.datastreamer.*;
+import org.apache.ignite.marshaller.portable.*;
+import org.apache.ignite.testframework.config.*;
+
+import junit.framework.*;
+
+import java.util.*;
+
+/**
+ * Cache suite with portable marshaller.
+ */
+public class IgnitePortableCacheTestSuite extends TestSuite {
+    /**
+     * @return Suite.
+     * @throws Exception In case of error.
+     */
+    public static TestSuite suite() throws Exception {
+        GridTestProperties.setProperty(GridTestProperties.MARSH_CLASS_NAME, PortableMarshaller.class.getName());
+
+        TestSuite suite = new TestSuite("Portable Cache Test Suite");
+
+        HashSet<Class> ignoredTests = new HashSet<>();
+
+        // Tests below have a special version for Portable Marshaller
+        ignoredTests.add(DataStreamProcessorSelfTest.class);
+        ignoredTests.add(GridCacheOffHeapTieredEvictionAtomicSelfTest.class);
+        ignoredTests.add(GridCacheOffHeapTieredEvictionSelfTest.class);
+        ignoredTests.add(GridCacheOffHeapTieredSelfTest.class);
+        ignoredTests.add(GridCacheOffHeapTieredAtomicSelfTest.class);
+        ignoredTests.add(GridCacheAffinityRoutingSelfTest.class);
+        ignoredTests.add(IgniteCacheAtomicLocalExpiryPolicyTest.class);
+        ignoredTests.add(GridCacheEntryMemorySizeSelfTest.class);
+
+        // Tests that are not ready to be used with PortableMarshaller
+        ignoredTests.add(GridCacheMvccSelfTest.class);
+
+        suite.addTest(IgniteCacheTestSuite.suite(ignoredTests));
+        suite.addTest(IgniteCacheExpiryPolicyTestSuite.suite());
+
+        suite.addTestSuite(GridCacheMemoryModePortableSelfTest.class);
+        suite.addTestSuite(GridCacheOffHeapTieredEvictionAtomicPortableSelfTest.class);
+        suite.addTestSuite(GridCacheOffHeapTieredEvictionPortableSelfTest.class);
+
+        suite.addTestSuite(GridCachePortablesPartitionedOnlyByteArrayValuesSelfTest.class);
+        suite.addTestSuite(GridCachePortablesNearPartitionedByteArrayValuesSelfTest.class);
+        suite.addTestSuite(GridCacheOffHeapTieredPortableSelfTest.class);
+        suite.addTestSuite(GridCacheOffHeapTieredAtomicPortableSelfTest.class);
+
+        suite.addTestSuite(GridDataStreamerImplSelfTest.class);
+        suite.addTestSuite(DataStreamProcessorPortableSelfTest.class);
+        suite.addTestSuite(GridCacheAtomicPartitionedOnlyPortableDataStreamerMultiNodeSelfTest.class);
+        suite.addTestSuite(GridCacheAtomicPartitionedOnlyPortableDataStreamerMultithreadedSelfTest.class);
+
+        suite.addTestSuite(GridCacheAtomicPartitionedOnlyPortableMultiNodeSelfTest.class);
+        suite.addTestSuite(GridCacheAtomicPartitionedOnlyPortableMultithreadedSelfTest.class);
+
+        suite.addTestSuite(GridCacheAffinityRoutingPortableSelfTest.class);
+        suite.addTestSuite(GridPortableCacheEntryMemorySizeSelfTest.class);
+
+        return suite;
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/java/org/apache/ignite/testsuites/IgnitePortableObjectsTestSuite.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/testsuites/IgnitePortableObjectsTestSuite.java b/modules/core/src/test/java/org/apache/ignite/testsuites/IgnitePortableObjectsTestSuite.java
new file mode 100644
index 0000000..ece949d
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/testsuites/IgnitePortableObjectsTestSuite.java
@@ -0,0 +1,74 @@
+/*
+ * 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 org.apache.ignite.internal.portable.*;
+import org.apache.ignite.internal.processors.cache.portable.*;
+import org.apache.ignite.internal.processors.cache.portable.datastreaming.*;
+import org.apache.ignite.internal.processors.cache.portable.distributed.dht.*;
+import org.apache.ignite.internal.processors.cache.portable.distributed.replicated.*;
+import org.apache.ignite.internal.processors.cache.portable.local.*;
+
+import junit.framework.*;
+
+/**
+ * Test for portable objects stored in cache.
+ */
+public class IgnitePortableObjectsTestSuite extends TestSuite {
+    /**
+     * @return Suite.
+     * @throws Exception If failed.
+     */
+    public static TestSuite suite() throws Exception {
+        TestSuite suite = new TestSuite("GridGain Portable Objects Test Suite");
+
+        suite.addTestSuite(GridPortableMarshallerSelfTest.class);
+        suite.addTestSuite(GridPortableMarshallerCtxDisabledSelfTest.class);
+        suite.addTestSuite(GridPortableBuilderSelfTest.class);
+        suite.addTestSuite(GridPortableBuilderStringAsCharsSelfTest.class);
+        suite.addTestSuite(GridPortableMetaDataSelfTest.class);
+        suite.addTestSuite(GridPortableMetaDataDisabledSelfTest.class);
+        suite.addTestSuite(GridPortableAffinityKeySelfTest.class);
+        suite.addTestSuite(GridPortableWildcardsSelfTest.class);
+        suite.addTestSuite(GridPortableBuilderAdditionalSelfTest.class);
+        suite.addTestSuite(GridPortableBuilderStringAsCharsAdditionalSelfTest.class);
+
+        suite.addTestSuite(GridCachePortableObjectsLocalSelfTest.class);
+        suite.addTestSuite(GridCachePortableObjectsAtomicLocalSelfTest.class);
+        suite.addTestSuite(GridCachePortableObjectsReplicatedSelfTest.class);
+        suite.addTestSuite(GridCachePortableObjectsPartitionedSelfTest.class);
+        suite.addTestSuite(GridCachePortableObjectsPartitionedNearDisabledSelfTest.class);
+        suite.addTestSuite(GridCachePortableObjectsAtomicSelfTest.class);
+        suite.addTestSuite(GridCachePortableObjectsAtomicNearDisabledSelfTest.class);
+
+        suite.addTestSuite(GridCachePortableObjectsLocalOffheapTieredSelfTest.class);
+        suite.addTestSuite(GridCachePortableObjectsAtomicOffheapTieredSelfTest.class);
+        suite.addTestSuite(GridCachePortableObjectsAtomicNearDisabledOffheapTieredSelfTest.class);
+        suite.addTestSuite(GridCachePortableObjectsPartitionedOffheapTieredSelfTest.class);
+        suite.addTestSuite(GridCachePortableObjectsPartitionedNearDisabledOffheapTieredSelfTest.class);
+
+        suite.addTestSuite(GridCachePortableStoreObjectsSelfTest.class);
+        suite.addTestSuite(GridCachePortableStorePortablesSelfTest.class);
+
+        suite.addTestSuite(GridCacheClientNodePortableMetadataTest.class);
+        suite.addTestSuite(GridCacheClientNodePortableMetadataMultinodeTest.class);
+
+        return suite;
+    }
+}
+

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/portables/repo/org/apache/ignite/portable/test1/1.1/test1-1.1.jar
----------------------------------------------------------------------
diff --git a/modules/core/src/test/portables/repo/org/apache/ignite/portable/test1/1.1/test1-1.1.jar b/modules/core/src/test/portables/repo/org/apache/ignite/portable/test1/1.1/test1-1.1.jar
new file mode 100644
index 0000000..863350d
Binary files /dev/null and b/modules/core/src/test/portables/repo/org/apache/ignite/portable/test1/1.1/test1-1.1.jar differ

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/portables/repo/org/apache/ignite/portable/test1/1.1/test1-1.1.pom
----------------------------------------------------------------------
diff --git a/modules/core/src/test/portables/repo/org/apache/ignite/portable/test1/1.1/test1-1.1.pom b/modules/core/src/test/portables/repo/org/apache/ignite/portable/test1/1.1/test1-1.1.pom
new file mode 100644
index 0000000..c79dfbf
--- /dev/null
+++ b/modules/core/src/test/portables/repo/org/apache/ignite/portable/test1/1.1/test1-1.1.pom
@@ -0,0 +1,9 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
+    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+  <modelVersion>4.0.0</modelVersion>
+  <groupId>org.apache.ignite.portable</groupId>
+  <artifactId>test1</artifactId>
+  <version>1.1</version>
+  <description>POM was created from install:install-file</description>
+</project>

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/portables/repo/org/apache/ignite/portable/test1/maven-metadata-local.xml
----------------------------------------------------------------------
diff --git a/modules/core/src/test/portables/repo/org/apache/ignite/portable/test1/maven-metadata-local.xml b/modules/core/src/test/portables/repo/org/apache/ignite/portable/test1/maven-metadata-local.xml
new file mode 100644
index 0000000..33f5abf
--- /dev/null
+++ b/modules/core/src/test/portables/repo/org/apache/ignite/portable/test1/maven-metadata-local.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<metadata>
+  <groupId>org.apache.ignite.portable</groupId>
+  <artifactId>test1</artifactId>
+  <versioning>
+    <release>1.1</release>
+    <versions>
+      <version>1.1</version>
+    </versions>
+    <lastUpdated>20140806090184</lastUpdated>
+  </versioning>
+</metadata>

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/portables/repo/org/apache/ignite/portable/test2/1.1/test2-1.1.jar
----------------------------------------------------------------------
diff --git a/modules/core/src/test/portables/repo/org/apache/ignite/portable/test2/1.1/test2-1.1.jar b/modules/core/src/test/portables/repo/org/apache/ignite/portable/test2/1.1/test2-1.1.jar
new file mode 100644
index 0000000..ccf4ea2
Binary files /dev/null and b/modules/core/src/test/portables/repo/org/apache/ignite/portable/test2/1.1/test2-1.1.jar differ

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/portables/repo/org/apache/ignite/portable/test2/1.1/test2-1.1.pom
----------------------------------------------------------------------
diff --git a/modules/core/src/test/portables/repo/org/apache/ignite/portable/test2/1.1/test2-1.1.pom b/modules/core/src/test/portables/repo/org/apache/ignite/portable/test2/1.1/test2-1.1.pom
new file mode 100644
index 0000000..37621e1
--- /dev/null
+++ b/modules/core/src/test/portables/repo/org/apache/ignite/portable/test2/1.1/test2-1.1.pom
@@ -0,0 +1,9 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
+    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+  <modelVersion>4.0.0</modelVersion>
+  <groupId>org.apache.ignite.portable</groupId>
+  <artifactId>test2</artifactId>
+  <version>1.1</version>
+  <description>POM was created from install:install-file</description>
+</project>

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/portables/repo/org/apache/ignite/portable/test2/maven-metadata-local.xml
----------------------------------------------------------------------
diff --git a/modules/core/src/test/portables/repo/org/apache/ignite/portable/test2/maven-metadata-local.xml b/modules/core/src/test/portables/repo/org/apache/ignite/portable/test2/maven-metadata-local.xml
new file mode 100644
index 0000000..9c705ef
--- /dev/null
+++ b/modules/core/src/test/portables/repo/org/apache/ignite/portable/test2/maven-metadata-local.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<metadata>
+  <groupId>org.apache.ignite.portable</groupId>
+  <artifactId>test2</artifactId>
+  <versioning>
+    <release>1.1</release>
+    <versions>
+      <version>1.1</version>
+    </versions>
+    <lastUpdated>20140806090410</lastUpdated>
+  </versioning>
+</metadata>

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/indexing/src/test/java/org/apache/ignite/testsuites/IgnitePortableCacheQueryTestSuite.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/test/java/org/apache/ignite/testsuites/IgnitePortableCacheQueryTestSuite.java b/modules/indexing/src/test/java/org/apache/ignite/testsuites/IgnitePortableCacheQueryTestSuite.java
new file mode 100644
index 0000000..42b4134
--- /dev/null
+++ b/modules/indexing/src/test/java/org/apache/ignite/testsuites/IgnitePortableCacheQueryTestSuite.java
@@ -0,0 +1,95 @@
+/*
+ * 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 org.apache.ignite.internal.processors.cache.*;
+import org.apache.ignite.internal.processors.cache.portable.distributed.dht.*;
+import org.apache.ignite.internal.processors.cache.query.continuous.*;
+import org.apache.ignite.internal.processors.query.h2.sql.*;
+import org.apache.ignite.marshaller.portable.*;
+import org.apache.ignite.spi.communication.tcp.*;
+import org.apache.ignite.testframework.config.*;
+
+import junit.framework.*;
+
+/**
+ * Cache query suite with portable marshaller.
+ */
+public class IgnitePortableCacheQueryTestSuite extends TestSuite {
+    /**
+     * @return Suite.
+     * @throws Exception In case of error.
+     */
+    public static TestSuite suite() throws Exception {
+        GridTestProperties.setProperty(GridTestProperties.MARSH_CLASS_NAME, PortableMarshaller.class.getName());
+
+        TestSuite suite = new TestSuite("Grid Cache Query Test Suite using PortableMarshaller");
+
+        // Parsing
+        suite.addTestSuite(GridQueryParsingTest.class);
+
+        // Queries tests.
+        suite.addTestSuite(GridCacheQueryIndexDisabledSelfTest.class);
+        suite.addTestSuite(IgniteCachePartitionedQueryMultiThreadedSelfTest.class);
+        suite.addTestSuite(IgniteCacheLargeResultSelfTest.class);
+        suite.addTestSuite(IgniteCacheQueryMultiThreadedSelfTest.class);
+        suite.addTestSuite(IgniteCacheQueryEvictsMultiThreadedSelfTest.class);
+        suite.addTestSuite(IgniteCacheQueryOffheapMultiThreadedSelfTest.class);
+
+        suite.addTestSuite(IgniteCacheOffheapTieredMultithreadedSelfTest.class);
+        suite.addTestSuite(GridCacheReduceQueryMultithreadedSelfTest.class);
+
+
+        // Fields queries.
+        suite.addTestSuite(IgniteCacheFieldsQueryNoDataSelfTest.class);
+
+        // Continuous queries.
+        suite.addTestSuite(GridCacheContinuousQueryLocalAtomicSelfTest.class);
+        suite.addTestSuite(GridCacheContinuousQueryReplicatedAtomicSelfTest.class);
+        suite.addTestSuite(GridCacheContinuousQueryPartitionedOnlySelfTest.class);
+        suite.addTestSuite(GridCacheContinuousQueryAtomicSelfTest.class);
+        suite.addTestSuite(GridCacheContinuousQueryAtomicNearEnabledSelfTest.class);
+        suite.addTestSuite(GridCacheContinuousQueryAtomicP2PDisabledSelfTest.class);
+
+        suite.addTestSuite(GridCacheQueryIndexingDisabledSelfTest.class);
+
+        //Should be adjusted. Not ready to be used with PortableMarshaller.
+        //suite.addTestSuite(GridCachePortableSwapScanQuerySelfTest.class);
+
+        suite.addTestSuite(GridOrderedMessageCancelSelfTest.class);
+
+        // Ignite cache and H2 comparison.
+        suite.addTestSuite(BaseH2CompareQueryTest.class);
+        suite.addTestSuite(H2CompareBigQueryTest.class);
+
+        // Metrics tests
+        suite.addTestSuite(CacheLocalQueryMetricsSelfTest.class);
+        suite.addTestSuite(CachePartitionedQueryMetricsDistributedSelfTest.class);
+        suite.addTestSuite(CachePartitionedQueryMetricsLocalSelfTest.class);
+        suite.addTestSuite(CacheReplicatedQueryMetricsDistributedSelfTest.class);
+        suite.addTestSuite(CacheReplicatedQueryMetricsLocalSelfTest.class);
+
+        //Unmarshallig query test.
+        suite.addTestSuite(IgniteCacheP2pUnmarshallingQueryErrorTest.class);
+
+        suite.addTestSuite(GridCachePortableDuplicateIndexObjectPartitionedAtomicSelfTest.class);
+        suite.addTestSuite(GridCachePortableDuplicateIndexObjectPartitionedTransactionalSelfTest.class);
+
+        return suite;
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformInputStream.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformInputStream.java b/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformInputStream.java
index 96db40d..6d0d107 100644
--- a/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformInputStream.java
+++ b/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformInputStream.java
@@ -17,12 +17,12 @@
 
 package org.apache.ignite.internal.platform.memory;
 
-import org.apache.ignite.internal.processors.portable.*;
+import org.apache.ignite.internal.portable.streams.*;
 
 /**
  * Interop output stream,
  */
-public interface PlatformInputStream extends GridPortableInputStream {
+public interface PlatformInputStream extends PortableInputStream {
     /**
      * Synchronize input. Must be called before start reading data from a memory changed by another platform.
      */

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformOutputStream.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformOutputStream.java b/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformOutputStream.java
index cd3c676..89527ce 100644
--- a/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformOutputStream.java
+++ b/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformOutputStream.java
@@ -17,12 +17,12 @@
 
 package org.apache.ignite.internal.platform.memory;
 
-import org.apache.ignite.internal.processors.portable.*;
+import org.apache.ignite.internal.portable.streams.*;
 
 /**
  * Interop output stream.
  */
-public interface PlatformOutputStream extends GridPortableOutputStream {
+public interface PlatformOutputStream extends PortableOutputStream {
     /**
      * Synchronize output stream with underlying memory
      */

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/spring/src/main/java/org/apache/ignite/IgniteSpringBean.java
----------------------------------------------------------------------
diff --git a/modules/spring/src/main/java/org/apache/ignite/IgniteSpringBean.java b/modules/spring/src/main/java/org/apache/ignite/IgniteSpringBean.java
index 3228210..a1a1b46 100644
--- a/modules/spring/src/main/java/org/apache/ignite/IgniteSpringBean.java
+++ b/modules/spring/src/main/java/org/apache/ignite/IgniteSpringBean.java
@@ -339,6 +339,13 @@ public class IgniteSpringBean implements Ignite, DisposableBean, InitializingBea
     }
 
     /** {@inheritDoc} */
+    @Override public IgnitePortables portables() {
+        assert g != null;
+
+        return g.portables();
+    }
+
+    /** {@inheritDoc} */
     @Override public void close() throws IgniteException {
         g.close();
     }

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/parent/pom.xml
----------------------------------------------------------------------
diff --git a/parent/pom.xml b/parent/pom.xml
index 49aa36f..17fcea7 100644
--- a/parent/pom.xml
+++ b/parent/pom.xml
@@ -318,6 +318,10 @@
                                 <packages>org.apache.ignite.marshaller*</packages>
                             </group>
                             <group>
+                                <title>Portable Objects API</title>
+                                <packages>org.apache.ignite.portable*</packages>
+                            </group>
+                            <group>
                                 <title>Visor Plugins</title>
                                 <packages>org.apache.ignite.visor.plugin</packages>
                             </group>
@@ -703,6 +707,10 @@
                                         <exclude>dev-tools/.gradle/**/*</exclude>
                                         <exclude>dev-tools/gradle/wrapper/**/*</exclude>
                                         <exclude>dev-tools/gradlew</exclude>
+                                        <exclude>src/test/portables/repo/org/apache/ignite/portable/test2/1.1/test2-1.1.pom</exclude>
+                                        <exclude>src/test/portables/repo/org/apache/ignite/portable/test2/maven-metadata-local.xml</exclude>
+                                        <exclude>src/test/portables/repo/org/apache/ignite/portable/test1/1.1/test1-1.1.pom</exclude>
+                                        <exclude>src/test/portables/repo/org/apache/ignite/portable/test1/maven-metadata-local.xml</exclude>
                                         <!--shmem-->
                                         <exclude>ipc/shmem/**/Makefile.in</exclude><!--auto generated files-->
                                         <exclude>ipc/shmem/**/Makefile</exclude><!--auto generated files-->


[44/59] [abbrv] ignite git commit: Moved InteropTarget interface to Ignite.

Posted by vk...@apache.org.
Moved InteropTarget interface to Ignite.


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

Branch: refs/heads/ignite-884
Commit: 93821183ae44cf1b1d0fd5c3ed30b65f611d2da6
Parents: a43e80a
Author: vozerov-gridgain <vo...@gridgain.com>
Authored: Wed Aug 26 13:19:25 2015 +0300
Committer: vozerov-gridgain <vo...@gridgain.com>
Committed: Wed Aug 26 13:19:25 2015 +0300

----------------------------------------------------------------------
 .../processors/platform/PlatformTarget.java     | 76 ++++++++++++++++++++
 1 file changed, 76 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/93821183/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/PlatformTarget.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/PlatformTarget.java b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/PlatformTarget.java
new file mode 100644
index 0000000..1d54b4e
--- /dev/null
+++ b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/PlatformTarget.java
@@ -0,0 +1,76 @@
+/*
+ * 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.platform;
+
+import org.jetbrains.annotations.*;
+
+/**
+ * Interop target abstraction.
+ */
+@SuppressWarnings("UnusedDeclaration")
+public interface PlatformTarget {
+    /**
+     * Synchronous IN operation.
+     *
+     * @param type Operation type.
+     * @param memPtr Memory pointer.
+     * @return Value specific for the given operation otherwise.
+     * @throws Exception If failed.
+     */
+    public int inOp(int type, long memPtr) throws Exception;
+
+    /**
+     * Synchronous IN operation which returns managed object as result.
+     *
+     * @param type Operation type.
+     * @param memPtr Memory pointer.
+     * @return Managed result.
+     * @throws Exception If case of failure.
+     */
+    public Object inOpObject(int type, long memPtr) throws Exception;
+
+    /**
+     * Synchronous OUT operation.
+     *
+     * @param type Operation type.
+     * @param memPtr Memory pointer.
+     * @throws Exception In case of failure.
+     */
+    public void outOp(int type, long memPtr) throws Exception;
+
+    /**
+     * Synchronous IN-OUT operation.
+     *
+     * @param type Operation type.
+     * @param inMemPtr Input memory pointer.
+     * @param outMemPtr Output memory pointer.
+     * @throws Exception In case of failure.
+     */
+    public void inOutOp(int type, long inMemPtr, long outMemPtr) throws Exception;
+
+    /**
+     * Synchronous IN-OUT operation with optional argument.
+     *
+     * @param type Operation type.
+     * @param inMemPtr Input memory pointer.
+     * @param outMemPtr Output memory pointer.
+     * @param arg Argument (optional).
+     * @throws Exception In case of failure.
+     */
+    public void inOutOp(int type, long inMemPtr, long outMemPtr, @Nullable Object arg) throws Exception;
+}


[05/59] [abbrv] ignite git commit: ignite-1258: portable objects API support in Ignite

Posted by vk...@apache.org.
http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/java/org/apache/ignite/internal/portable/GridPortableBuilderAdditionalSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/portable/GridPortableBuilderAdditionalSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/portable/GridPortableBuilderAdditionalSelfTest.java
new file mode 100644
index 0000000..1a41a4d
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/portable/GridPortableBuilderAdditionalSelfTest.java
@@ -0,0 +1,1001 @@
+/*
+ * 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.portable;
+
+import org.apache.ignite.*;
+import org.apache.ignite.configuration.*;
+import org.apache.ignite.internal.portable.mutabletest.*;
+import org.apache.ignite.internal.processors.cache.portable.*;
+import org.apache.ignite.internal.util.lang.*;
+import org.apache.ignite.marshaller.portable.*;
+import org.apache.ignite.portable.*;
+import org.apache.ignite.testframework.*;
+import org.apache.ignite.testframework.junits.common.*;
+
+import com.google.common.collect.*;
+import org.junit.*;
+
+import java.lang.reflect.*;
+import java.sql.*;
+import java.util.*;
+import java.util.Date;
+
+import static org.apache.ignite.cache.CacheMode.*;
+import static org.apache.ignite.internal.portable.mutabletest.GridPortableTestClasses.*;
+
+/**
+ *
+ */
+public class GridPortableBuilderAdditionalSelfTest extends GridCommonAbstractTest {
+    /** {@inheritDoc} */
+    @Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception {
+        IgniteConfiguration cfg = super.getConfiguration(gridName);
+
+        CacheConfiguration cacheCfg = new CacheConfiguration();
+
+        cacheCfg.setCacheMode(REPLICATED);
+
+        cfg.setCacheConfiguration(cacheCfg);
+
+        PortableMarshaller marsh = new PortableMarshaller();
+
+        marsh.setClassNames(Arrays.asList("org.apache.ignite.internal.portable.mutabletest.*"));
+
+        marsh.setConvertStringToBytes(useUtf8());
+
+        cfg.setMarshaller(marsh);
+
+        return cfg;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void beforeTestsStarted() throws Exception {
+        startGrids(1);
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void afterTestsStopped() throws Exception {
+        stopAllGrids();
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void afterTest() throws Exception {
+        jcache(0).clear();
+    }
+
+    /**
+     * @return Whether to use UTF8 strings.
+     */
+    protected boolean useUtf8() {
+        return true;
+    }
+
+    /**
+     * @return Portables API.
+     */
+    protected IgnitePortables portables() {
+        return grid(0).portables();
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testSimpleTypeFieldRead() throws Exception {
+        TestObjectAllTypes exp = new TestObjectAllTypes();
+
+        exp.setDefaultData();
+
+        PortableBuilder mutPo = wrap(exp);
+
+        for (Field field : TestObjectAllTypes.class.getDeclaredFields()) {
+            Object expVal = field.get(exp);
+            Object actVal = mutPo.getField(field.getName());
+
+            switch (field.getName()) {
+                case "anEnum":
+                    assertEquals(((PortableBuilderEnum)actVal).getOrdinal(), ((Enum)expVal).ordinal());
+                    break;
+
+                case "enumArr": {
+                    PortableBuilderEnum[] actArr = (PortableBuilderEnum[])actVal;
+                    Enum[] expArr = (Enum[])expVal;
+
+                    assertEquals(expArr.length, actArr.length);
+
+                    for (int i = 0; i < actArr.length; i++)
+                        assertEquals(expArr[i].ordinal(), actArr[i].getOrdinal());
+
+                    break;
+                }
+
+                case "entry":
+                    assertEquals(((Map.Entry)expVal).getKey(), ((Map.Entry)actVal).getKey());
+                    assertEquals(((Map.Entry)expVal).getValue(), ((Map.Entry)actVal).getValue());
+                    break;
+
+                default:
+                    assertTrue(field.getName(), Objects.deepEquals(expVal, actVal));
+                    break;
+            }
+        }
+    }
+
+    /**
+     *
+     */
+    public void testSimpleTypeFieldSerialize() {
+        TestObjectAllTypes exp = new TestObjectAllTypes();
+
+        exp.setDefaultData();
+
+        PortableBuilderImpl mutPo = wrap(exp);
+
+        TestObjectAllTypes res = mutPo.build().deserialize();
+
+        GridTestUtils.deepEquals(exp, res);
+    }
+
+    /**
+     * @throws Exception If any error occurs.
+     */
+    public void testSimpleTypeFieldOverride() throws Exception {
+        TestObjectAllTypes exp = new TestObjectAllTypes();
+
+        exp.setDefaultData();
+
+        PortableBuilderImpl mutPo = wrap(new TestObjectAllTypes());
+
+        for (Field field : TestObjectAllTypes.class.getDeclaredFields())
+            mutPo.setField(field.getName(), field.get(exp));
+
+        TestObjectAllTypes res = mutPo.build().deserialize();
+
+        GridTestUtils.deepEquals(exp, res);
+    }
+
+    /**
+     * @throws Exception If any error occurs.
+     */
+    public void testSimpleTypeFieldSetNull() throws Exception {
+        TestObjectAllTypes exp = new TestObjectAllTypes();
+
+        exp.setDefaultData();
+
+        PortableBuilderImpl mutPo = wrap(exp);
+
+        for (Field field : TestObjectAllTypes.class.getDeclaredFields()) {
+            if (!field.getType().isPrimitive())
+                mutPo.setField(field.getName(), null);
+        }
+
+        TestObjectAllTypes res = mutPo.build().deserialize();
+
+        for (Field field : TestObjectAllTypes.class.getDeclaredFields()) {
+            if (!field.getType().isPrimitive())
+                assertNull(field.getName(), field.get(res));
+        }
+    }
+
+    /**
+     * @throws IgniteCheckedException If any error occurs.
+     */
+    public void testMakeCyclicDependency() throws IgniteCheckedException {
+        TestObjectOuter outer = new TestObjectOuter();
+        outer.inner = new TestObjectInner();
+
+        PortableBuilderImpl mutOuter = wrap(outer);
+
+        PortableBuilderImpl mutInner = mutOuter.getField("inner");
+
+        mutInner.setField("outer", mutOuter);
+        mutInner.setField("foo", mutInner);
+
+        TestObjectOuter res = mutOuter.build().deserialize();
+
+        assertEquals(res, res.inner.outer);
+        assertEquals(res.inner, res.inner.foo);
+    }
+
+    /**
+     *
+     */
+    public void testSimpleArrayModification() {
+        TestObjectAllTypes obj = new TestObjectAllTypes();
+
+        obj.strArr = new String[]{"a", "a", "a"};
+
+        PortableBuilderImpl mutObj = wrap(obj);
+
+        String[] arr = mutObj.getField("strArr");
+        arr[0] = "b";
+
+        TestObjectAllTypes res = mutObj.build().deserialize();
+
+        Assert.assertArrayEquals(obj.strArr, res.strArr);
+    }
+
+    /**
+     *
+     */
+    public void testModifyObjectArray() {
+        fail("https://issues.apache.org/jira/browse/IGNITE-1273");
+
+        TestObjectContainer obj = new TestObjectContainer();
+        obj.foo = new Object[]{"a"};
+
+        PortableBuilderImpl mutObj = wrap(obj);
+
+        Object[] arr = mutObj.getField("foo");
+
+        Assert.assertArrayEquals(new Object[]{"a"}, arr);
+
+        arr[0] = "b";
+
+        TestObjectContainer res = mutObj.build().deserialize();
+
+        Assert.assertArrayEquals(new Object[] {"a"}, (Object[])res.foo);
+    }
+
+    /**
+     *
+     */
+    public void testOverrideObjectArrayField() {
+        PortableBuilderImpl mutObj = wrap(new TestObjectContainer());
+
+        Object[] createdArr = {mutObj, "a", 1, new String[] {"s", "s"}, new byte[]{1, 2}, new UUID(3, 0)};
+
+        mutObj.setField("foo", createdArr.clone());
+
+        TestObjectContainer res = mutObj.build().deserialize();
+
+        createdArr[0] = res;
+
+        assertTrue(Objects.deepEquals(createdArr, res.foo));
+    }
+
+    /**
+     *
+     */
+    public void testDeepArray() {
+        TestObjectContainer obj = new TestObjectContainer();
+        obj.foo = new Object[]{new Object[]{"a", obj}};
+
+        PortableBuilderImpl mutObj = wrap(obj);
+
+        Object[] arr = (Object[])mutObj.<Object[]>getField("foo")[0];
+
+        assertEquals("a", arr[0]);
+        assertSame(mutObj, arr[1]);
+
+        arr[0] = mutObj;
+
+        TestObjectContainer res = mutObj.build().deserialize();
+
+        arr = (Object[])((Object[])res.foo)[0];
+
+        assertSame(arr[0], res);
+        assertSame(arr[0], arr[1]);
+    }
+
+    /**
+     *
+     */
+    public void testArrayListRead() {
+        TestObjectContainer obj = new TestObjectContainer();
+        obj.foo = Lists.newArrayList(obj, "a");
+
+        PortableBuilderImpl mutObj = wrap(obj);
+
+        List<Object> list = mutObj.getField("foo");
+
+        assert list.equals(Lists.newArrayList(mutObj, "a"));
+    }
+
+    /**
+     *
+     */
+    public void testArrayListOverride() {
+        TestObjectContainer obj = new TestObjectContainer();
+
+        PortableBuilderImpl mutObj = wrap(obj);
+
+        ArrayList<Object> list = Lists.newArrayList(mutObj, "a", Lists.newArrayList(1, 2));
+
+        mutObj.setField("foo", list);
+
+        TestObjectContainer res = mutObj.build().deserialize();
+
+        list.set(0, res);
+
+        assertNotSame(list, res.foo);
+        assertEquals(list, res.foo);
+    }
+
+    /**
+     *
+     */
+    public void testArrayListModification() {
+        TestObjectContainer obj = new TestObjectContainer();
+        obj.foo = Lists.newArrayList("a", "b", "c");
+
+        PortableBuilderImpl mutObj = wrap(obj);
+
+        List<String> list = mutObj.getField("foo");
+
+        list.add("!"); // "a", "b", "c", "!"
+        list.add(0, "_"); // "_", "a", "b", "c", "!"
+
+        String s = list.remove(1); // "_", "b", "c", "!"
+        assertEquals("a", s);
+
+        assertEquals(Arrays.asList("c", "!"), list.subList(2, 4));
+        assertEquals(1, list.indexOf("b"));
+        assertEquals(1, list.lastIndexOf("b"));
+
+        TestObjectContainer res = mutObj.build().deserialize();
+
+        assertTrue(res.foo instanceof ArrayList);
+        assertEquals(Arrays.asList("_", "b", "c", "!"), res.foo);
+    }
+
+    /**
+     *
+     */
+    public void testArrayListClear() {
+        TestObjectContainer obj = new TestObjectContainer();
+        obj.foo = Lists.newArrayList("a", "b", "c");
+
+        PortableBuilderImpl mutObj = wrap(obj);
+
+        List<String> list = mutObj.getField("foo");
+
+        list.clear();
+
+        assertEquals(Collections.emptyList(), mutObj.build().<TestObjectContainer>deserialize().foo);
+    }
+
+    /**
+     *
+     */
+    public void testArrayListWriteUnmodifiable() {
+        TestObjectContainer obj = new TestObjectContainer();
+
+        ArrayList<Object> src = Lists.newArrayList(obj, "a", "b", "c");
+
+        obj.foo = src;
+
+        PortableBuilderImpl mutObj = wrap(obj);
+
+        TestObjectContainer deserialized = mutObj.build().deserialize();
+
+        List<Object> res = (List<Object>)deserialized.foo;
+
+        src.set(0, deserialized);
+
+        assertEquals(src, res);
+    }
+
+    /**
+     *
+     */
+    public void testLinkedListRead() {
+        TestObjectContainer obj = new TestObjectContainer();
+        obj.foo = Lists.newLinkedList(Arrays.asList(obj, "a"));
+
+        PortableBuilderImpl mutObj = wrap(obj);
+
+        List<Object> list = mutObj.getField("foo");
+
+        assert list.equals(Lists.newLinkedList(Arrays.asList(mutObj, "a")));
+    }
+
+    /**
+     *
+     */
+    public void testLinkedListOverride() {
+        TestObjectContainer obj = new TestObjectContainer();
+
+        PortableBuilderImpl mutObj = wrap(obj);
+
+        List<Object> list = Lists.newLinkedList(Arrays.asList(mutObj, "a", Lists.newLinkedList(Arrays.asList(1, 2))));
+
+        mutObj.setField("foo", list);
+
+        TestObjectContainer res = mutObj.build().deserialize();
+
+        list.set(0, res);
+
+        assertNotSame(list, res.foo);
+        assertEquals(list, res.foo);
+    }
+
+    /**
+     *
+     */
+    public void testLinkedListModification() {
+        TestObjectContainer obj = new TestObjectContainer();
+
+        obj.foo = Lists.newLinkedList(Arrays.asList("a", "b", "c"));
+
+        PortableBuilderImpl mutObj = wrap(obj);
+
+        List<String> list = mutObj.getField("foo");
+
+        list.add("!"); // "a", "b", "c", "!"
+        list.add(0, "_"); // "_", "a", "b", "c", "!"
+
+        String s = list.remove(1); // "_", "b", "c", "!"
+        assertEquals("a", s);
+
+        assertEquals(Arrays.asList("c", "!"), list.subList(2, 4));
+        assertEquals(1, list.indexOf("b"));
+        assertEquals(1, list.lastIndexOf("b"));
+
+        TestObjectContainer res = mutObj.build().deserialize();
+
+        assertTrue(res.foo instanceof LinkedList);
+        assertEquals(Arrays.asList("_", "b", "c", "!"), res.foo);
+    }
+
+    /**
+     *
+     */
+    public void testLinkedListWriteUnmodifiable() {
+        TestObjectContainer obj = new TestObjectContainer();
+
+        LinkedList<Object> src = Lists.newLinkedList(Arrays.asList(obj, "a", "b", "c"));
+
+        obj.foo = src;
+
+        PortableBuilderImpl mutObj = wrap(obj);
+
+        TestObjectContainer deserialized = mutObj.build().deserialize();
+
+        List<Object> res = (List<Object>)deserialized.foo;
+
+        src.set(0, deserialized);
+
+        assertEquals(src, res);
+    }
+
+    /**
+     *
+     */
+    public void testHashSetRead() {
+        TestObjectContainer obj = new TestObjectContainer();
+        obj.foo = Sets.newHashSet(obj, "a");
+
+        PortableBuilderImpl mutObj = wrap(obj);
+
+        Set<Object> set = mutObj.getField("foo");
+
+        assert set.equals(Sets.newHashSet(mutObj, "a"));
+    }
+
+    /**
+     *
+     */
+    public void testHashSetOverride() {
+        TestObjectContainer obj = new TestObjectContainer();
+
+        PortableBuilderImpl mutObj = wrap(obj);
+
+        Set<Object> c = Sets.newHashSet(mutObj, "a", Sets.newHashSet(1, 2));
+
+        mutObj.setField("foo", c);
+
+        TestObjectContainer res = mutObj.build().deserialize();
+
+        c.remove(mutObj);
+        c.add(res);
+
+        assertNotSame(c, res.foo);
+        assertEquals(c, res.foo);
+    }
+
+    /**
+     *
+     */
+    public void testHashSetModification() {
+        TestObjectContainer obj = new TestObjectContainer();
+        obj.foo = Sets.newHashSet("a", "b", "c");
+
+        PortableBuilderImpl mutObj = wrap(obj);
+
+        Set<String> set = mutObj.getField("foo");
+
+        set.remove("b");
+        set.add("!");
+
+        assertEquals(Sets.newHashSet("a", "!", "c"), set);
+        assertTrue(set.contains("a"));
+        assertTrue(set.contains("!"));
+
+        TestObjectContainer res = mutObj.build().deserialize();
+
+        assertTrue(res.foo instanceof HashSet);
+        assertEquals(Sets.newHashSet("a", "!", "c"), res.foo);
+    }
+
+    /**
+     *
+     */
+    public void testHashSetWriteUnmodifiable() {
+        TestObjectContainer obj = new TestObjectContainer();
+
+        Set<Object> src = Sets.newHashSet(obj, "a", "b", "c");
+
+        obj.foo = src;
+
+        TestObjectContainer deserialized = wrap(obj).build().deserialize();
+
+        Set<Object> res = (Set<Object>)deserialized.foo;
+
+        src.remove(obj);
+        src.add(deserialized);
+
+        assertEquals(src, res);
+    }
+
+    /**
+     *
+     */
+    public void testMapRead() {
+        TestObjectContainer obj = new TestObjectContainer();
+        obj.foo = Maps.newHashMap(ImmutableMap.of(obj, "a", "b", obj));
+
+        PortableBuilderImpl mutObj = wrap(obj);
+
+        Map<Object, Object> map = mutObj.getField("foo");
+
+        assert map.equals(ImmutableMap.of(mutObj, "a", "b", mutObj));
+    }
+
+    /**
+     *
+     */
+    public void testMapOverride() {
+        TestObjectContainer obj = new TestObjectContainer();
+
+        PortableBuilderImpl mutObj = wrap(obj);
+
+        Map<Object, Object> map = Maps.newHashMap(ImmutableMap.of(mutObj, "a", "b", mutObj));
+
+        mutObj.setField("foo", map);
+
+        TestObjectContainer res = mutObj.build().deserialize();
+
+        assertEquals(ImmutableMap.of(res, "a", "b", res), res.foo);
+    }
+
+    /**
+     *
+     */
+    public void testMapModification() {
+        TestObjectContainer obj = new TestObjectContainer();
+        obj.foo = Maps.newHashMap(ImmutableMap.of(1, "a", 2, "b"));
+
+        PortableBuilderImpl mutObj = wrap(obj);
+
+        Map<Object, Object> map = mutObj.getField("foo");
+
+        map.put(3, mutObj);
+        Object rmv = map.remove(1);
+
+        assertEquals("a", rmv);
+
+        TestObjectContainer res = mutObj.build().deserialize();
+
+        assertEquals(ImmutableMap.of(2, "b", 3, res), res.foo);
+    }
+
+    /**
+     *
+     */
+    public void testEnumArrayModification() {
+        TestObjectAllTypes obj = new TestObjectAllTypes();
+
+        obj.enumArr = new TestObjectEnum[]{TestObjectEnum.A, TestObjectEnum.B};
+
+        PortableBuilderImpl mutObj = wrap(obj);
+
+        PortableBuilderEnum[] arr = mutObj.getField("enumArr");
+        arr[0] = new PortableBuilderEnum(mutObj.typeId(), TestObjectEnum.B);
+
+        TestObjectAllTypes res = mutObj.build().deserialize();
+
+        Assert.assertArrayEquals(new TestObjectEnum[] {TestObjectEnum.A, TestObjectEnum.B}, res.enumArr);
+    }
+
+    /**
+     *
+     */
+    public void testEditObjectWithRawData() {
+        GridPortableMarshalerAwareTestClass obj = new GridPortableMarshalerAwareTestClass();
+
+        obj.s = "a";
+        obj.sRaw = "aa";
+
+        PortableBuilderImpl mutableObj = wrap(obj);
+
+        mutableObj.setField("s", "z");
+
+        GridPortableMarshalerAwareTestClass res = mutableObj.build().deserialize();
+        assertEquals("z", res.s);
+        assertEquals("aa", res.sRaw);
+    }
+
+    /**
+     *
+     */
+    public void testHashCode() {
+        TestObjectContainer obj = new TestObjectContainer();
+
+        PortableBuilderImpl mutableObj = wrap(obj);
+
+        assertEquals(obj.hashCode(), mutableObj.build().hashCode());
+
+        mutableObj.hashCode(25);
+
+        assertEquals(25, mutableObj.build().hashCode());
+    }
+
+    /**
+     *
+     */
+    public void testCollectionsInCollection() {
+        TestObjectContainer obj = new TestObjectContainer();
+        obj.foo = Lists.newArrayList(
+            Lists.newArrayList(1, 2),
+            Lists.newLinkedList(Arrays.asList(1, 2)),
+            Sets.newHashSet("a", "b"),
+            Sets.newLinkedHashSet(Arrays.asList("a", "b")),
+            Maps.newHashMap(ImmutableMap.of(1, "a", 2, "b")));
+
+        TestObjectContainer deserialized = wrap(obj).build().deserialize();
+
+        assertEquals(obj.foo, deserialized.foo);
+    }
+
+    /**
+     *
+     */
+    public void testMapEntryModification() {
+        TestObjectContainer obj = new TestObjectContainer();
+        obj.foo = ImmutableMap.of(1, "a").entrySet().iterator().next();
+
+        PortableBuilderImpl mutableObj = wrap(obj);
+
+        Map.Entry<Object, Object> entry = mutableObj.getField("foo");
+
+        assertEquals(1, entry.getKey());
+        assertEquals("a", entry.getValue());
+
+        entry.setValue("b");
+
+        TestObjectContainer res = mutableObj.build().deserialize();
+
+        assertEquals(new GridMapEntry<>(1, "b"), res.foo);
+    }
+
+    /**
+     *
+     */
+    public void testMapEntryOverride() {
+        TestObjectContainer obj = new TestObjectContainer();
+
+        PortableBuilderImpl mutableObj = wrap(obj);
+
+        mutableObj.setField("foo", new GridMapEntry<>(1, "a"));
+
+        TestObjectContainer res = mutableObj.build().deserialize();
+
+        assertEquals(new GridMapEntry<>(1, "a"), res.foo);
+    }
+
+    /**
+     *
+     */
+    public void testMetadataChangingDoublePut() {
+        PortableBuilderImpl mutableObj = wrap(new TestObjectContainer());
+
+        mutableObj.setField("xx567", "a");
+        mutableObj.setField("xx567", "b");
+
+        mutableObj.build();
+
+        PortableMetadata metadata = portables().metadata(TestObjectContainer.class);
+
+        assertEquals("String", metadata.fieldTypeName("xx567"));
+    }
+
+    /**
+     *
+     */
+    public void testMetadataChangingDoublePut2() {
+        PortableBuilderImpl mutableObj = wrap(new TestObjectContainer());
+
+        mutableObj.setField("xx567", "a");
+        mutableObj.setField("xx567", "b");
+
+        mutableObj.build();
+
+        PortableMetadata metadata = portables().metadata(TestObjectContainer.class);
+
+        assertEquals("String", metadata.fieldTypeName("xx567"));
+    }
+
+    /**
+     *
+     */
+    public void testMetadataChanging() {
+        TestObjectContainer c = new TestObjectContainer();
+
+        PortableBuilderImpl mutableObj = wrap(c);
+
+        mutableObj.setField("intField", 1);
+        mutableObj.setField("intArrField", new int[] {1});
+        mutableObj.setField("arrField", new String[] {"1"});
+        mutableObj.setField("strField", "1");
+        mutableObj.setField("colField", Lists.newArrayList("1"));
+        mutableObj.setField("mapField", Maps.newHashMap(ImmutableMap.of(1, "1")));
+        mutableObj.setField("enumField", TestObjectEnum.A);
+        mutableObj.setField("enumArrField", new Enum[] {TestObjectEnum.A});
+
+        mutableObj.build();
+
+        PortableMetadata metadata = portables().metadata(c.getClass());
+
+        assertTrue(metadata.fields().containsAll(Arrays.asList("intField", "intArrField", "arrField", "strField",
+            "colField", "mapField", "enumField", "enumArrField")));
+
+        assertEquals("int", metadata.fieldTypeName("intField"));
+        assertEquals("int[]", metadata.fieldTypeName("intArrField"));
+        assertEquals("String[]", metadata.fieldTypeName("arrField"));
+        assertEquals("String", metadata.fieldTypeName("strField"));
+        assertEquals("Collection", metadata.fieldTypeName("colField"));
+        assertEquals("Map", metadata.fieldTypeName("mapField"));
+        assertEquals("Enum", metadata.fieldTypeName("enumField"));
+        assertEquals("Enum[]", metadata.fieldTypeName("enumArrField"));
+    }
+
+    /**
+     *
+     */
+    public void testDateInObjectField() {
+        TestObjectContainer obj = new TestObjectContainer();
+
+        obj.foo = new Date();
+
+        PortableBuilderImpl mutableObj = wrap(obj);
+
+        assertEquals(Timestamp.class, mutableObj.getField("foo").getClass());
+    }
+
+    /**
+     *
+     */
+    public void testDateInCollection() {
+        TestObjectContainer obj = new TestObjectContainer();
+
+        obj.foo = Lists.newArrayList(new Date());
+
+        PortableBuilderImpl mutableObj = wrap(obj);
+
+        assertEquals(Timestamp.class, ((List<?>)mutableObj.getField("foo")).get(0).getClass());
+    }
+
+    /**
+     *
+     */
+    @SuppressWarnings("AssertEqualsBetweenInconvertibleTypes")
+    public void testDateArrayOverride() {
+        TestObjectContainer obj = new TestObjectContainer();
+
+        PortableBuilderImpl mutableObj = wrap(obj);
+
+        Date[] arr = {new Date()};
+
+        mutableObj.setField("foo", arr);
+
+        TestObjectContainer res = mutableObj.build().deserialize();
+
+        assertEquals(Date[].class, res.foo.getClass());
+        assertTrue(Objects.deepEquals(arr, res.foo));
+    }
+
+    /**
+     *
+     */
+    public void testChangeMap() {
+        AddressBook addrBook = new AddressBook();
+
+        addrBook.addCompany(new Company(1, "Google inc", 100, new Address("Saint-Petersburg", "Torzhkovskya", 1, 53), "occupation"));
+        addrBook.addCompany(new Company(2, "Apple inc", 100, new Address("Saint-Petersburg", "Torzhkovskya", 1, 54), "occupation"));
+        addrBook.addCompany(new Company(3, "Microsoft", 100, new Address("Saint-Petersburg", "Torzhkovskya", 1, 55), "occupation"));
+        addrBook.addCompany(new Company(4, "Oracle", 100, new Address("Saint-Petersburg", "Nevskiy", 1, 1), "occupation"));
+
+        PortableBuilderImpl mutableObj = wrap(addrBook);
+
+        Map<String, List<PortableBuilderImpl>> map = mutableObj.getField("companyByStreet");
+
+        List<PortableBuilderImpl> list = map.get("Torzhkovskya");
+
+        PortableBuilderImpl company = list.get(0);
+
+        assert "Google inc".equals(company.<String>getField("name"));
+
+        list.remove(0);
+
+        AddressBook res = mutableObj.build().deserialize();
+
+        assertEquals(Arrays.asList("Nevskiy", "Torzhkovskya"), new ArrayList<>(res.getCompanyByStreet().keySet()));
+
+        List<Company> torzhkovskyaCompanies = res.getCompanyByStreet().get("Torzhkovskya");
+
+        assertEquals(2, torzhkovskyaCompanies.size());
+        assertEquals("Apple inc", torzhkovskyaCompanies.get(0).name);
+    }
+
+    /**
+     *
+     */
+    public void testSavingObjectWithNotZeroStart() {
+        TestObjectOuter out = new TestObjectOuter();
+        TestObjectInner inner = new TestObjectInner();
+
+        out.inner = inner;
+        inner.outer = out;
+
+        PortableBuilderImpl builder = wrap(out);
+
+        PortableBuilderImpl innerBuilder = builder.getField("inner");
+
+        TestObjectInner res = innerBuilder.build().deserialize();
+
+        assertSame(res, res.outer.inner);
+    }
+
+    /**
+     *
+     */
+    public void testPortableObjectField() {
+        TestObjectContainer container = new TestObjectContainer(toPortable(new TestObjectArrayList()));
+
+        PortableBuilderImpl wrapper = wrap(container);
+
+        assertTrue(wrapper.getField("foo") instanceof PortableObject);
+
+        TestObjectContainer deserialized = wrapper.build().deserialize();
+        assertTrue(deserialized.foo instanceof PortableObject);
+    }
+
+    /**
+     *
+     */
+    public void testAssignPortableObject() {
+        TestObjectContainer container = new TestObjectContainer();
+
+        PortableBuilderImpl wrapper = wrap(container);
+
+        wrapper.setField("foo", toPortable(new TestObjectArrayList()));
+
+        TestObjectContainer deserialized = wrapper.build().deserialize();
+        assertTrue(deserialized.foo instanceof TestObjectArrayList);
+    }
+
+    /**
+     *
+     */
+    public void testRemoveFromNewObject() {
+        PortableBuilderImpl wrapper = newWrapper(TestObjectAllTypes.class);
+
+        wrapper.setField("str", "a");
+
+        wrapper.removeField("str");
+
+        assertNull(wrapper.build().<TestObjectAllTypes>deserialize().str);
+    }
+
+    /**
+     *
+     */
+    public void testRemoveFromExistingObject() {
+        TestObjectAllTypes obj = new TestObjectAllTypes();
+        obj.setDefaultData();
+
+        PortableBuilderImpl wrapper = wrap(toPortable(obj));
+
+        wrapper.removeField("str");
+
+        assertNull(wrapper.build().<TestObjectAllTypes>deserialize().str);
+    }
+
+    /**
+     *
+     */
+    public void testCyclicArrays() {
+        fail("https://issues.apache.org/jira/browse/IGNITE-1273");
+
+        TestObjectContainer obj = new TestObjectContainer();
+
+        Object[] arr1 = new Object[1];
+        Object[] arr2 = new Object[]{arr1};
+
+        arr1[0] = arr2;
+
+        obj.foo = arr1;
+
+        TestObjectContainer res = toPortable(obj).deserialize();
+
+        Object[] resArr = (Object[])res.foo;
+
+        assertSame(((Object[])resArr[0])[0], resArr);
+    }
+
+    /**
+     *
+     */
+    @SuppressWarnings("TypeMayBeWeakened")
+    public void testCyclicArrayList() {
+        fail("https://issues.apache.org/jira/browse/IGNITE-1273");
+        TestObjectContainer obj = new TestObjectContainer();
+
+        List<Object> arr1 = new ArrayList<>();
+        List<Object> arr2 = new ArrayList<>();
+
+        arr1.add(arr2);
+        arr2.add(arr1);
+
+        obj.foo = arr1;
+
+        TestObjectContainer res = toPortable(obj).deserialize();
+
+        List<?> resArr = (List<?>)res.foo;
+
+        assertSame(((List<Object>)resArr.get(0)).get(0), resArr);
+    }
+
+    /**
+     * @param obj Object.
+     * @return Object in portable format.
+     */
+    private PortableObject toPortable(Object obj) {
+        return portables().toPortable(obj);
+    }
+
+    /**
+     * @param obj Object.
+     * @return GridMutablePortableObject.
+     */
+    private PortableBuilderImpl wrap(Object obj) {
+        return PortableBuilderImpl.wrap(toPortable(obj));
+    }
+
+    /**
+     * @param aCls Class.
+     * @return Wrapper.
+     */
+    private PortableBuilderImpl newWrapper(Class<?> aCls) {
+        CacheObjectPortableProcessorImpl processor = (CacheObjectPortableProcessorImpl)(
+            (IgnitePortablesImpl)portables()).processor();
+
+        return new PortableBuilderImpl(processor.portableContext(), processor.typeId(aCls.getName()),
+            aCls.getSimpleName());
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/java/org/apache/ignite/internal/portable/GridPortableBuilderSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/portable/GridPortableBuilderSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/portable/GridPortableBuilderSelfTest.java
new file mode 100644
index 0000000..6ffa3dd
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/portable/GridPortableBuilderSelfTest.java
@@ -0,0 +1,1007 @@
+/*
+ * 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.portable;
+
+import org.apache.ignite.*;
+import org.apache.ignite.configuration.*;
+import org.apache.ignite.internal.processors.cache.portable.*;
+import org.apache.ignite.internal.util.*;
+import org.apache.ignite.internal.util.typedef.*;
+import org.apache.ignite.marshaller.portable.*;
+import org.apache.ignite.portable.*;
+import org.apache.ignite.testframework.*;
+import org.apache.ignite.testframework.junits.common.*;
+
+import org.apache.ignite.internal.portable.mutabletest.GridPortableTestClasses.*;
+import sun.misc.*;
+
+import java.math.*;
+import java.util.*;
+
+/**
+ * Portable builder test.
+ */
+public class GridPortableBuilderSelfTest extends GridCommonAbstractTest {
+    /** */
+    private static final Unsafe UNSAFE = GridUnsafe.unsafe();
+
+    /** */
+    protected static final long BYTE_ARR_OFF = UNSAFE.arrayBaseOffset(byte[].class);
+
+    /** {@inheritDoc} */
+    @Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception {
+        IgniteConfiguration cfg = super.getConfiguration(gridName);
+
+        PortableMarshaller marsh = new PortableMarshaller();
+
+        marsh.setClassNames(Arrays.asList(Key.class.getName(), Value.class.getName(),
+            "org.gridgain.grid.internal.util.portable.mutabletest.*"));
+
+        PortableTypeConfiguration customIdMapper = new PortableTypeConfiguration();
+
+        customIdMapper.setClassName(CustomIdMapper.class.getName());
+        customIdMapper.setIdMapper(new PortableIdMapper() {
+            @Override public int typeId(String clsName) {
+                return ~PortableContext.DFLT_ID_MAPPER.typeId(clsName);
+            }
+
+            @Override public int fieldId(int typeId, String fieldName) {
+                return typeId + ~PortableContext.DFLT_ID_MAPPER.fieldId(typeId, fieldName);
+            }
+        });
+
+        marsh.setTypeConfigurations(Collections.singleton(customIdMapper));
+
+        marsh.setConvertStringToBytes(useUtf8());
+
+        cfg.setMarshaller(marsh);
+
+        return cfg;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void beforeTestsStarted() throws Exception {
+        startGrids(1);
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void afterTestsStopped() throws Exception {
+        stopAllGrids();
+    }
+
+    /**
+     * @return Whether to use UTF8 strings.
+     */
+    protected boolean useUtf8() {
+        return true;
+    }
+
+    /**
+     *
+     */
+    public void testAllFieldsSerialization() {
+        TestObjectAllTypes obj = new TestObjectAllTypes();
+        obj.setDefaultData();
+        obj.enumArr = null;
+
+        TestObjectAllTypes deserialized = builder(toPortable(obj)).build().deserialize();
+
+        GridTestUtils.deepEquals(obj, deserialized);
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testByteField() throws Exception {
+        PortableBuilder builder = builder("Class");
+
+        builder.hashCode(100);
+
+        builder.setField("byteField", (byte)1);
+
+        PortableObject po = builder.build();
+
+        assertEquals("class".hashCode(), po.typeId());
+        assertEquals(100, po.hashCode());
+
+        assertEquals((byte)1, po.<Byte>field("byteField").byteValue());
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testShortField() throws Exception {
+        PortableBuilder builder = builder("Class");
+
+        builder.hashCode(100);
+
+        builder.setField("shortField", (short)1);
+
+        PortableObject po = builder.build();
+
+        assertEquals("class".hashCode(), po.typeId());
+        assertEquals(100, po.hashCode());
+
+        assertEquals((short)1, po.<Short>field("shortField").shortValue());
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testIntField() throws Exception {
+        PortableBuilder builder = builder("Class");
+
+        builder.hashCode(100);
+
+        builder.setField("intField", 1);
+
+        PortableObject po = builder.build();
+
+        assertEquals("class".hashCode(), po.typeId());
+        assertEquals(100, po.hashCode());
+
+        assertEquals(1, po.<Integer>field("intField").intValue());
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testLongField() throws Exception {
+        PortableBuilder builder = builder("Class");
+
+        builder.hashCode(100);
+
+        builder.setField("longField", 1L);
+
+        PortableObject po = builder.build();
+
+        assertEquals("class".hashCode(), po.typeId());
+        assertEquals(100, po.hashCode());
+
+        assertEquals(1L, po.<Long>field("longField").longValue());
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testFloatField() throws Exception {
+        PortableBuilder builder = builder("Class");
+
+        builder.hashCode(100);
+
+        builder.setField("floatField", 1.0f);
+
+        PortableObject po = builder.build();
+
+        assertEquals("class".hashCode(), po.typeId());
+        assertEquals(100, po.hashCode());
+
+        assertEquals(1.0f, po.<Float>field("floatField").floatValue(), 0);
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testDoubleField() throws Exception {
+        PortableBuilder builder = builder("Class");
+
+        builder.hashCode(100);
+
+        builder.setField("doubleField", 1.0d);
+
+        PortableObject po = builder.build();
+
+        assertEquals("class".hashCode(), po.typeId());
+        assertEquals(100, po.hashCode());
+
+        assertEquals(1.0d, po.<Double>field("doubleField").doubleValue(), 0);
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testCharField() throws Exception {
+        PortableBuilder builder = builder("Class");
+
+        builder.hashCode(100);
+
+        builder.setField("charField", (char)1);
+
+        PortableObject po = builder.build();
+
+        assertEquals("class".hashCode(), po.typeId());
+        assertEquals(100, po.hashCode());
+
+        assertEquals((char)1, po.<Character>field("charField").charValue());
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testBooleanField() throws Exception {
+        PortableBuilder builder = builder("Class");
+
+        builder.hashCode(100);
+
+        builder.setField("booleanField", true);
+
+        PortableObject po = builder.build();
+
+        assertEquals("class".hashCode(), po.typeId());
+        assertEquals(100, po.hashCode());
+
+        assertTrue(po.<Boolean>field("booleanField"));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testDecimalField() throws Exception {
+        PortableBuilder builder = builder("Class");
+
+        builder.hashCode(100);
+
+        builder.setField("decimalField", BigDecimal.TEN);
+
+        PortableObject po = builder.build();
+
+        assertEquals("class".hashCode(), po.typeId());
+        assertEquals(100, po.hashCode());
+
+        assertEquals(BigDecimal.TEN, po.<String>field("decimalField"));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testStringField() throws Exception {
+        PortableBuilder builder = builder("Class");
+
+        builder.hashCode(100);
+
+        builder.setField("stringField", "str");
+
+        PortableObject po = builder.build();
+
+        assertEquals("class".hashCode(), po.typeId());
+        assertEquals(100, po.hashCode());
+
+        assertEquals("str", po.<String>field("stringField"));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testUuidField() throws Exception {
+        PortableBuilder builder = builder("Class");
+
+        builder.hashCode(100);
+
+        UUID uuid = UUID.randomUUID();
+
+        builder.setField("uuidField", uuid);
+
+        PortableObject po = builder.build();
+
+        assertEquals("class".hashCode(), po.typeId());
+        assertEquals(100, po.hashCode());
+
+        assertEquals(uuid, po.<UUID>field("uuidField"));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testByteArrayField() throws Exception {
+        PortableBuilder builder = builder("Class");
+
+        builder.hashCode(100);
+
+        builder.setField("byteArrayField", new byte[] {1, 2, 3});
+
+        PortableObject po = builder.build();
+
+        assertEquals("class".hashCode(), po.typeId());
+        assertEquals(100, po.hashCode());
+
+        assertTrue(Arrays.equals(new byte[] {1, 2, 3}, po.<byte[]>field("byteArrayField")));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testShortArrayField() throws Exception {
+        PortableBuilder builder = builder("Class");
+
+        builder.hashCode(100);
+
+        builder.setField("shortArrayField", new short[] {1, 2, 3});
+
+        PortableObject po = builder.build();
+
+        assertEquals("class".hashCode(), po.typeId());
+        assertEquals(100, po.hashCode());
+
+        assertTrue(Arrays.equals(new short[] {1, 2, 3}, po.<short[]>field("shortArrayField")));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testIntArrayField() throws Exception {
+        PortableBuilder builder = builder("Class");
+
+        builder.hashCode(100);
+
+        builder.setField("intArrayField", new int[] {1, 2, 3});
+
+        PortableObject po = builder.build();
+
+        assertEquals("class".hashCode(), po.typeId());
+        assertEquals(100, po.hashCode());
+
+        assertTrue(Arrays.equals(new int[] {1, 2, 3}, po.<int[]>field("intArrayField")));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testLongArrayField() throws Exception {
+        PortableBuilder builder = builder("Class");
+
+        builder.hashCode(100);
+
+        builder.setField("longArrayField", new long[] {1, 2, 3});
+
+        PortableObject po = builder.build();
+
+        assertEquals("class".hashCode(), po.typeId());
+        assertEquals(100, po.hashCode());
+
+        assertTrue(Arrays.equals(new long[] {1, 2, 3}, po.<long[]>field("longArrayField")));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testFloatArrayField() throws Exception {
+        PortableBuilder builder = builder("Class");
+
+        builder.hashCode(100);
+
+        builder.setField("floatArrayField", new float[] {1, 2, 3});
+
+        PortableObject po = builder.build();
+
+        assertEquals("class".hashCode(), po.typeId());
+        assertEquals(100, po.hashCode());
+
+        assertTrue(Arrays.equals(new float[] {1, 2, 3}, po.<float[]>field("floatArrayField")));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testDoubleArrayField() throws Exception {
+        PortableBuilder builder = builder("Class");
+
+        builder.hashCode(100);
+
+        builder.setField("doubleArrayField", new double[] {1, 2, 3});
+
+        PortableObject po = builder.build();
+
+        assertEquals("class".hashCode(), po.typeId());
+        assertEquals(100, po.hashCode());
+
+        assertTrue(Arrays.equals(new double[] {1, 2, 3}, po.<double[]>field("doubleArrayField")));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testCharArrayField() throws Exception {
+        PortableBuilder builder = builder("Class");
+
+        builder.hashCode(100);
+
+        builder.setField("charArrayField", new char[] {1, 2, 3});
+
+        PortableObject po = builder.build();
+
+        assertEquals("class".hashCode(), po.typeId());
+        assertEquals(100, po.hashCode());
+
+        assertTrue(Arrays.equals(new char[] {1, 2, 3}, po.<char[]>field("charArrayField")));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testBooleanArrayField() throws Exception {
+        PortableBuilder builder = builder("Class");
+
+        builder.hashCode(100);
+
+        builder.setField("booleanArrayField", new boolean[] {true, false});
+
+        PortableObject po = builder.build();
+
+        assertEquals("class".hashCode(), po.typeId());
+        assertEquals(100, po.hashCode());
+
+        boolean[] arr = po.field("booleanArrayField");
+
+        assertEquals(2, arr.length);
+
+        assertTrue(arr[0]);
+        assertFalse(arr[1]);
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testDecimalArrayField() throws Exception {
+        PortableBuilder builder = builder("Class");
+
+        builder.hashCode(100);
+
+        builder.setField("decimalArrayField", new BigDecimal[] {BigDecimal.ONE, BigDecimal.TEN});
+
+        PortableObject po = builder.build();
+
+        assertEquals("class".hashCode(), po.typeId());
+        assertEquals(100, po.hashCode());
+
+        assertTrue(Arrays.equals(new BigDecimal[] {BigDecimal.ONE, BigDecimal.TEN}, po.<String[]>field("decimalArrayField")));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testStringArrayField() throws Exception {
+        PortableBuilder builder = builder("Class");
+
+        builder.hashCode(100);
+
+        builder.setField("stringArrayField", new String[] {"str1", "str2", "str3"});
+
+        PortableObject po = builder.build();
+
+        assertEquals("class".hashCode(), po.typeId());
+        assertEquals(100, po.hashCode());
+
+        assertTrue(Arrays.equals(new String[] {"str1", "str2", "str3"}, po.<String[]>field("stringArrayField")));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testUuidArrayField() throws Exception {
+        PortableBuilder builder = builder("Class");
+
+        builder.hashCode(100);
+
+        UUID[] arr = new UUID[] {UUID.randomUUID(), UUID.randomUUID()};
+
+        builder.setField("uuidArrayField", arr);
+
+        PortableObject po = builder.build();
+
+        assertEquals("class".hashCode(), po.typeId());
+        assertEquals(100, po.hashCode());
+
+        assertTrue(Arrays.equals(arr, po.<UUID[]>field("uuidArrayField")));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testObjectField() throws Exception {
+        PortableBuilder builder = builder("Class");
+
+        builder.hashCode(100);
+
+        builder.setField("objectField", new Value(1));
+
+        PortableObject po = builder.build();
+
+        assertEquals("class".hashCode(), po.typeId());
+        assertEquals(100, po.hashCode());
+
+        assertEquals(1, po.<PortableObject>field("objectField").<Value>deserialize().i);
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testObjectArrayField() throws Exception {
+        PortableBuilder builder = builder("Class");
+
+        builder.hashCode(100);
+
+        builder.setField("objectArrayField", new Value[] {new Value(1), new Value(2)});
+
+        PortableObject po = builder.build();
+
+        assertEquals("class".hashCode(), po.typeId());
+        assertEquals(100, po.hashCode());
+
+        Object[] arr = po.field("objectArrayField");
+
+        assertEquals(2, arr.length);
+
+        assertEquals(1, ((PortableObject)arr[0]).<Value>deserialize().i);
+        assertEquals(2, ((PortableObject)arr[1]).<Value>deserialize().i);
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testCollectionField() throws Exception {
+        PortableBuilder builder = builder("Class");
+
+        builder.hashCode(100);
+
+        builder.setField("collectionField", Arrays.asList(new Value(1), new Value(2)));
+
+        PortableObject po = builder.build();
+
+        assertEquals("class".hashCode(), po.typeId());
+        assertEquals(100, po.hashCode());
+
+        List<PortableObject> list = po.field("collectionField");
+
+        assertEquals(2, list.size());
+
+        assertEquals(1, list.get(0).<Value>deserialize().i);
+        assertEquals(2, list.get(1).<Value>deserialize().i);
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testMapField() throws Exception {
+        PortableBuilder builder = builder("Class");
+
+        builder.hashCode(100);
+
+        builder.setField("mapField", F.asMap(new Key(1), new Value(1), new Key(2), new Value(2)));
+
+        PortableObject po = builder.build();
+
+        assertEquals("class".hashCode(), po.typeId());
+        assertEquals(100, po.hashCode());
+
+        Map<PortableObject, PortableObject> map = po.field("mapField");
+
+        assertEquals(2, map.size());
+
+        for (Map.Entry<PortableObject, PortableObject> e : map.entrySet())
+            assertEquals(e.getKey().<Key>deserialize().i, e.getValue().<Value>deserialize().i);
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testSeveralFields() throws Exception {
+        PortableBuilder builder = builder("Class");
+
+        builder.hashCode(100);
+
+        builder.setField("i", 111);
+        builder.setField("f", 111.111f);
+        builder.setField("iArr", new int[] {1, 2, 3});
+        builder.setField("obj", new Key(1));
+        builder.setField("col", Arrays.asList(new Value(1), new Value(2)));
+
+        PortableObject po = builder.build();
+
+        assertEquals("class".hashCode(), po.typeId());
+        assertEquals(100, po.hashCode());
+
+        assertEquals(111, po.<Integer>field("i").intValue());
+        assertEquals(111.111f, po.<Float>field("f").floatValue(), 0);
+        assertTrue(Arrays.equals(new int[] {1, 2, 3}, po.<int[]>field("iArr")));
+        assertEquals(1, po.<PortableObject>field("obj").<Key>deserialize().i);
+
+        List<PortableObject> list = po.field("col");
+
+        assertEquals(2, list.size());
+
+        assertEquals(1, list.get(0).<Value>deserialize().i);
+        assertEquals(2, list.get(1).<Value>deserialize().i);
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testOffheapPortable() throws Exception {
+        PortableBuilder builder = builder("Class");
+
+        builder.hashCode(100);
+
+        builder.setField("i", 111);
+        builder.setField("f", 111.111f);
+        builder.setField("iArr", new int[] {1, 2, 3});
+        builder.setField("obj", new Key(1));
+        builder.setField("col", Arrays.asList(new Value(1), new Value(2)));
+
+        PortableObject po = builder.build();
+
+        byte[] arr = ((CacheObjectPortableProcessorImpl)(grid(0)).context().cacheObjects()).marshal(po);
+
+        long ptr = UNSAFE.allocateMemory(arr.length + 5);
+
+        try {
+            long ptr0 = ptr;
+
+            UNSAFE.putBoolean(null, ptr0++, false);
+
+            UNSAFE.putInt(ptr0, arr.length);
+
+            UNSAFE.copyMemory(arr, BYTE_ARR_OFF, null, ptr0 + 4, arr.length);
+
+            PortableObject offheapObj = (PortableObject)
+                ((CacheObjectPortableProcessorImpl)(grid(0)).context().cacheObjects()).unmarshal(ptr, false);
+
+            assertEquals(PortableObjectOffheapImpl.class, offheapObj.getClass());
+
+            assertEquals("class".hashCode(), offheapObj.typeId());
+            assertEquals(100, offheapObj.hashCode());
+
+            assertEquals(111, offheapObj.<Integer>field("i").intValue());
+            assertEquals(111.111f, offheapObj.<Float>field("f").floatValue(), 0);
+            assertTrue(Arrays.equals(new int[] {1, 2, 3}, offheapObj.<int[]>field("iArr")));
+            assertEquals(1, offheapObj.<PortableObject>field("obj").<Key>deserialize().i);
+
+            List<PortableObject> list = offheapObj.field("col");
+
+            assertEquals(2, list.size());
+
+            assertEquals(1, list.get(0).<Value>deserialize().i);
+            assertEquals(2, list.get(1).<Value>deserialize().i);
+
+            assertEquals(po, offheapObj);
+            assertEquals(offheapObj, po);
+        }
+        finally {
+            UNSAFE.freeMemory(ptr);
+        }
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testBuildAndDeserialize() throws Exception {
+        PortableBuilder builder = builder(Value.class.getName());
+
+        builder.hashCode(100);
+
+        builder.setField("i", 1);
+
+        PortableObject po = builder.build();
+
+        assertEquals("value".hashCode(), po.typeId());
+        assertEquals(100, po.hashCode());
+
+        assertEquals(1, po.<Value>deserialize().i);
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testMetaData2() throws Exception {
+        PortableBuilder builder = builder("org.test.MetaTest2");
+
+        builder.setField("objectField", "a", Object.class);
+
+        PortableObject po = builder.build();
+
+        PortableMetadata meta = po.metaData();
+
+        assertEquals("MetaTest2", meta.typeName());
+        assertEquals("Object", meta.fieldTypeName("objectField"));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testMetaData() throws Exception {
+        PortableBuilder builder = builder("org.test.MetaTest");
+
+        builder.hashCode(100);
+
+        builder.setField("intField", 1);
+        builder.setField("byteArrayField", new byte[] {1, 2, 3});
+
+        PortableObject po = builder.build();
+
+        PortableMetadata meta = po.metaData();
+
+        assertEquals("MetaTest", meta.typeName());
+
+        Collection<String> fields = meta.fields();
+
+        assertEquals(2, fields.size());
+
+        assertTrue(fields.contains("intField"));
+        assertTrue(fields.contains("byteArrayField"));
+
+        assertEquals("int", meta.fieldTypeName("intField"));
+        assertEquals("byte[]", meta.fieldTypeName("byteArrayField"));
+
+        builder = builder("org.test.MetaTest");
+
+        builder.hashCode(100);
+
+        builder.setField("intField", 2);
+        builder.setField("uuidField", UUID.randomUUID());
+
+        po = builder.build();
+
+        meta = po.metaData();
+
+        assertEquals("MetaTest", meta.typeName());
+
+        fields = meta.fields();
+
+        assertEquals(3, fields.size());
+
+        assertTrue(fields.contains("intField"));
+        assertTrue(fields.contains("byteArrayField"));
+        assertTrue(fields.contains("uuidField"));
+
+        assertEquals("int", meta.fieldTypeName("intField"));
+        assertEquals("byte[]", meta.fieldTypeName("byteArrayField"));
+        assertEquals("UUID", meta.fieldTypeName("uuidField"));
+    }
+
+    /**
+     *
+     */
+    public void testGetFromCopiedObj() {
+        PortableObject objStr = builder(TestObjectAllTypes.class.getName()).setField("str", "aaa").build();
+
+        PortableBuilderImpl builder = builder(objStr);
+        assertEquals("aaa", builder.getField("str"));
+
+        builder.setField("str", "bbb");
+        assertEquals("bbb", builder.getField("str"));
+
+        assertNull(builder.getField("i_"));
+        assertEquals("bbb", builder.build().<TestObjectAllTypes>deserialize().str);
+    }
+
+    /**
+     *
+     */
+    public void testCopyFromInnerObjects() {
+        ArrayList<Object> list = new ArrayList<>();
+        list.add(new TestObjectAllTypes());
+        list.add(list.get(0));
+
+        TestObjectContainer c = new TestObjectContainer(list);
+
+        PortableBuilderImpl builder = builder(toPortable(c));
+        builder.<List>getField("foo").add("!!!");
+
+        PortableObject res = builder.build();
+
+        TestObjectContainer deserialized = res.deserialize();
+
+        List deserializedList = (List)deserialized.foo;
+
+        assertSame(deserializedList.get(0), deserializedList.get(1));
+        assertEquals("!!!", deserializedList.get(2));
+        assertTrue(deserializedList.get(0) instanceof TestObjectAllTypes);
+    }
+
+    /**
+     *
+     */
+    public void testSetPortableObject() {
+        PortableObject portableObj = builder(TestObjectContainer.class.getName())
+            .setField("foo", toPortable(new TestObjectAllTypes()))
+            .build();
+
+        assertTrue(portableObj.<TestObjectContainer>deserialize().foo instanceof TestObjectAllTypes);
+    }
+
+    /**
+     *
+     */
+    public void testPlainPortableObjectCopyFrom() {
+        TestObjectPlainPortable obj = new TestObjectPlainPortable(toPortable(new TestObjectAllTypes()));
+
+        PortableBuilderImpl builder = builder(toPortable(obj));
+        assertTrue(builder.getField("plainPortable") instanceof PortableObject);
+
+        TestObjectPlainPortable deserialized = builder.build().deserialize();
+        assertTrue(deserialized.plainPortable instanceof PortableObject);
+    }
+
+    /**
+     *
+     */
+    public void testRemoveFromNewObject() {
+        PortableBuilder builder = builder(TestObjectAllTypes.class.getName());
+
+        builder.setField("str", "a");
+
+        builder.removeField("str");
+
+        assertNull(builder.build().<TestObjectAllTypes>deserialize().str);
+    }
+
+    /**
+     *
+     */
+    public void testRemoveFromExistingObject() {
+        TestObjectAllTypes obj = new TestObjectAllTypes();
+        obj.setDefaultData();
+        obj.enumArr = null;
+
+        PortableBuilder builder = builder(toPortable(obj));
+
+        builder.removeField("str");
+
+        assertNull(builder.build().<TestObjectAllTypes>deserialize().str);
+    }
+
+    /**
+     *
+     */
+    public void testRemoveFromExistingObjectAfterGet() {
+        TestObjectAllTypes obj = new TestObjectAllTypes();
+        obj.setDefaultData();
+        obj.enumArr = null;
+
+        PortableBuilderImpl builder = builder(toPortable(obj));
+
+        builder.getField("i_");
+
+        builder.removeField("str");
+
+        assertNull(builder.build().<TestObjectAllTypes>deserialize().str);
+    }
+
+    /**
+     * @throws IgniteCheckedException If any error occurs.
+     */
+    public void testDontBrokeCyclicDependency() throws IgniteCheckedException {
+        TestObjectOuter outer = new TestObjectOuter();
+        outer.inner = new TestObjectInner();
+        outer.inner.outer = outer;
+        outer.foo = "a";
+
+        PortableBuilder builder = builder(toPortable(outer));
+
+        builder.setField("foo", "b");
+
+        TestObjectOuter res = builder.build().deserialize();
+
+        assertEquals("b", res.foo);
+        assertSame(res, res.inner.outer);
+    }
+
+    /**
+     * @return Portables.
+     */
+    private IgnitePortables portables() {
+        return grid(0).portables();
+    }
+
+    /**
+     * @param obj Object.
+     * @return Portable object.
+     */
+    private PortableObject toPortable(Object obj) {
+        return portables().toPortable(obj);
+    }
+
+    /**
+     * @return Builder.
+     */
+    private <T> PortableBuilder builder(int typeId) {
+        return portables().builder(typeId);
+    }
+
+    /**
+     * @return Builder.
+     */
+    private <T> PortableBuilder builder(String clsName) {
+        return portables().builder(clsName);
+    }
+
+    /**
+     * @return Builder.
+     */
+    private <T> PortableBuilderImpl builder(PortableObject obj) {
+        return (PortableBuilderImpl)portables().builder(obj);
+    }
+
+    /**
+     *
+     */
+    private static class CustomIdMapper {
+        /** */
+        private String str = "a";
+
+        /** */
+        private int i = 10;
+    }
+
+    /**
+     */
+    private static class Key {
+        /** */
+        private int i;
+
+        /**
+         */
+        private Key() {
+            // No-op.
+        }
+
+        /**
+         * @param i Index.
+         */
+        private Key(int i) {
+            this.i = i;
+        }
+
+        /** {@inheritDoc} */
+        @Override public boolean equals(Object o) {
+            if (this == o)
+                return true;
+
+            if (o == null || getClass() != o.getClass())
+                return false;
+
+            Key key = (Key)o;
+
+            return i == key.i;
+        }
+
+        /** {@inheritDoc} */
+        @Override public int hashCode() {
+            return i;
+        }
+    }
+
+    /**
+     */
+    private static class Value {
+        /** */
+        private int i;
+
+        /**
+         */
+        private Value() {
+            // No-op.
+        }
+
+        /**
+         * @param i Index.
+         */
+        private Value(int i) {
+            this.i = i;
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/java/org/apache/ignite/internal/portable/GridPortableBuilderStringAsCharsAdditionalSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/portable/GridPortableBuilderStringAsCharsAdditionalSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/portable/GridPortableBuilderStringAsCharsAdditionalSelfTest.java
new file mode 100644
index 0000000..71f670d
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/portable/GridPortableBuilderStringAsCharsAdditionalSelfTest.java
@@ -0,0 +1,28 @@
+/*
+ * 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.portable;
+
+/**
+ *
+ */
+public class GridPortableBuilderStringAsCharsAdditionalSelfTest extends GridPortableBuilderAdditionalSelfTest {
+    /** {@inheritDoc} */
+    @Override protected boolean useUtf8() {
+        return false;
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/java/org/apache/ignite/internal/portable/GridPortableBuilderStringAsCharsSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/portable/GridPortableBuilderStringAsCharsSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/portable/GridPortableBuilderStringAsCharsSelfTest.java
new file mode 100644
index 0000000..4ba9dfa
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/portable/GridPortableBuilderStringAsCharsSelfTest.java
@@ -0,0 +1,28 @@
+/*
+ * 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.portable;
+
+/**
+ * Portable builder test.
+ */
+public class GridPortableBuilderStringAsCharsSelfTest extends GridPortableBuilderSelfTest {
+    /** {@inheritDoc} */
+    @Override protected boolean useUtf8() {
+        return false;
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/java/org/apache/ignite/internal/portable/GridPortableMarshallerCtxDisabledSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/portable/GridPortableMarshallerCtxDisabledSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/portable/GridPortableMarshallerCtxDisabledSelfTest.java
new file mode 100644
index 0000000..0cb6197
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/portable/GridPortableMarshallerCtxDisabledSelfTest.java
@@ -0,0 +1,128 @@
+/*
+ * 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.portable;
+
+import org.apache.ignite.*;
+import org.apache.ignite.internal.*;
+import org.apache.ignite.internal.util.*;
+import org.apache.ignite.marshaller.portable.*;
+import org.apache.ignite.portable.*;
+import org.apache.ignite.testframework.junits.common.*;
+
+/**
+ *
+ */
+public class GridPortableMarshallerCtxDisabledSelfTest extends GridCommonAbstractTest {
+    /** */
+    protected static final PortableMetaDataHandler META_HND = new PortableMetaDataHandler() {
+        @Override public void addMeta(int typeId, PortableMetadata meta) {
+            // No-op.
+        }
+
+        @Override public PortableMetadata metadata(int typeId) {
+            return null;
+        }
+    };
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testObjectExchange() throws Exception {
+        PortableMarshaller marsh = new PortableMarshaller();
+        marsh.setContext(new MarshallerContextWithNoStorage());
+
+        PortableContext context = new PortableContext(META_HND, null);
+
+        IgniteUtils.invoke(PortableMarshaller.class, marsh, "setPortableContext", context);
+
+        SimpleObject obj0 = new SimpleObject();
+
+        obj0.b = 2;
+        obj0.bArr = new byte[] {2, 3, 4, 5, 5};
+        obj0.c = 'A';
+        obj0.enumVal = TestEnum.D;
+        obj0.objArr = new Object[] {"hello", "world", "from", "me"};
+        obj0.enumArr = new TestEnum[] {TestEnum.C, TestEnum.B};
+
+        byte[] arr = marsh.marshal(obj0);
+
+        SimpleObject obj2 = marsh.unmarshal(arr, null);
+
+        assertEquals(obj0.b, obj2.b);
+        assertEquals(obj0.c, obj2.c);
+        assertEquals(obj0.enumVal, obj2.enumVal);
+
+        for (int i = 0; i < obj0.bArr.length; i++)
+            assertEquals(obj0.bArr[i], obj2.bArr[i]);
+
+        for (int i = 0; i < obj0.objArr.length; i++)
+            assertEquals(obj0.objArr[i], obj2.objArr[i]);
+
+        for (int i = 0; i < obj0.enumArr.length; i++)
+            assertEquals(obj0.enumArr[i], obj2.enumArr[i]);
+    }
+
+    /**
+     * Marshaller context with no storage. Platform has to work in such environment as well by marshalling class name
+     * of a portable object.
+     */
+    private static class MarshallerContextWithNoStorage extends MarshallerContextAdapter {
+        /** */
+        public MarshallerContextWithNoStorage() {
+            super(null);
+        }
+
+        /** {@inheritDoc} */
+        @Override protected boolean registerClassName(int id, String clsName) throws IgniteCheckedException {
+            return false;
+        }
+
+        /** {@inheritDoc} */
+        @Override protected String className(int id) throws IgniteCheckedException {
+            return null;
+        }
+    }
+
+    /**
+     */
+    private enum TestEnum {
+        A, B, C, D, E
+    }
+
+    /**
+     */
+    private static class SimpleObject {
+        /** */
+        private byte b;
+
+        /** */
+        private char c;
+
+        /** */
+        private byte[] bArr;
+
+        /** */
+        private Object[] objArr;
+
+        /** */
+        private TestEnum enumVal;
+
+        /** */
+        private TestEnum[] enumArr;
+    }
+}


[11/59] [abbrv] ignite git commit: ignite-1258: portable objects API support in Ignite

Posted by vk...@apache.org.
http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableObjectEx.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableObjectEx.java b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableObjectEx.java
new file mode 100644
index 0000000..270ba9f
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableObjectEx.java
@@ -0,0 +1,213 @@
+/*
+ * 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.portable;
+
+import org.apache.ignite.*;
+import org.apache.ignite.internal.util.offheap.unsafe.*;
+import org.apache.ignite.internal.util.typedef.internal.*;
+import org.apache.ignite.portable.*;
+
+import org.jetbrains.annotations.*;
+
+import java.math.*;
+import java.util.*;
+
+/**
+ * Internal portable object interface.
+ */
+public abstract class PortableObjectEx implements PortableObject {
+    /**
+     * @return Length.
+     */
+    public abstract int length();
+
+    /**
+     * @return Object start.
+     */
+    public abstract int start();
+
+    /**
+     * @return {@code True} if object is array based.
+     */
+    protected abstract boolean hasArray();
+
+    /**
+     * @return Object array if object is array based, otherwise {@code null}.
+     */
+    public abstract byte[] array();
+
+    /**
+     * @return Object offheap address is object is offheap based, otherwise 0.
+     */
+    public abstract long offheapAddress();
+
+    /**
+     * @param ctx Reader context.
+     * @param fieldName Field name.
+     * @return Field name.
+     */
+    @Nullable protected abstract <F> F field(PortableReaderContext ctx, String fieldName);
+
+    /** {@inheritDoc} */
+    @Override public PortableObject clone() throws CloneNotSupportedException {
+        return (PortableObject)super.clone();
+    }
+
+    /** {@inheritDoc} */
+    public boolean equals(Object other) {
+        if (other == this)
+            return true;
+
+        if (other == null)
+            return false;
+
+        if (!(other instanceof PortableObjectEx))
+            return false;
+
+        PortableObjectEx otherPo = (PortableObjectEx)other;
+
+        if (length() != otherPo.length() || typeId() != otherPo.typeId())
+            return false;
+
+        if (hasArray()) {
+            if (otherPo.hasArray()) {
+                int len = length();
+                int end = start() + len;
+
+                byte[] arr = array();
+                byte[] otherArr = otherPo.array();
+
+                for (int i = start(), j = otherPo.start(); i < end; i++, j++) {
+                    if (arr[i] != otherArr[j])
+                        return false;
+                }
+
+                return true;
+            }
+            else {
+                assert otherPo.offheapAddress() > 0;
+
+                return GridUnsafeMemory.compare(otherPo.offheapAddress() + otherPo.start(), array());
+            }
+        }
+        else {
+            assert offheapAddress() > 0;
+
+            if (otherPo.hasArray())
+                return GridUnsafeMemory.compare(offheapAddress() + start(), otherPo.array());
+            else {
+                assert otherPo.offheapAddress() > 0;
+
+                return GridUnsafeMemory.compare(offheapAddress() + start(),
+                    otherPo.offheapAddress() + otherPo.start(),
+                    length());
+            }
+        }
+    }
+
+    /**
+     * @param ctx Reader context.
+     * @param handles Handles for already traversed objects.
+     * @return String representation.
+     */
+    private String toString(PortableReaderContext ctx, IdentityHashMap<PortableObject, Integer> handles) {
+        int idHash = System.identityHashCode(this);
+
+        PortableMetadata meta;
+
+        try {
+            meta = metaData();
+        }
+        catch (PortableException ignore) {
+            meta = null;
+        }
+
+        if (meta == null)
+            return "PortableObject [hash=" + idHash + ", typeId=" + typeId() + ']';
+
+        handles.put(this, idHash);
+
+        SB buf = new SB(meta.typeName());
+
+        if (meta.fields() != null) {
+            buf.a(" [hash=").a(idHash);
+
+            for (String name : meta.fields()) {
+                Object val = field(ctx, name);
+
+                buf.a(", ").a(name).a('=');
+
+                if (val instanceof byte[])
+                    buf.a(Arrays.toString((byte[]) val));
+                else if (val instanceof short[])
+                    buf.a(Arrays.toString((short[])val));
+                else if (val instanceof int[])
+                    buf.a(Arrays.toString((int[])val));
+                else if (val instanceof long[])
+                    buf.a(Arrays.toString((long[])val));
+                else if (val instanceof float[])
+                    buf.a(Arrays.toString((float[])val));
+                else if (val instanceof double[])
+                    buf.a(Arrays.toString((double[])val));
+                else if (val instanceof char[])
+                    buf.a(Arrays.toString((char[])val));
+                else if (val instanceof boolean[])
+                    buf.a(Arrays.toString((boolean[]) val));
+                else if (val instanceof BigDecimal[])
+                    buf.a(Arrays.toString((BigDecimal[])val));
+                else {
+                    if (val instanceof PortableObjectEx) {
+                        PortableObjectEx po = (PortableObjectEx)val;
+
+                        Integer idHash0 = handles.get(val);
+
+                        if (idHash0 != null) {  // Circular reference.
+                            PortableMetadata meta0 = po.metaData();
+
+                            assert meta0 != null;
+
+                            buf.a(meta0.typeName()).a(" [hash=").a(idHash0).a(", ...]");
+                        }
+                        else
+                            buf.a(po.toString(ctx, handles));
+                    }
+                    else
+                        buf.a(val);
+                }
+            }
+
+            buf.a(']');
+        }
+
+        return buf.toString();
+    }
+
+    /** {@inheritDoc} */
+    @Override public String toString() {
+        try {
+            PortableReaderContext ctx = new PortableReaderContext();
+
+            ctx.setPortableHandler(start(), this);
+
+            return toString(ctx, new IdentityHashMap<PortableObject, Integer>());
+        }
+        catch (PortableException e) {
+            throw new IgniteException("Failed to create string representation of portable object.", e);
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableObjectImpl.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableObjectImpl.java b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableObjectImpl.java
new file mode 100644
index 0000000..f3dfd50
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableObjectImpl.java
@@ -0,0 +1,383 @@
+/*
+ * 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.portable;
+
+import org.apache.ignite.*;
+import org.apache.ignite.internal.*;
+import org.apache.ignite.internal.portable.streams.*;
+import org.apache.ignite.internal.processors.cache.*;
+import org.apache.ignite.internal.processors.cache.portable.*;
+import org.apache.ignite.internal.util.typedef.internal.*;
+import org.apache.ignite.plugin.extensions.communication.*;
+import org.apache.ignite.portable.*;
+
+import org.jetbrains.annotations.*;
+
+import java.io.*;
+import java.nio.*;
+
+/**
+ * Portable object implementation.
+ */
+@IgniteCodeGeneratingFail // Fields arr and start should not be generated by MessageCodeGenerator.
+public final class PortableObjectImpl extends PortableObjectEx implements Externalizable,
+    Message, CacheObject, KeyCacheObject {
+    /** */
+    public static final byte TYPE_PORTABLE = 100;
+
+    /** */
+    private static final long serialVersionUID = 0L;
+
+    /** */
+    private static final PortablePrimitives PRIM = PortablePrimitives.get();
+
+    /** */
+    @GridDirectTransient
+    private PortableContext ctx;
+
+    /** */
+    private byte[] arr;
+
+    /** */
+    private int start;
+
+    /** */
+    @GridDirectTransient
+    private Object obj;
+
+    /** */
+    @GridDirectTransient
+    private boolean detachAllowed;
+
+    /**
+     * For {@link Externalizable}.
+     */
+    public PortableObjectImpl() {
+        // No-op.
+    }
+
+    /**
+     * @param ctx Context.
+     * @param arr Array.
+     * @param start Start.
+     */
+    public PortableObjectImpl(PortableContext ctx, byte[] arr, int start) {
+        assert ctx != null;
+        assert arr != null;
+
+        this.ctx = ctx;
+        this.arr = arr;
+        this.start = start;
+    }
+
+    /** {@inheritDoc} */
+    @Override public byte type() {
+        return TYPE_PORTABLE;
+    }
+
+    /** {@inheritDoc} */
+    @Override public boolean internal() {
+        return false;
+    }
+
+    /** {@inheritDoc} */
+    @SuppressWarnings("unchecked")
+    @Nullable @Override public <T> T value(CacheObjectContext ctx, boolean cpy) {
+        return (T)this;
+    }
+
+    /** {@inheritDoc} */
+    @Override public byte[] valueBytes(CacheObjectContext ctx) throws IgniteCheckedException {
+        if (detached())
+            return array();
+
+        int len = length();
+
+        byte[] arr0 = new byte[len];
+
+        U.arrayCopy(arr, start, arr0, 0, len);
+
+        return arr0;
+    }
+
+    /** {@inheritDoc} */
+    @Override public CacheObject prepareForCache(CacheObjectContext ctx) {
+        if (detached())
+            return this;
+
+        return (PortableObjectImpl)detach();
+    }
+
+    /** {@inheritDoc} */
+    @Override public void finishUnmarshal(CacheObjectContext ctx, ClassLoader ldr) throws IgniteCheckedException {
+        this.ctx = ((CacheObjectPortableProcessorImpl)ctx.processor()).portableContext();
+    }
+
+    /** {@inheritDoc} */
+    @Override public void prepareMarshal(CacheObjectContext ctx) throws IgniteCheckedException {
+        // No-op.
+    }
+
+    /** {@inheritDoc} */
+    @Override public int length() {
+        return PRIM.readInt(arr, start + GridPortableMarshaller.TOTAL_LEN_POS);
+    }
+
+    /**
+     * @return Detached portable object.
+     */
+    public PortableObject detach() {
+        if (!detachAllowed || detached())
+            return this;
+
+        int len = length();
+
+        byte[] arr0 = new byte[len];
+
+        U.arrayCopy(arr, start, arr0, 0, len);
+
+        return new PortableObjectImpl(ctx, arr0, 0);
+    }
+
+    /**
+     * @return Detached or not.
+     */
+    public boolean detached() {
+        return start == 0 && length() == arr.length;
+    }
+
+    /**
+     * @return {@code True} if detach is allowed.
+     */
+    public boolean detachAllowed() {
+        return true;
+    }
+
+    /**
+     * @param detachAllowed Detach allowed flag.
+     */
+    public void detachAllowed(boolean detachAllowed) {
+        this.detachAllowed = detachAllowed;
+    }
+
+    /**
+     * @return Context.
+     */
+    public PortableContext context() {
+        return ctx;
+    }
+
+    /**
+     * @param ctx Context.
+     */
+    public void context(PortableContext ctx) {
+        this.ctx = ctx;
+    }
+
+    /** {@inheritDoc} */
+    @Override public byte[] array() {
+        return arr;
+    }
+
+    /** {@inheritDoc} */
+    @Override public int start() {
+        return start;
+    }
+
+    /** {@inheritDoc} */
+    @Override public long offheapAddress() {
+        return 0;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected boolean hasArray() {
+        return true;
+    }
+
+    /** {@inheritDoc} */
+    @Override public int typeId() {
+        return PRIM.readInt(arr, start + 2);
+    }
+
+    /** {@inheritDoc} */
+    @Nullable @Override public PortableMetadata metaData() throws PortableException {
+        if (ctx == null)
+            throw new PortableException("PortableContext is not set for the object.");
+
+        return ctx.metaData(typeId());
+    }
+
+    /** {@inheritDoc} */
+    @SuppressWarnings("unchecked")
+    @Nullable @Override public <F> F field(String fieldName) throws PortableException {
+        PortableReaderExImpl reader = new PortableReaderExImpl(ctx, arr, start, null);
+
+        return (F)reader.unmarshal(fieldName);
+    }
+
+    /** {@inheritDoc} */
+    @SuppressWarnings("unchecked")
+    @Nullable @Override protected <F> F field(PortableReaderContext rCtx, String fieldName) {
+        PortableReaderExImpl reader = new PortableReaderExImpl(ctx,
+            new PortableHeapInputStream(arr),
+            start,
+            null,
+            rCtx);
+
+        return (F)reader.unmarshal(fieldName);
+    }
+
+    /** {@inheritDoc} */
+    @Override public boolean hasField(String fieldName) {
+        PortableReaderExImpl reader = new PortableReaderExImpl(ctx, arr, start, null);
+
+        return reader.hasField(fieldName);
+    }
+
+    /** {@inheritDoc} */
+    @SuppressWarnings("unchecked")
+    @Nullable @Override public <T> T deserialize() throws PortableException {
+        Object obj0 = obj;
+
+        if (obj0 == null) {
+            // TODO: IGNITE-1272 - Deserialize with proper class loader.
+            PortableReaderExImpl reader = new PortableReaderExImpl(ctx, arr, start, null);
+
+            obj0 = reader.deserialize();
+
+            PortableClassDescriptor desc = reader.descriptor();
+
+            assert desc != null;
+
+            if (desc.keepDeserialized())
+                obj = obj0;
+        }
+
+        return (T)obj0;
+    }
+
+    /** {@inheritDoc} */
+    @Override public PortableObject clone() throws CloneNotSupportedException {
+        return super.clone();
+    }
+
+    /** {@inheritDoc} */
+    @Override public int hashCode() {
+        return PRIM.readInt(arr, start + 6);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeExternal(ObjectOutput out) throws IOException {
+        out.writeObject(ctx);
+
+        if (detachAllowed) {
+            int len = length();
+
+            out.writeInt(len);
+            out.write(arr, start, len);
+            out.writeInt(0);
+        }
+        else {
+            out.writeInt(arr.length);
+            out.write(arr);
+            out.writeInt(start);
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
+        ctx = (PortableContext)in.readObject();
+
+        arr = new byte[in.readInt()];
+
+        in.readFully(arr);
+
+        start = in.readInt();
+    }
+
+    /** {@inheritDoc} */
+    @Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) {
+        writer.setBuffer(buf);
+
+        if (!writer.isHeaderWritten()) {
+            if (!writer.writeHeader(directType(), fieldsCount()))
+                return false;
+
+            writer.onHeaderWritten();
+        }
+
+        switch (writer.state()) {
+            case 0:
+                if (!writer.writeByteArray("arr",
+                    arr,
+                    detachAllowed ? start : 0,
+                    detachAllowed ? length() : arr.length))
+                    return false;
+
+                writer.incrementState();
+
+            case 1:
+                if (!writer.writeInt("start", detachAllowed ? 0 : start))
+                    return false;
+
+                writer.incrementState();
+
+        }
+
+        return true;
+    }
+
+    /** {@inheritDoc} */
+    @Override public boolean readFrom(ByteBuffer buf, MessageReader reader) {
+        reader.setBuffer(buf);
+
+        if (!reader.beforeMessageRead())
+            return false;
+
+        switch (reader.state()) {
+            case 0:
+                arr = reader.readByteArray("arr");
+
+                if (!reader.isLastRead())
+                    return false;
+
+                reader.incrementState();
+
+            case 1:
+                start = reader.readInt("start");
+
+                if (!reader.isLastRead())
+                    return false;
+
+                reader.incrementState();
+
+        }
+
+        return true;
+    }
+
+    /** {@inheritDoc} */
+    @Override public byte directType() {
+        return 113;
+    }
+
+    /** {@inheritDoc} */
+    @Override public byte fieldsCount() {
+        return 3;
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableObjectOffheapImpl.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableObjectOffheapImpl.java b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableObjectOffheapImpl.java
new file mode 100644
index 0000000..40655ba
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableObjectOffheapImpl.java
@@ -0,0 +1,238 @@
+/*
+ * 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.portable;
+
+import org.apache.ignite.*;
+import org.apache.ignite.internal.portable.streams.*;
+import org.apache.ignite.internal.processors.cache.*;
+import org.apache.ignite.internal.util.*;
+import org.apache.ignite.internal.util.typedef.internal.*;
+import org.apache.ignite.plugin.extensions.communication.*;
+import org.apache.ignite.portable.*;
+
+import org.jetbrains.annotations.*;
+import sun.misc.*;
+
+import java.io.*;
+import java.nio.*;
+
+/**
+ *  Portable object implementation over offheap memory
+ */
+public class PortableObjectOffheapImpl extends PortableObjectEx implements Externalizable, CacheObject {
+    /** */
+    private static final long serialVersionUID = 0L;
+
+    /** */
+    private static final Unsafe UNSAFE = GridUnsafe.unsafe();
+
+    /** */
+    private final PortableContext ctx;
+
+    /** */
+    private final long ptr;
+
+    /** */
+    private final int start;
+
+    /** */
+    private final int size;
+
+    /**
+     * For {@link Externalizable} (not supported).
+     */
+    public PortableObjectOffheapImpl() {
+        throw new UnsupportedOperationException();
+    }
+
+    /**
+     * @param ctx Context.
+     * @param ptr Memory address.
+     * @param start Object start.
+     * @param size Memory size.
+     */
+    public PortableObjectOffheapImpl(PortableContext ctx, long ptr, int start, int size) {
+        this.ctx = ctx;
+        this.ptr = ptr;
+        this.start = start;
+        this.size = size;
+    }
+
+    /**
+     * @return Heap-based copy.
+     */
+    public PortableObject heapCopy() {
+        return new PortableObjectImpl(ctx, U.copyMemory(ptr, size), start);
+    }
+
+    /** {@inheritDoc} */
+    @Override public int typeId() {
+        return UNSAFE.getInt(ptr + start + 2);
+    }
+
+    /** {@inheritDoc} */
+    @Override public int length() {
+        return UNSAFE.getInt(ptr + start + GridPortableMarshaller.TOTAL_LEN_POS);
+    }
+
+    /** {@inheritDoc} */
+    @Override public int hashCode() {
+        return UNSAFE.getInt(ptr + start + 6);
+    }
+
+    /** {@inheritDoc} */
+    @Override public int start() {
+        return start;
+    }
+
+    /** {@inheritDoc} */
+    @Override public byte[] array() {
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public long offheapAddress() {
+        return ptr;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected boolean hasArray() {
+        return false;
+    }
+
+    /** {@inheritDoc} */
+    @Nullable @Override public PortableMetadata metaData() throws PortableException {
+        if (ctx == null)
+            throw new PortableException("PortableContext is not set for the object.");
+
+        return ctx.metaData(typeId());
+    }
+
+    /** {@inheritDoc} */
+    @SuppressWarnings("unchecked")
+    @Nullable @Override public <F> F field(String fieldName) throws PortableException {
+        PortableReaderExImpl reader = new PortableReaderExImpl(ctx,
+            new PortableOffheapInputStream(ptr, size, false),
+            start,
+            null);
+
+        return (F)reader.unmarshal(fieldName);
+    }
+
+    /** {@inheritDoc} */
+    @SuppressWarnings("unchecked")
+    @Nullable @Override protected <F> F field(PortableReaderContext rCtx, String fieldName) {
+        PortableReaderExImpl reader = new PortableReaderExImpl(ctx,
+            new PortableOffheapInputStream(ptr, size, false),
+            start,
+            null,
+            rCtx);
+
+        return (F)reader.unmarshal(fieldName);
+    }
+
+    /** {@inheritDoc} */
+    @Override public boolean hasField(String fieldName) {
+        PortableReaderExImpl reader = new PortableReaderExImpl(ctx,
+            new PortableOffheapInputStream(ptr, size, false),
+            start,
+            null);
+
+        return reader.hasField(fieldName);
+    }
+
+    /** {@inheritDoc} */
+    @SuppressWarnings("unchecked")
+    @Nullable @Override public <T> T deserialize() throws PortableException {
+        // TODO: IGNITE-1272 - Deserialize with proper class loader.
+        PortableReaderExImpl reader = new PortableReaderExImpl(
+            ctx,
+            new PortableOffheapInputStream(ptr, size, false),
+            start,
+            null);
+
+        return (T)reader.deserialize();
+    }
+
+    /** {@inheritDoc} */
+    @SuppressWarnings("CloneDoesntCallSuperClone")
+    @Override public PortableObject clone() throws CloneNotSupportedException {
+        return heapCopy();
+    }
+
+    /** {@inheritDoc} */
+    @Override public byte type() {
+        throw new UnsupportedOperationException();
+    }
+
+    /** {@inheritDoc} */
+    @SuppressWarnings("unchecked")
+    @Nullable @Override public <T> T value(CacheObjectContext ctx, boolean cpy) {
+        return (T)this;
+    }
+
+    /** {@inheritDoc} */
+    @Override public byte[] valueBytes(CacheObjectContext ctx) throws IgniteCheckedException {
+        throw new UnsupportedOperationException();
+    }
+
+    /** {@inheritDoc} */
+    @Override public CacheObject prepareForCache(CacheObjectContext ctx) {
+        throw new UnsupportedOperationException();
+    }
+
+    /** {@inheritDoc} */
+    @Override public void finishUnmarshal(CacheObjectContext ctx, ClassLoader ldr) throws IgniteCheckedException {
+        throw new UnsupportedOperationException();
+    }
+
+    /** {@inheritDoc} */
+    @Override public void prepareMarshal(CacheObjectContext ctx) throws IgniteCheckedException {
+        throw new UnsupportedOperationException();
+    }
+
+    /** {@inheritDoc} */
+    @Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) {
+        throw new UnsupportedOperationException();
+    }
+
+    /** {@inheritDoc} */
+    @Override public boolean readFrom(ByteBuffer buf, MessageReader reader) {
+        throw new UnsupportedOperationException();
+    }
+
+    /** {@inheritDoc} */
+    @Override public byte directType() {
+        throw new UnsupportedOperationException();
+    }
+
+    /** {@inheritDoc} */
+    @Override public byte fieldsCount() {
+        throw new UnsupportedOperationException();
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeExternal(ObjectOutput out) throws IOException {
+        throw new UnsupportedOperationException(); // To make sure it is not marshalled.
+    }
+
+    /** {@inheritDoc} */
+    @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
+        throw new UnsupportedOperationException(); // To make sure it is not marshalled.
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/internal/portable/PortablePlainLazyValue.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/portable/PortablePlainLazyValue.java b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortablePlainLazyValue.java
new file mode 100644
index 0000000..73cc19e
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortablePlainLazyValue.java
@@ -0,0 +1,47 @@
+/*
+ * 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.portable;
+
+/**
+ *
+ */
+class PortablePlainLazyValue extends PortableAbstractLazyValue {
+    /** */
+    protected final int len;
+
+    /**
+     * @param reader Reader
+     * @param valOff Offset
+     * @param len Length.
+     */
+    protected PortablePlainLazyValue(PortableBuilderReader reader, int valOff, int len) {
+        super(reader, valOff);
+
+        this.len = len;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected Object init() {
+        return reader.reader().unmarshal(valOff);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeTo(PortableWriterExImpl writer, PortableBuilderSerializer ctx) {
+        writer.write(reader.array(), valOff, len);
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/internal/portable/PortablePlainPortableObject.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/portable/PortablePlainPortableObject.java b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortablePlainPortableObject.java
new file mode 100644
index 0000000..1679303
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortablePlainPortableObject.java
@@ -0,0 +1,50 @@
+/*
+ * 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.portable;
+
+import org.apache.ignite.portable.*;
+
+/**
+ *
+ */
+public class PortablePlainPortableObject implements PortableLazyValue {
+    /** */
+    private final PortableObject portableObj;
+
+    /**
+     * @param portableObj Portable object.
+     */
+    public PortablePlainPortableObject(PortableObject portableObj) {
+        this.portableObj = portableObj;
+    }
+
+    /** {@inheritDoc} */
+    @Override public Object value() {
+        return portableObj;
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeTo(PortableWriterExImpl writer, PortableBuilderSerializer ctx) {
+        PortableObject val = portableObj;
+
+        if (val instanceof PortableObjectOffheapImpl)
+            val = ((PortableObjectOffheapImpl)val).heapCopy();
+
+        writer.doWritePortableObject((PortableObjectImpl)val);
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/internal/portable/PortablePrimitives.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/portable/PortablePrimitives.java b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortablePrimitives.java
new file mode 100644
index 0000000..10f3479
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortablePrimitives.java
@@ -0,0 +1,773 @@
+/*
+ * 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.portable;
+
+import org.apache.ignite.internal.util.*;
+
+import sun.misc.*;
+
+import static java.nio.ByteOrder.*;
+
+/**
+ * Primitives writer.
+ */
+abstract class PortablePrimitives {
+    /** */
+    private static final PortablePrimitives INSTANCE =
+        nativeOrder() == LITTLE_ENDIAN ? new UnsafePrimitives() : new BytePrimitives();
+
+    /**
+     * @return Primitives writer.
+     */
+    static PortablePrimitives get() {
+        return INSTANCE;
+    }
+
+    /**
+     * @param arr Array.
+     * @param off Offset.
+     * @param val Value.
+     */
+    abstract void writeByte(byte[] arr, int off, byte val);
+
+    /**
+     * @param arr Array.
+     * @param off Offset.
+     * @return Value.
+     */
+    abstract byte readByte(byte[] arr, int off);
+
+    /**
+     * @param arr Array.
+     * @param off Offset.
+     * @param val Value.
+     */
+    abstract void writeShort(byte[] arr, int off, short val);
+
+    /**
+     * @param arr Array.
+     * @param off Offset.
+     * @return Value.
+     */
+    abstract short readShort(byte[] arr, int off);
+
+    /**
+     * @param arr Array.
+     * @param off Offset.
+     * @param val Value.
+     */
+    abstract void writeInt(byte[] arr, int off, int val);
+
+    /**
+     * @param arr Array.
+     * @param off Offset.
+     * @return Value.
+     */
+    abstract int readInt(byte[] arr, int off);
+
+    /**
+     * @param arr Array.
+     * @param off Offset.
+     * @param val Value.
+     */
+    abstract void writeLong(byte[] arr, int off, long val);
+
+    /**
+     * @param arr Array.
+     * @param off Offset.
+     * @return Value.
+     */
+    abstract long readLong(byte[] arr, int off);
+
+    /**
+     * @param arr Array.
+     * @param off Offset.
+     * @param val Value.
+     */
+    abstract void writeFloat(byte[] arr, int off, float val);
+
+    /**
+     * @param arr Array.
+     * @param off Offset.
+     * @return Value.
+     */
+    abstract float readFloat(byte[] arr, int off);
+
+    /**
+     * @param arr Array.
+     * @param off Offset.
+     * @param val Value.
+     */
+    abstract void writeDouble(byte[] arr, int off, double val);
+
+    /**
+     * @param arr Array.
+     * @param off Offset.
+     * @return Value.
+     */
+    abstract double readDouble(byte[] arr, int off);
+
+    /**
+     * @param arr Array.
+     * @param off Offset.
+     * @param val Value.
+     */
+    abstract void writeChar(byte[] arr, int off, char val);
+
+    /**
+     * @param arr Array.
+     * @param off Offset.
+     * @return Value.
+     */
+    abstract char readChar(byte[] arr, int off);
+
+    /**
+     * @param arr Array.
+     * @param off Offset.
+     * @param val Value.
+     */
+    abstract void writeBoolean(byte[] arr, int off, boolean val);
+
+    /**
+     * @param arr Array.
+     * @param off Offset.
+     * @return Value.
+     */
+    abstract boolean readBoolean(byte[] arr, int off);
+
+    /**
+     * @param arr Array.
+     * @param off Offset.
+     * @param val Value.
+     */
+    abstract void writeByteArray(byte[] arr, int off, byte[] val);
+
+    /**
+     * @param arr Array.
+     * @param off Offset.
+     * @return Value.
+     */
+    abstract byte[] readByteArray(byte[] arr, int off, int len);
+
+    /**
+     * @param arr Array.
+     * @param off Offset.
+     * @param val Value.
+     */
+    abstract void writeShortArray(byte[] arr, int off, short[] val);
+
+    /**
+     * @param arr Array.
+     * @param off Offset.
+     * @return Value.
+     */
+    abstract short[] readShortArray(byte[] arr, int off, int len);
+
+    /**
+     * @param arr Array.
+     * @param off Offset.
+     * @param val Value.
+     */
+    abstract void writeIntArray(byte[] arr, int off, int[] val);
+
+    /**
+     * @param arr Array.
+     * @param off Offset.
+     * @return Value.
+     */
+    abstract int[] readIntArray(byte[] arr, int off, int len);
+
+    /**
+     * @param arr Array.
+     * @param off Offset.
+     * @param val Value.
+     */
+    abstract void writeLongArray(byte[] arr, int off, long[] val);
+
+    /**
+     * @param arr Array.
+     * @param off Offset.
+     * @return Value.
+     */
+    abstract long[] readLongArray(byte[] arr, int off, int len);
+
+    /**
+     * @param arr Array.
+     * @param off Offset.
+     * @param val Value.
+     */
+    abstract void writeFloatArray(byte[] arr, int off, float[] val);
+
+    /**
+     * @param arr Array.
+     * @param off Offset.
+     * @return Value.
+     */
+    abstract float[] readFloatArray(byte[] arr, int off, int len);
+
+    /**
+     * @param arr Array.
+     * @param off Offset.
+     * @param val Value.
+     */
+    abstract void writeDoubleArray(byte[] arr, int off, double[] val);
+
+    /**
+     * @param arr Array.
+     * @param off Offset.
+     * @return Value.
+     */
+    abstract double[] readDoubleArray(byte[] arr, int off, int len);
+
+    /**
+     * @param arr Array.
+     * @param off Offset.
+     * @param val Value.
+     */
+    abstract void writeCharArray(byte[] arr, int off, char[] val);
+
+    /**
+     * @param arr Array.
+     * @param off Offset.
+     * @return Value.
+     */
+    abstract char[] readCharArray(byte[] arr, int off, int len);
+
+    /**
+     * @param arr Array.
+     * @param off Offset.
+     * @param val Value.
+     */
+    abstract void writeBooleanArray(byte[] arr, int off, boolean[] val);
+
+    /**
+     * @param arr Array.
+     * @param off Offset.
+     * @return Value.
+     */
+    abstract boolean[] readBooleanArray(byte[] arr, int off, int len);
+
+    /** */
+    private static class UnsafePrimitives extends PortablePrimitives {
+        /** */
+        private static final Unsafe UNSAFE = GridUnsafe.unsafe();
+
+        /** */
+        private static final long BYTE_ARR_OFF = UNSAFE.arrayBaseOffset(byte[].class);
+
+        /** */
+        private static final long SHORT_ARR_OFF = UNSAFE.arrayBaseOffset(short[].class);
+
+        /** */
+        private static final long INT_ARR_OFF = UNSAFE.arrayBaseOffset(int[].class);
+
+        /** */
+        private static final long LONG_ARR_OFF = UNSAFE.arrayBaseOffset(long[].class);
+
+        /** */
+        private static final long FLOAT_ARR_OFF = UNSAFE.arrayBaseOffset(float[].class);
+
+        /** */
+        private static final long DOUBLE_ARR_OFF = UNSAFE.arrayBaseOffset(double[].class);
+
+        /** */
+        private static final long CHAR_ARR_OFF = UNSAFE.arrayBaseOffset(char[].class);
+
+        /** */
+        private static final long BOOLEAN_ARR_OFF = UNSAFE.arrayBaseOffset(boolean[].class);
+
+        /** {@inheritDoc} */
+        @Override void writeByte(byte[] arr, int off, byte val) {
+            UNSAFE.putByte(arr, BYTE_ARR_OFF + off, val);
+        }
+
+        /** {@inheritDoc} */
+        @Override byte readByte(byte[] arr, int off) {
+            return UNSAFE.getByte(arr, BYTE_ARR_OFF + off);
+        }
+
+        /** {@inheritDoc} */
+        @Override void writeShort(byte[] arr, int off, short val) {
+            UNSAFE.putShort(arr, BYTE_ARR_OFF + off, val);
+        }
+
+        /** {@inheritDoc} */
+        @Override short readShort(byte[] arr, int off) {
+            return UNSAFE.getShort(arr, BYTE_ARR_OFF + off);
+        }
+
+        /** {@inheritDoc} */
+        @Override void writeInt(byte[] arr, int off, int val) {
+            UNSAFE.putInt(arr, BYTE_ARR_OFF + off, val);
+        }
+
+        /** {@inheritDoc} */
+        @Override int readInt(byte[] arr, int off) {
+            return UNSAFE.getInt(arr, BYTE_ARR_OFF + off);
+        }
+
+        /** {@inheritDoc} */
+        @Override void writeLong(byte[] arr, int off, long val) {
+            UNSAFE.putLong(arr, BYTE_ARR_OFF + off, val);
+        }
+
+        /** {@inheritDoc} */
+        @Override long readLong(byte[] arr, int off) {
+            return UNSAFE.getLong(arr, BYTE_ARR_OFF + off);
+        }
+
+        /** {@inheritDoc} */
+        @Override void writeFloat(byte[] arr, int off, float val) {
+            UNSAFE.putFloat(arr, BYTE_ARR_OFF + off, val);
+        }
+
+        /** {@inheritDoc} */
+        @Override float readFloat(byte[] arr, int off) {
+            return UNSAFE.getFloat(arr, BYTE_ARR_OFF + off);
+        }
+
+        /** {@inheritDoc} */
+        @Override void writeDouble(byte[] arr, int off, double val) {
+            UNSAFE.putDouble(arr, BYTE_ARR_OFF + off, val);
+        }
+
+        /** {@inheritDoc} */
+        @Override double readDouble(byte[] arr, int off) {
+            return UNSAFE.getDouble(arr, BYTE_ARR_OFF + off);
+        }
+
+        /** {@inheritDoc} */
+        @Override void writeChar(byte[] arr, int off, char val) {
+            UNSAFE.putChar(arr, BYTE_ARR_OFF + off, val);
+        }
+
+        /** {@inheritDoc} */
+        @Override char readChar(byte[] arr, int off) {
+            return UNSAFE.getChar(arr, BYTE_ARR_OFF + off);
+        }
+
+        /** {@inheritDoc} */
+        @Override void writeBoolean(byte[] arr, int off, boolean val) {
+            UNSAFE.putBoolean(arr, BYTE_ARR_OFF + off, val);
+        }
+
+        /** {@inheritDoc} */
+        @Override boolean readBoolean(byte[] arr, int off) {
+            return UNSAFE.getBoolean(arr, BYTE_ARR_OFF + off);
+        }
+
+        /** {@inheritDoc} */
+        @Override void writeByteArray(byte[] arr, int off, byte[] val) {
+            UNSAFE.copyMemory(val, BYTE_ARR_OFF, arr, BYTE_ARR_OFF + off, val.length);
+        }
+
+        /** {@inheritDoc} */
+        @Override byte[] readByteArray(byte[] arr, int off, int len) {
+            byte[] arr0 = new byte[len];
+
+            UNSAFE.copyMemory(arr, BYTE_ARR_OFF + off, arr0, BYTE_ARR_OFF, len);
+
+            return arr0;
+        }
+
+        /** {@inheritDoc} */
+        @Override void writeShortArray(byte[] arr, int off, short[] val) {
+            UNSAFE.copyMemory(val, SHORT_ARR_OFF, arr, BYTE_ARR_OFF + off, val.length << 1);
+        }
+
+        /** {@inheritDoc} */
+        @Override short[] readShortArray(byte[] arr, int off, int len) {
+            short[] arr0 = new short[len];
+
+            UNSAFE.copyMemory(arr, BYTE_ARR_OFF + off, arr0, SHORT_ARR_OFF, len << 1);
+
+            return arr0;
+        }
+
+        /** {@inheritDoc} */
+        @Override void writeIntArray(byte[] arr, int off, int[] val) {
+            UNSAFE.copyMemory(val, INT_ARR_OFF, arr, BYTE_ARR_OFF + off, val.length << 2);
+        }
+
+        /** {@inheritDoc} */
+        @Override int[] readIntArray(byte[] arr, int off, int len) {
+            int[] arr0 = new int[len];
+
+            UNSAFE.copyMemory(arr, BYTE_ARR_OFF + off, arr0, INT_ARR_OFF, len << 2);
+
+            return arr0;
+        }
+
+        /** {@inheritDoc} */
+        @Override void writeLongArray(byte[] arr, int off, long[] val) {
+            UNSAFE.copyMemory(val, LONG_ARR_OFF, arr, BYTE_ARR_OFF + off, val.length << 3);
+        }
+
+        /** {@inheritDoc} */
+        @Override long[] readLongArray(byte[] arr, int off, int len) {
+            long[] arr0 = new long[len];
+
+            UNSAFE.copyMemory(arr, BYTE_ARR_OFF + off, arr0, LONG_ARR_OFF, len << 3);
+
+            return arr0;
+        }
+
+        /** {@inheritDoc} */
+        @Override void writeFloatArray(byte[] arr, int off, float[] val) {
+            UNSAFE.copyMemory(val, FLOAT_ARR_OFF, arr, BYTE_ARR_OFF + off, val.length << 2);
+        }
+
+        /** {@inheritDoc} */
+        @Override float[] readFloatArray(byte[] arr, int off, int len) {
+            float[] arr0 = new float[len];
+
+            UNSAFE.copyMemory(arr, BYTE_ARR_OFF + off, arr0, FLOAT_ARR_OFF, len << 2);
+
+            return arr0;
+        }
+
+        /** {@inheritDoc} */
+        @Override void writeDoubleArray(byte[] arr, int off, double[] val) {
+            UNSAFE.copyMemory(val, DOUBLE_ARR_OFF, arr, BYTE_ARR_OFF + off, val.length << 3);
+        }
+
+        /** {@inheritDoc} */
+        @Override double[] readDoubleArray(byte[] arr, int off, int len) {
+            double[] arr0 = new double[len];
+
+            UNSAFE.copyMemory(arr, BYTE_ARR_OFF + off, arr0, DOUBLE_ARR_OFF, len << 3);
+
+            return arr0;
+        }
+
+        /** {@inheritDoc} */
+        @Override void writeCharArray(byte[] arr, int off, char[] val) {
+            UNSAFE.copyMemory(val, CHAR_ARR_OFF, arr, BYTE_ARR_OFF + off, val.length << 1);
+        }
+
+        /** {@inheritDoc} */
+        @Override char[] readCharArray(byte[] arr, int off, int len) {
+            char[] arr0 = new char[len];
+
+            UNSAFE.copyMemory(arr, BYTE_ARR_OFF + off, arr0, CHAR_ARR_OFF, len << 1);
+
+            return arr0;
+        }
+
+        /** {@inheritDoc} */
+        @Override void writeBooleanArray(byte[] arr, int off, boolean[] val) {
+            UNSAFE.copyMemory(val, BOOLEAN_ARR_OFF, arr, BYTE_ARR_OFF + off, val.length);
+        }
+
+        /** {@inheritDoc} */
+        @Override boolean[] readBooleanArray(byte[] arr, int off, int len) {
+            boolean[] arr0 = new boolean[len];
+
+            UNSAFE.copyMemory(arr, BYTE_ARR_OFF + off, arr0, BOOLEAN_ARR_OFF, len);
+
+            return arr0;
+        }
+    }
+
+    /** */
+    private static class BytePrimitives extends PortablePrimitives {
+        /** {@inheritDoc} */
+        @Override void writeByte(byte[] arr, int off, byte val) {
+            arr[off] = val;
+        }
+
+        /** {@inheritDoc} */
+        @Override byte readByte(byte[] arr, int off) {
+            return arr[off];
+        }
+
+        /** {@inheritDoc} */
+        @Override void writeShort(byte[] arr, int off, short val) {
+            arr[off++] = (byte)(val & 0xff);
+            arr[off] = (byte)((val >>> 8) & 0xff);
+        }
+
+        /** {@inheritDoc} */
+        @Override short readShort(byte[] arr, int off) {
+            short val = 0;
+
+            val |= (arr[off++] & 0xff);
+            val |= (arr[off] & 0xff) << 8;
+
+            return val;
+        }
+
+        /** {@inheritDoc} */
+        @Override void writeInt(byte[] arr, int off, int val) {
+            arr[off++] = (byte)(val & 0xff);
+            arr[off++] = (byte)((val >>> 8) & 0xff);
+            arr[off++] = (byte)((val >>> 16) & 0xff);
+            arr[off] = (byte)((val >>> 24) & 0xff);
+        }
+
+        /** {@inheritDoc} */
+        @Override int readInt(byte[] arr, int off) {
+            int val = 0;
+
+            val |= (arr[off++] & 0xff);
+            val |= (arr[off++] & 0xff) << 8;
+            val |= (arr[off++] & 0xff) << 16;
+            val |= (arr[off] & 0xff) << 24;
+
+            return val;
+        }
+
+        /** {@inheritDoc} */
+        @Override void writeLong(byte[] arr, int off, long val) {
+            arr[off++] = (byte)(val & 0xffL);
+            arr[off++] = (byte)((val >>> 8) & 0xffL);
+            arr[off++] = (byte)((val >>> 16) & 0xffL);
+            arr[off++] = (byte)((val >>> 24) & 0xffL);
+            arr[off++] = (byte)((val >>> 32) & 0xffL);
+            arr[off++] = (byte)((val >>> 40) & 0xffL);
+            arr[off++] = (byte)((val >>> 48) & 0xffL);
+            arr[off] = (byte)((val >>> 56) & 0xffL);
+        }
+
+        /** {@inheritDoc} */
+        @Override long readLong(byte[] arr, int off) {
+            long val = 0;
+
+            val |= (arr[off++] & 0xffL);
+            val |= (arr[off++] & 0xffL) << 8;
+            val |= (arr[off++] & 0xffL) << 16;
+            val |= (arr[off++] & 0xffL) << 24;
+            val |= (arr[off++] & 0xffL) << 32;
+            val |= (arr[off++] & 0xffL) << 40;
+            val |= (arr[off++] & 0xffL) << 48;
+            val |= (arr[off] & 0xffL) << 56;
+
+            return val;
+        }
+
+        /** {@inheritDoc} */
+        @Override void writeFloat(byte[] arr, int off, float val) {
+            writeInt(arr, off, Float.floatToIntBits(val));
+        }
+
+        /** {@inheritDoc} */
+        @Override float readFloat(byte[] arr, int off) {
+            return Float.intBitsToFloat(readInt(arr, off));
+        }
+
+        /** {@inheritDoc} */
+        @Override void writeDouble(byte[] arr, int off, double val) {
+            writeLong(arr, off, Double.doubleToLongBits(val));
+        }
+
+        /** {@inheritDoc} */
+        @Override double readDouble(byte[] arr, int off) {
+            return Double.longBitsToDouble(readLong(arr, off));
+        }
+
+        /** {@inheritDoc} */
+        @Override void writeChar(byte[] arr, int off, char val) {
+            arr[off++] = (byte)(val & 0xff);
+            arr[off] = (byte)((val >>> 8) & 0xff);
+        }
+
+        /** {@inheritDoc} */
+        @Override char readChar(byte[] arr, int off) {
+            char val = 0;
+
+            val |= (arr[off++] & 0xff);
+            val |= (arr[off] & 0xff) << 8;
+
+            return val;
+        }
+
+        /** {@inheritDoc} */
+        @Override void writeBoolean(byte[] arr, int off, boolean val) {
+            arr[off] = (byte)(val ? 1 : 0);
+        }
+
+        /** {@inheritDoc} */
+        @Override boolean readBoolean(byte[] arr, int off) {
+            return arr[off] != 0;
+        }
+
+        /** {@inheritDoc} */
+        @Override void writeByteArray(byte[] arr, int off, byte[] val) {
+            for (byte b : val)
+                arr[off++] = b;
+        }
+
+        /** {@inheritDoc} */
+        @Override byte[] readByteArray(byte[] arr, int off, int len) {
+            byte[] val = new byte[len];
+
+            for (int i = 0; i < len; i++)
+                val[i] = arr[off++];
+
+            return val;
+        }
+
+        /** {@inheritDoc} */
+        @Override void writeShortArray(byte[] arr, int off, short[] val) {
+            for (short s : val) {
+                writeShort(arr, off, s);
+
+                off += 2;
+            }
+        }
+
+        /** {@inheritDoc} */
+        @Override short[] readShortArray(byte[] arr, int off, int len) {
+            short[] val = new short[len];
+
+            for (int i = 0; i < len; i++) {
+                val[i] = readShort(arr, off);
+
+                off += 2;
+            }
+
+            return val;
+        }
+
+        /** {@inheritDoc} */
+        @Override void writeIntArray(byte[] arr, int off, int[] val) {
+            for (int i : val) {
+                writeInt(arr, off, i);
+
+                off += 4;
+            }
+        }
+
+        /** {@inheritDoc} */
+        @Override int[] readIntArray(byte[] arr, int off, int len) {
+            int[] val = new int[len];
+
+            for (int i = 0; i < len; i++) {
+                val[i] = readInt(arr, off);
+
+                off += 4;
+            }
+
+            return val;
+        }
+
+        /** {@inheritDoc} */
+        @Override void writeLongArray(byte[] arr, int off, long[] val) {
+            for (long l : val) {
+                writeLong(arr, off, l);
+
+                off += 8;
+            }
+        }
+
+        /** {@inheritDoc} */
+        @Override long[] readLongArray(byte[] arr, int off, int len) {
+            long[] val = new long[len];
+
+            for (int i = 0; i < len; i++) {
+                val[i] = readLong(arr, off);
+
+                off += 8;
+            }
+
+            return val;
+        }
+
+        /** {@inheritDoc} */
+        @Override void writeFloatArray(byte[] arr, int off, float[] val) {
+            for (float f : val) {
+                writeFloat(arr, off, f);
+
+                off += 4;
+            }
+        }
+
+        /** {@inheritDoc} */
+        @Override float[] readFloatArray(byte[] arr, int off, int len) {
+            float[] val = new float[len];
+
+            for (int i = 0; i < len; i++) {
+                val[i] = readFloat(arr, off);
+
+                off += 4;
+            }
+
+            return val;
+        }
+
+        /** {@inheritDoc} */
+        @Override void writeDoubleArray(byte[] arr, int off, double[] val) {
+            for (double d : val) {
+                writeDouble(arr, off, d);
+
+                off += 8;
+            }
+        }
+
+        /** {@inheritDoc} */
+        @Override double[] readDoubleArray(byte[] arr, int off, int len) {
+            double[] val = new double[len];
+
+            for (int i = 0; i < len; i++) {
+                val[i] = readDouble(arr, off);
+
+                off += 8;
+            }
+
+            return val;
+        }
+
+        /** {@inheritDoc} */
+        @Override void writeCharArray(byte[] arr, int off, char[] val) {
+            for (char c : val) {
+                writeChar(arr, off, c);
+
+                off += 2;
+            }
+        }
+
+        /** {@inheritDoc} */
+        @Override char[] readCharArray(byte[] arr, int off, int len) {
+            char[] val = new char[len];
+
+            for (int i = 0; i < len; i++) {
+                val[i] = readChar(arr, off);
+
+                off += 2;
+            }
+
+            return val;
+        }
+
+        /** {@inheritDoc} */
+        @Override void writeBooleanArray(byte[] arr, int off, boolean[] val) {
+            for (boolean b : val)
+                writeBoolean(arr, off++, b);
+        }
+
+        /** {@inheritDoc} */
+        @Override boolean[] readBooleanArray(byte[] arr, int off, int len) {
+            boolean[] val = new boolean[len];
+
+            for (int i = 0; i < len; i++)
+                val[i] = readBoolean(arr, off++);
+
+            return val;
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableRawReaderEx.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableRawReaderEx.java b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableRawReaderEx.java
new file mode 100644
index 0000000..2abce7f
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableRawReaderEx.java
@@ -0,0 +1,33 @@
+/*
+ * 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.portable;
+
+import org.apache.ignite.portable.*;
+
+import org.jetbrains.annotations.*;
+
+/**
+ * Extended reader interface.
+ */
+public interface PortableRawReaderEx extends PortableRawReader {
+    /**
+     * @return Object.
+     * @throws PortableException In case of error.
+     */
+    @Nullable public Object readObjectDetached() throws PortableException;
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableRawWriterEx.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableRawWriterEx.java b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableRawWriterEx.java
new file mode 100644
index 0000000..d3e65f0
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableRawWriterEx.java
@@ -0,0 +1,44 @@
+/*
+ * 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.portable;
+
+import org.apache.ignite.internal.portable.streams.*;
+import org.apache.ignite.portable.*;
+
+import org.jetbrains.annotations.*;
+
+/**
+ * Extended writer interface.
+ */
+public interface PortableRawWriterEx extends PortableRawWriter, AutoCloseable {
+    /**
+     * @param obj Object to write.
+     * @throws PortableException In case of error.
+     */
+    public void writeObjectDetached(@Nullable Object obj) throws PortableException;
+
+    /**
+     * @return Output stream.
+     */
+    public PortableOutputStream out();
+
+    /**
+     * Cleans resources.
+     */
+    @Override public void close();
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableReaderContext.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableReaderContext.java b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableReaderContext.java
new file mode 100644
index 0000000..704305a
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableReaderContext.java
@@ -0,0 +1,83 @@
+/*
+ * 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.portable;
+
+import org.apache.ignite.internal.util.typedef.internal.*;
+import org.apache.ignite.portable.*;
+
+import org.jetbrains.annotations.*;
+
+import java.util.*;
+
+/**
+ * Reader context.
+ */
+class PortableReaderContext {
+    /** */
+    private Map<Integer, Object> oHandles;
+
+    /** */
+    private Map<Integer, PortableObject> poHandles;
+
+    /**
+     * @param handle Handle.
+     * @param obj Object.
+     */
+    void setObjectHandler(int handle, Object obj) {
+        assert obj != null;
+
+        if (oHandles == null)
+            oHandles = new HashMap<>(3, 1.0f);
+
+        oHandles.put(handle, obj);
+    }
+
+    /**
+     * @param handle Handle.
+     * @param po Portable object.
+     */
+    void setPortableHandler(int handle, PortableObject po) {
+        assert po != null;
+
+        if (poHandles == null)
+            poHandles = new HashMap<>(3, 1.0f);
+
+        poHandles.put(handle, po);
+    }
+
+    /**
+     * @param handle Handle.
+     * @return Object.
+     */
+    @Nullable Object getObjectByHandle(int handle) {
+        return oHandles != null ? oHandles.get(handle) : null;
+    }
+
+    /**
+     * @param handle Handle.
+     * @return Object.
+     */
+    @Nullable PortableObject getPortableByHandle(int handle) {
+        return poHandles != null ? poHandles.get(handle) : null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public String toString() {
+        return S.toString(PortableReaderContext.class, this);
+    }
+}


[10/59] [abbrv] ignite git commit: ignite-1258: portable objects API support in Ignite

Posted by vk...@apache.org.
http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableReaderExImpl.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableReaderExImpl.java b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableReaderExImpl.java
new file mode 100644
index 0000000..2a6c2e3
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableReaderExImpl.java
@@ -0,0 +1,2949 @@
+/*
+ * 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.portable;
+
+import org.apache.ignite.*;
+import org.apache.ignite.internal.portable.streams.*;
+import org.apache.ignite.internal.util.*;
+import org.apache.ignite.internal.util.lang.*;
+import org.apache.ignite.internal.util.typedef.internal.*;
+import org.apache.ignite.portable.*;
+
+import org.jetbrains.annotations.*;
+
+import java.io.*;
+import java.lang.reflect.Array;
+import java.lang.reflect.*;
+import java.math.*;
+import java.sql.*;
+import java.util.*;
+import java.util.Date;
+import java.util.concurrent.*;
+
+import static java.nio.charset.StandardCharsets.*;
+import static org.apache.ignite.internal.portable.GridPortableMarshaller.*;
+
+/**
+ * Portable reader implementation.
+ */
+@SuppressWarnings("unchecked")
+public class PortableReaderExImpl implements PortableReader, PortableRawReaderEx, ObjectInput {
+    /** */
+    private final PortableContext ctx;
+
+    /** */
+    private final PortableInputStream in;
+
+    /** */
+    private final int start;
+
+    /** */
+    private final PortableReaderContext rCtx;
+
+    /** */
+    private final ClassLoader ldr;
+
+    /** */
+    private int off;
+
+    /** */
+    private int rawOff;
+
+    /** */
+    private int len;
+
+    /** */
+    private PortableClassDescriptor desc;
+
+    /** */
+    private int hdrLen;
+
+    /** */
+    private int clsNameLen;
+
+    /** */
+    private Integer typeId;
+
+    /**
+     * @param ctx Context.
+     * @param arr Array.
+     * @param start Start.
+     * @param ldr Class loader.
+     */
+    PortableReaderExImpl(PortableContext ctx, byte[] arr, int start, ClassLoader ldr) {
+        this(ctx, new PortableHeapInputStream(arr), start, ldr, new PortableReaderContext());
+    }
+
+    /**
+     * @param ctx Context.
+     * @param in Input stream.
+     * @param start Start.
+     */
+    PortableReaderExImpl(PortableContext ctx, PortableInputStream in, int start, ClassLoader ldr) {
+        this(ctx, in, start, ldr, new PortableReaderContext());
+    }
+
+    /**
+     * @param ctx Context.
+     * @param in Input stream.
+     * @param start Start.
+     * @param rCtx Context.
+     */
+    PortableReaderExImpl(PortableContext ctx, PortableInputStream in, int start, ClassLoader ldr,
+        PortableReaderContext rCtx) {
+        this.ctx = ctx;
+        this.in = in;
+        this.start = start;
+        this.ldr = ldr;
+        this.rCtx = rCtx;
+
+        off = start;
+        rawOff = start;
+    }
+
+    /**
+     * Preloads typeId from the input array.
+     */
+    private void readObjectTypeId(boolean skipObjByte) {
+        int pos = rawOff;
+
+        if (!skipObjByte)
+            // skip obj type byte
+            rawOff++;
+
+        // skip user flag
+        rawOff += 1;
+
+        typeId = doReadInt(true);
+
+        if (typeId == UNREGISTERED_TYPE_ID) {
+            // skip hash code, length and raw offset
+            rawOff += 12;
+
+            int off = rawOff;
+
+            Class cls = doReadClass(true, typeId);
+
+            // registers class by typeId, at least locally if the cache is not ready yet.
+            PortableClassDescriptor desc = ctx.descriptorForClass(cls);
+
+            typeId = desc.typeId();
+
+            clsNameLen = rawOff - off;
+
+            hdrLen = CLS_NAME_POS + clsNameLen;
+        }
+        else
+            hdrLen = DFLT_HDR_LEN;
+
+        in.position(rawOff = pos);
+    }
+
+    /**
+     * @return Descriptor.
+     */
+    PortableClassDescriptor descriptor() {
+        return desc;
+    }
+
+    /**
+     * @return Unmarshalled value.
+     * @throws PortableException In case of error.
+     */
+    @Nullable Object unmarshal() throws PortableException {
+        return unmarshal(true);
+    }
+
+    /**
+     * @param fieldName Field name.
+     * @return Unmarshalled value.
+     * @throws PortableException In case of error.
+     */
+    @Nullable Object unmarshal(String fieldName) throws PortableException {
+        off = fieldOffset(fieldId(fieldName));
+
+        return off >= 0 ? unmarshal(false) : null;
+    }
+
+    /**
+     * @param offset Offset in the array.
+     * @return Unmarshalled value.
+     * @throws PortableException In case of error.
+     */
+    Object unmarshal(int offset) throws PortableException {
+        off = offset;
+
+        return off >= 0 ? unmarshal(false) : null;
+    }
+
+    /**
+     * @param fieldId Field ID.
+     * @return Value.
+     * @throws PortableException In case of error.
+     */
+    @Nullable Byte readByte(int fieldId) throws PortableException {
+        off = fieldOffset(fieldId);
+
+        if (off >= 0) {
+            byte flag = doReadByte(false);
+
+            if (flag == NULL)
+                return null;
+
+            if (flag != BYTE)
+                throw new PortableException("Invalid flag value: " + flag);
+
+            return doReadByte(false);
+        }
+        else
+            return null;
+    }
+
+    /**
+     * @param fieldId Field ID.
+     * @return Value.
+     * @throws PortableException In case of error.
+     */
+    @Nullable Short readShort(int fieldId) throws PortableException {
+        off = fieldOffset(fieldId);
+
+        if (off >= 0) {
+            byte flag = doReadByte(false);
+
+            if (flag == NULL)
+                return null;
+
+            if (flag != SHORT)
+                throw new PortableException("Invalid flag value: " + flag);
+
+            return doReadShort(false);
+        }
+        else
+            return null;
+    }
+
+    /**
+     * @param fieldId Field ID.
+     * @return Value.
+     * @throws PortableException In case of error.
+     */
+    @Nullable Integer readInt(int fieldId) throws PortableException {
+        off = fieldOffset(fieldId);
+
+        if (off >= 0) {
+            byte flag = doReadByte(false);
+
+            if (flag == NULL)
+                return null;
+
+            if (flag != INT)
+                throw new PortableException("Invalid flag value: " + flag);
+
+            return doReadInt(false);
+        }
+        else
+            return null;
+    }
+
+    /**
+     * @param fieldId Field ID.
+     * @return Value.
+     * @throws PortableException In case of error.
+     */
+    @Nullable Long readLong(int fieldId) throws PortableException {
+        off = fieldOffset(fieldId);
+
+        if (off >= 0) {
+            byte flag = doReadByte(false);
+
+            if (flag == NULL)
+                return null;
+
+            if (flag != LONG)
+                throw new PortableException("Invalid flag value: " + flag);
+
+            return doReadLong(false);
+        }
+        else
+            return null;
+    }
+
+    /**
+     * @param fieldId Field ID.
+     * @return Value.
+     * @throws PortableException In case of error.
+     */
+    @Nullable Float readFloat(int fieldId) throws PortableException {
+        off = fieldOffset(fieldId);
+
+        if (off >= 0) {
+            byte flag = doReadByte(false);
+
+            if (flag == NULL)
+                return null;
+
+            if (flag != FLOAT)
+                throw new PortableException("Invalid flag value: " + flag);
+
+            return doReadFloat(false);
+        }
+        else
+            return null;
+    }
+
+    /**
+     * @param fieldId Field ID.
+     * @return Value.
+     * @throws PortableException In case of error.
+     */
+    @Nullable Double readDouble(int fieldId) throws PortableException {
+        off = fieldOffset(fieldId);
+
+        if (off >= 0) {
+            byte flag = doReadByte(false);
+
+            if (flag == NULL)
+                return null;
+
+            if (flag != DOUBLE)
+                throw new PortableException("Invalid flag value: " + flag);
+
+            return doReadDouble(false);
+        }
+        else
+            return null;
+    }
+
+    /**
+     * @param fieldId Field ID.
+     * @return Value.
+     * @throws PortableException In case of error.
+     */
+    @Nullable Character readChar(int fieldId) throws PortableException {
+        off = fieldOffset(fieldId);
+
+        if (off >= 0) {
+            byte flag = doReadByte(false);
+
+            if (flag == NULL)
+                return null;
+
+            if (flag != CHAR)
+                throw new PortableException("Invalid flag value: " + flag);
+
+            return doReadChar(false);
+        }
+        else
+            return null;
+    }
+
+    /**
+     * @param fieldId Field ID.
+     * @return Value.
+     * @throws PortableException In case of error.
+     */
+    @Nullable Boolean readBoolean(int fieldId) throws PortableException {
+        off = fieldOffset(fieldId);
+
+        if (off >= 0) {
+            byte flag = doReadByte(false);
+
+            if (flag == NULL)
+                return null;
+
+            if (flag != BOOLEAN)
+                throw new PortableException("Invalid flag value: " + flag);
+
+            return doReadBoolean(false);
+        }
+        else
+            return null;
+    }
+
+    /**
+     * @param fieldId Field ID.
+     * @return Value.
+     * @throws PortableException In case of error.
+     */
+    @Nullable BigDecimal readDecimal(int fieldId) throws PortableException {
+        off = fieldOffset(fieldId);
+
+        if (off >= 0) {
+            byte flag = doReadByte(false);
+
+            if (flag == NULL)
+                return null;
+
+            if (flag != DECIMAL)
+                throw new PortableException("Invalid flag value: " + flag);
+
+            return doReadDecimal(false);
+        }
+        else
+            return null;
+    }
+
+    /**
+     * @param fieldId Field ID.
+     * @return Value.
+     * @throws PortableException In case of error.
+     */
+    @Nullable String readString(int fieldId) throws PortableException {
+        off = fieldOffset(fieldId);
+
+        if (off >= 0) {
+            byte flag = doReadByte(false);
+
+            if (flag == NULL)
+                return null;
+
+            if (flag != STRING)
+                throw new PortableException("Invalid flag value: " + flag);
+
+            return doReadString(false);
+        }
+        else
+            return null;
+    }
+
+    /**
+     * @param fieldId Field ID.
+     * @return Value.
+     * @throws PortableException In case of error.
+     */
+    @Nullable UUID readUuid(int fieldId) throws PortableException {
+        off = fieldOffset(fieldId);
+
+        if (off >= 0) {
+            byte flag = doReadByte(false);
+
+            if (flag == NULL)
+                return null;
+
+            if (flag != UUID)
+                throw new PortableException("Invalid flag value: " + flag);
+
+            return doReadUuid(false);
+        }
+        else
+            return null;
+    }
+
+    /**
+     * @param fieldId Field ID.
+     * @return Value.
+     * @throws PortableException In case of error.
+     */
+    @Nullable Date readDate(int fieldId) throws PortableException {
+        off = fieldOffset(fieldId);
+
+        if (off >= 0) {
+            byte flag = doReadByte(false);
+
+            if (flag == NULL)
+                return null;
+
+            if (flag != DATE)
+                throw new PortableException("Invalid flag value: " + flag);
+
+            return doReadDate(false);
+        }
+        else
+            return null;
+    }
+
+    /**
+     * @param fieldId Field ID.
+     * @return Value.
+     * @throws PortableException In case of error.
+     */
+    @Nullable Timestamp readTimestamp(int fieldId) throws PortableException {
+        off = fieldOffset(fieldId);
+
+        if (off >= 0) {
+            byte flag = doReadByte(false);
+
+            if (flag == NULL)
+                return null;
+
+            if (flag != DATE)
+                throw new PortableException("Invalid flag value: " + flag);
+
+            return doReadTimestamp(false);
+        }
+        else
+            return null;
+    }
+
+    /**
+     * @param fieldId Field ID.
+     * @return Value.
+     * @throws PortableException In case of error.
+     */
+    @Nullable Object readObject(int fieldId) throws PortableException {
+        off = fieldOffset(fieldId);
+
+        return off >= 0 ? doReadObject(false) : null;
+    }
+
+    /**
+     * @param fieldId Field ID.
+     * @return Value.
+     * @throws PortableException In case of error.
+     */
+    @Nullable byte[] readByteArray(int fieldId) throws PortableException {
+        off = fieldOffset(fieldId);
+
+        if (off >= 0) {
+            byte flag = doReadByte(false);
+
+            if (flag == NULL)
+                return null;
+
+            if (flag != BYTE_ARR)
+                throw new PortableException("Invalid flag value: " + flag);
+
+            return doReadByteArray(false);
+        }
+        else
+            return null;
+    }
+
+    /**
+     * @param fieldId Field ID.
+     * @return Value.
+     * @throws PortableException In case of error.
+     */
+    @Nullable short[] readShortArray(int fieldId) throws PortableException {
+        off = fieldOffset(fieldId);
+
+        if (off >= 0) {
+            byte flag = doReadByte(false);
+
+            if (flag == NULL)
+                return null;
+
+            if (flag != SHORT_ARR)
+                throw new PortableException("Invalid flag value: " + flag);
+
+            return doReadShortArray(false);
+        }
+        else
+            return null;
+    }
+
+    /**
+     * @param fieldId Field ID.
+     * @return Value.
+     * @throws PortableException In case of error.
+     */
+    @Nullable int[] readIntArray(int fieldId) throws PortableException {
+        off = fieldOffset(fieldId);
+
+        if (off >= 0) {
+            byte flag = doReadByte(false);
+
+            if (flag == NULL)
+                return null;
+
+            if (flag != INT_ARR)
+                throw new PortableException("Invalid flag value: " + flag);
+
+            return doReadIntArray(false);
+        }
+        else
+            return null;
+    }
+
+    /**
+     * @param fieldId Field ID.
+     * @return Value.
+     * @throws PortableException In case of error.
+     */
+    @Nullable long[] readLongArray(int fieldId) throws PortableException {
+        off = fieldOffset(fieldId);
+
+        if (off >= 0) {
+            byte flag = doReadByte(false);
+
+            if (flag == NULL)
+                return null;
+
+            if (flag != LONG_ARR)
+                throw new PortableException("Invalid flag value: " + flag);
+
+            return doReadLongArray(false);
+        }
+        else
+            return null;
+    }
+
+    /**
+     * @param fieldId Field ID.
+     * @return Value.
+     * @throws PortableException In case of error.
+     */
+    @Nullable float[] readFloatArray(int fieldId) throws PortableException {
+        off = fieldOffset(fieldId);
+
+        if (off >= 0) {
+            byte flag = doReadByte(false);
+
+            if (flag == NULL)
+                return null;
+
+            if (flag != FLOAT_ARR)
+                throw new PortableException("Invalid flag value: " + flag);
+
+            return doReadFloatArray(false);
+        }
+        else
+            return null;
+    }
+
+    /**
+     * @param fieldId Field ID.
+     * @return Value.
+     * @throws PortableException In case of error.
+     */
+    @Nullable double[] readDoubleArray(int fieldId) throws PortableException {
+        off = fieldOffset(fieldId);
+
+        if (off >= 0) {
+            byte flag = doReadByte(false);
+
+            if (flag == NULL)
+                return null;
+
+            if (flag != DOUBLE_ARR)
+                throw new PortableException("Invalid flag value: " + flag);
+
+            return doReadDoubleArray(false);
+        }
+        else
+            return null;
+    }
+
+    /**
+     * @param fieldId Field ID.
+     * @return Value.
+     * @throws PortableException In case of error.
+     */
+    @Nullable char[] readCharArray(int fieldId) throws PortableException {
+        off = fieldOffset(fieldId);
+
+        if (off >= 0) {
+            byte flag = doReadByte(false);
+
+            if (flag == NULL)
+                return null;
+
+            if (flag != CHAR_ARR)
+                throw new PortableException("Invalid flag value: " + flag);
+
+            return doReadCharArray(false);
+        }
+        else
+            return null;
+    }
+
+    /**
+     * @param fieldId Field ID.
+     * @return Value.
+     * @throws PortableException In case of error.
+     */
+    @Nullable boolean[] readBooleanArray(int fieldId) throws PortableException {
+        off = fieldOffset(fieldId);
+
+        if (off >= 0) {
+            byte flag = doReadByte(false);
+
+            if (flag == NULL)
+                return null;
+
+            if (flag != BOOLEAN_ARR)
+                throw new PortableException("Invalid flag value: " + flag);
+
+            return doReadBooleanArray(false);
+        }
+        else
+            return null;
+    }
+
+    /**
+     * @param fieldId Field ID.
+     * @return Value.
+     * @throws PortableException In case of error.
+     */
+    @Nullable BigDecimal[] readDecimalArray(int fieldId) throws PortableException {
+        off = fieldOffset(fieldId);
+
+        if (off >= 0) {
+            byte flag = doReadByte(false);
+
+            if (flag == NULL)
+                return null;
+
+            if (flag != DECIMAL_ARR)
+                throw new PortableException("Invalid flag value: " + flag);
+
+            return doReadDecimalArray(false);
+        }
+        else
+            return null;
+    }
+
+    /**
+     * @param fieldId Field ID.
+     * @return Value.
+     * @throws PortableException In case of error.
+     */
+    @Nullable String[] readStringArray(int fieldId) throws PortableException {
+        off = fieldOffset(fieldId);
+
+        if (off >= 0) {
+            byte flag = doReadByte(false);
+
+            if (flag == NULL)
+                return null;
+
+            if (flag != STRING_ARR)
+                throw new PortableException("Invalid flag value: " + flag);
+
+            return doReadStringArray(false);
+        }
+        else
+            return null;
+    }
+
+    /**
+     * @param fieldId Field ID.
+     * @return Value.
+     * @throws PortableException In case of error.
+     */
+    @Nullable UUID[] readUuidArray(int fieldId) throws PortableException {
+        off = fieldOffset(fieldId);
+
+        if (off >= 0) {
+            byte flag = doReadByte(false);
+
+            if (flag == NULL)
+                return null;
+
+            if (flag != UUID_ARR)
+                throw new PortableException("Invalid flag value: " + flag);
+
+            return doReadUuidArray(false);
+        }
+        else
+            return null;
+    }
+
+    /**
+     * @param fieldId Field ID.
+     * @return Value.
+     * @throws PortableException In case of error.
+     */
+    @Nullable Date[] readDateArray(int fieldId) throws PortableException {
+        off = fieldOffset(fieldId);
+
+        if (off >= 0) {
+            byte flag = doReadByte(false);
+
+            if (flag == NULL)
+                return null;
+
+            if (flag != DATE_ARR)
+                throw new PortableException("Invalid flag value: " + flag);
+
+            return doReadDateArray(false);
+        }
+        else
+            return null;
+    }
+
+    /**
+     * @param fieldId Field ID.
+     * @return Value.
+     * @throws PortableException In case of error.
+     */
+    @Nullable Object[] readObjectArray(int fieldId) throws PortableException {
+        off = fieldOffset(fieldId);
+
+        if (off >= 0) {
+            byte flag = doReadByte(false);
+
+            if (flag == NULL)
+                return null;
+
+            if (flag != OBJ_ARR)
+                throw new PortableException("Invalid flag value: " + flag);
+
+            return doReadObjectArray(false, true);
+        }
+        else
+            return null;
+    }
+
+    /**
+     * @param fieldId Field ID.
+     * @param cls Collection class.
+     * @return Value.
+     * @throws PortableException In case of error.
+     */
+    @Nullable <T> Collection<T> readCollection(int fieldId, @Nullable Class<? extends Collection> cls)
+        throws PortableException {
+        off = fieldOffset(fieldId);
+
+        if (off >= 0) {
+            byte flag = doReadByte(false);
+
+            if (flag == NULL)
+                return null;
+
+            if (flag != COL)
+                throw new PortableException("Invalid flag value: " + flag);
+
+            return (Collection<T>)doReadCollection(false, true, cls);
+        }
+        else
+            return null;
+    }
+
+    /**
+     * @param fieldId Field ID.
+     * @param cls Map class.
+     * @return Value.
+     * @throws PortableException In case of error.
+     */
+    @Nullable Map<?, ?> readMap(int fieldId, @Nullable Class<? extends Map> cls)
+        throws PortableException {
+        off = fieldOffset(fieldId);
+
+        if (off >= 0) {
+            byte flag = doReadByte(false);
+
+            if (flag == NULL)
+                return null;
+
+            if (flag != MAP)
+                throw new PortableException("Invalid flag value: " + flag);
+
+            return doReadMap(false, true, cls);
+        }
+        else
+            return null;
+    }
+
+    /**
+     * @param fieldId Field ID.
+     * @return Value.
+     * @throws PortableException On case of error.
+     */
+    @Nullable Map.Entry<?, ?> readMapEntry(int fieldId) throws PortableException {
+        off = fieldOffset(fieldId);
+
+        if (off >= 0) {
+            byte flag = doReadByte(false);
+
+            if (flag == NULL)
+                return null;
+
+            if (flag != MAP_ENTRY)
+                throw new PortableException("Invalid flag value: " + flag);
+
+            return new GridMapEntry<>(doReadObject(false), doReadObject(false));
+        }
+        else
+            return null;
+    }
+
+    /**
+     * @param fieldId Field ID.
+     * @return Portable object.
+     * @throws PortableException In case of error.
+     */
+    @Nullable PortableObject readPortableObject(int fieldId) throws PortableException {
+        off = fieldOffset(fieldId);
+
+        if (off >= 0) {
+            byte flag = doReadByte(false);
+
+            if (flag == NULL)
+                return null;
+
+            if (flag != PORTABLE_OBJ)
+                throw new PortableException("Invalid flag value: " + flag);
+
+            return new PortableObjectImpl(ctx, doReadByteArray(false), doReadInt(false));
+        }
+        else
+            return null;
+    }
+
+    /**
+     * @param fieldId Field ID.
+     * @param cls Class.
+     * @return Value.
+     * @throws PortableException In case of error.
+     */
+    @Nullable Enum<?> readEnum(int fieldId, @Nullable Class<?> cls) throws PortableException {
+        off = fieldOffset(fieldId);
+
+        if (off >= 0) {
+            byte flag = doReadByte(false);
+
+            if (flag == NULL)
+                return null;
+
+            if (flag != ENUM)
+                throw new PortableException("Invalid flag value: " + flag);
+
+            // Revisit: why have we started writing Class for enums in their serialized form?
+            if (cls == null)
+                cls = doReadClass(false);
+            else
+                doReadClass(false);
+
+            Object[] vals = GridEnumCache.get(cls);
+
+            return (Enum<?>)vals[doReadInt(false)];
+        }
+        else
+            return null;
+    }
+
+    /**
+     * @param fieldId Field ID.
+     * @param cls Class.
+     * @return Value.
+     * @throws PortableException In case of error.
+     */
+    @Nullable Object[] readEnumArray(int fieldId, @Nullable Class<?> cls) throws PortableException {
+        off = fieldOffset(fieldId);
+
+        if (off >= 0) {
+            byte flag = doReadByte(false);
+
+            if (flag == NULL)
+                return null;
+
+            if (flag != ENUM_ARR)
+                throw new PortableException("Invalid flag value: " + flag);
+
+            // Revisit: why have we started writing Class for enums in their serialized form?
+            if (cls == null)
+                cls = doReadClass(false);
+            else
+                doReadClass(false);
+
+            return doReadEnumArray(false, cls);
+        }
+        else
+            return null;
+    }
+
+    /**
+     * @param fieldId Field ID.
+     * @return Field class.
+     * @throws PortableException In case of error.
+     */
+    @Nullable Class<?> readClass(int fieldId) throws PortableException {
+        off = fieldOffset(fieldId);
+
+        if (off >= 0) {
+            byte flag = doReadByte(false);
+
+            if (flag == NULL)
+                return null;
+
+            if (flag != CLASS)
+                throw new PortableException("Invalid flag type: [flag=" + flag + ']');
+
+            return doReadClass(false);
+        }
+
+        return null;
+    }
+
+    /**
+     * @param obj Object.
+     */
+    void setHandler(Object obj) {
+        rCtx.setObjectHandler(start, obj);
+    }
+
+    /** {@inheritDoc} */
+    @Override public byte readByte(String fieldName) throws PortableException {
+        Byte val = readByte(fieldId(fieldName));
+
+        return val != null ? val : 0;
+    }
+
+    /** {@inheritDoc} */
+    @Override public byte readByte() throws PortableException {
+        return doReadByte(true);
+    }
+
+    /** {@inheritDoc} */
+    @Override public short readShort(String fieldName) throws PortableException {
+        Short val = readShort(fieldId(fieldName));
+
+        return val != null ? val : 0;
+    }
+
+    /** {@inheritDoc} */
+    @Override public short readShort() throws PortableException {
+        return doReadShort(true);
+    }
+
+    /** {@inheritDoc} */
+    @Override public int readInt(String fieldName) throws PortableException {
+        Integer val = readInt(fieldId(fieldName));
+
+        return val != null ? val : 0;
+    }
+
+    /** {@inheritDoc} */
+    @Override public int readInt() throws PortableException {
+        return doReadInt(true);
+    }
+
+    /** {@inheritDoc} */
+    @Override public long readLong(String fieldName) throws PortableException {
+        Long val = readLong(fieldId(fieldName));
+
+        return val != null ? val : 0;
+    }
+
+    /** {@inheritDoc} */
+    @Override public long readLong() throws PortableException {
+        return doReadLong(true);
+    }
+
+    /** {@inheritDoc} */
+    @Override public float readFloat(String fieldName) throws PortableException {
+        Float val = readFloat(fieldId(fieldName));
+
+        return val != null ? val : 0;
+    }
+
+    /** {@inheritDoc} */
+    @Override public float readFloat() throws PortableException {
+        return doReadFloat(true);
+    }
+
+    /** {@inheritDoc} */
+    @Override public double readDouble(String fieldName) throws PortableException {
+        Double val = readDouble(fieldId(fieldName));
+
+        return val != null ? val : 0;
+    }
+
+    /** {@inheritDoc} */
+    @Override public double readDouble() throws PortableException {
+        return doReadDouble(true);
+    }
+
+    /** {@inheritDoc} */
+    @Override public char readChar(String fieldName) throws PortableException {
+        Character val = readChar(fieldId(fieldName));
+
+        return val != null ? val : 0;
+    }
+
+    /** {@inheritDoc} */
+    @Override public char readChar() throws PortableException {
+        return doReadChar(true);
+    }
+
+    /** {@inheritDoc} */
+    @Override public boolean readBoolean(String fieldName) throws PortableException {
+        Boolean val = readBoolean(fieldId(fieldName));
+
+        return val != null ? val : false;
+    }
+
+    /** {@inheritDoc} */
+    @Override public boolean readBoolean() throws PortableException {
+        return doReadBoolean(true);
+    }
+
+    /** {@inheritDoc} */
+    @Override @Nullable public BigDecimal readDecimal(String fieldName) throws PortableException {
+        return readDecimal(fieldId(fieldName));
+    }
+
+    /** {@inheritDoc} */
+    @Override @Nullable public BigDecimal readDecimal() throws PortableException {
+        byte flag = doReadByte(true);
+
+        if (flag == NULL)
+            return null;
+
+        if (flag != DECIMAL)
+            throw new PortableException("Invalid flag value: " + flag);
+
+        return doReadDecimal(true);
+    }
+
+    /** {@inheritDoc} */
+    @Nullable @Override public String readString(String fieldName) throws PortableException {
+        return readString(fieldId(fieldName));
+    }
+
+    /** {@inheritDoc} */
+    @Nullable @Override public String readString() throws PortableException {
+        byte flag = doReadByte(true);
+
+        if (flag == NULL)
+            return null;
+
+        if (flag != STRING)
+            throw new PortableException("Invalid flag value: " + flag);
+
+        return doReadString(true);
+    }
+
+    /** {@inheritDoc} */
+    @Nullable @Override public UUID readUuid(String fieldName) throws PortableException {
+        return readUuid(fieldId(fieldName));
+    }
+
+    /** {@inheritDoc} */
+    @Nullable @Override public UUID readUuid() throws PortableException {
+        byte flag = doReadByte(true);
+
+        if (flag == NULL)
+            return null;
+
+        if (flag != UUID)
+            throw new PortableException("Invalid flag value: " + flag);
+
+        return doReadUuid(true);
+    }
+
+    /** {@inheritDoc} */
+    @Nullable @Override public Date readDate(String fieldName) throws PortableException {
+        return readDate(fieldId(fieldName));
+    }
+
+    /** {@inheritDoc} */
+    @Nullable @Override public Date readDate() throws PortableException {
+        byte flag = doReadByte(true);
+
+        if (flag == NULL)
+            return null;
+
+        if (flag != DATE)
+            throw new PortableException("Invalid flag value: " + flag);
+
+        return doReadDate(true);
+    }
+
+    /** {@inheritDoc} */
+    @Nullable @Override public Timestamp readTimestamp(String fieldName) throws PortableException {
+        return readTimestamp(fieldId(fieldName));
+    }
+
+    /** {@inheritDoc} */
+    @Nullable @Override public Timestamp readTimestamp() throws PortableException {
+        byte flag = doReadByte(true);
+
+        if (flag == NULL)
+            return null;
+
+        if (flag != DATE)
+            throw new PortableException("Invalid flag value: " + flag);
+
+        return doReadTimestamp(true);
+    }
+
+    /** {@inheritDoc} */
+    @SuppressWarnings("unchecked")
+    @Nullable @Override public <T> T readObject(String fieldName) throws PortableException {
+        return (T)readObject(fieldId(fieldName));
+    }
+
+    /** {@inheritDoc} */
+    @Override public Object readObject() throws PortableException {
+        return doReadObject(true);
+    }
+
+    /** {@inheritDoc} */
+    @Nullable @Override public Object readObjectDetached() throws PortableException {
+        return unmarshal(true, true);
+    }
+
+    /** {@inheritDoc} */
+    @Nullable @Override public byte[] readByteArray(String fieldName) throws PortableException {
+        return readByteArray(fieldId(fieldName));
+    }
+
+    /** {@inheritDoc} */
+    @Nullable @Override public byte[] readByteArray() throws PortableException {
+        byte flag = doReadByte(true);
+
+        if (flag == NULL)
+            return null;
+
+        if (flag != BYTE_ARR)
+            throw new PortableException("Invalid flag value: " + flag);
+
+        return doReadByteArray(true);
+    }
+
+    /** {@inheritDoc} */
+    @Nullable @Override public short[] readShortArray(String fieldName) throws PortableException {
+        return readShortArray(fieldId(fieldName));
+    }
+
+    /** {@inheritDoc} */
+    @Nullable @Override public short[] readShortArray() throws PortableException {
+        byte flag = doReadByte(true);
+
+        if (flag == NULL)
+            return null;
+
+        if (flag != SHORT_ARR)
+            throw new PortableException("Invalid flag value: " + flag);
+
+        return doReadShortArray(true);
+    }
+
+    /** {@inheritDoc} */
+    @Nullable @Override public int[] readIntArray(String fieldName) throws PortableException {
+        return readIntArray(fieldId(fieldName));
+    }
+
+    /** {@inheritDoc} */
+    @Nullable @Override public int[] readIntArray() throws PortableException {
+        byte flag = doReadByte(true);
+
+        if (flag == NULL)
+            return null;
+
+        if (flag != INT_ARR)
+            throw new PortableException("Invalid flag value: " + flag);
+
+        return doReadIntArray(true);
+    }
+
+    /** {@inheritDoc} */
+    @Nullable @Override public long[] readLongArray(String fieldName) throws PortableException {
+        return readLongArray(fieldId(fieldName));
+    }
+
+    /** {@inheritDoc} */
+    @Nullable @Override public long[] readLongArray() throws PortableException {
+        byte flag = doReadByte(true);
+
+        if (flag == NULL)
+            return null;
+
+        if (flag != LONG_ARR)
+            throw new PortableException("Invalid flag value: " + flag);
+
+        return doReadLongArray(true);
+    }
+
+    /** {@inheritDoc} */
+    @Nullable @Override public float[] readFloatArray(String fieldName) throws PortableException {
+        return readFloatArray(fieldId(fieldName));
+    }
+
+    /** {@inheritDoc} */
+    @Nullable @Override public float[] readFloatArray() throws PortableException {
+        byte flag = doReadByte(true);
+
+        if (flag == NULL)
+            return null;
+
+        if (flag != FLOAT_ARR)
+            throw new PortableException("Invalid flag value: " + flag);
+
+        return doReadFloatArray(true);
+    }
+
+    /** {@inheritDoc} */
+    @Nullable @Override public double[] readDoubleArray(String fieldName) throws PortableException {
+        return readDoubleArray(fieldId(fieldName));
+    }
+
+    /** {@inheritDoc} */
+    @Nullable @Override public double[] readDoubleArray() throws PortableException {
+        byte flag = doReadByte(true);
+
+        if (flag == NULL)
+            return null;
+
+        if (flag != DOUBLE_ARR)
+            throw new PortableException("Invalid flag value: " + flag);
+
+        return doReadDoubleArray(true);
+    }
+
+    /** {@inheritDoc} */
+    @Nullable @Override public char[] readCharArray(String fieldName) throws PortableException {
+        return readCharArray(fieldId(fieldName));
+    }
+
+    /** {@inheritDoc} */
+    @Nullable @Override public char[] readCharArray() throws PortableException {
+        byte flag = doReadByte(true);
+
+        if (flag == NULL)
+            return null;
+
+        if (flag != CHAR_ARR)
+            throw new PortableException("Invalid flag value: " + flag);
+
+        return doReadCharArray(true);
+    }
+
+    /** {@inheritDoc} */
+    @Nullable @Override public boolean[] readBooleanArray(String fieldName) throws PortableException {
+        return readBooleanArray(fieldId(fieldName));
+    }
+
+    /** {@inheritDoc} */
+    @Nullable @Override public boolean[] readBooleanArray() throws PortableException {
+        byte flag = doReadByte(true);
+
+        if (flag == NULL)
+            return null;
+
+        if (flag != BOOLEAN_ARR)
+            throw new PortableException("Invalid flag value: " + flag);
+
+        return doReadBooleanArray(true);
+    }
+
+    /** {@inheritDoc} */
+    @Override @Nullable public BigDecimal[] readDecimalArray(String fieldName) throws PortableException {
+        return readDecimalArray(fieldId(fieldName));
+    }
+
+    /** {@inheritDoc} */
+    @Override @Nullable public BigDecimal[] readDecimalArray() throws PortableException {
+        byte flag = doReadByte(true);
+
+        if (flag == NULL)
+            return null;
+
+        if (flag != DECIMAL_ARR)
+            throw new PortableException("Invalid flag value: " + flag);
+
+        return doReadDecimalArray(true);
+    }
+
+    /** {@inheritDoc} */
+    @Nullable @Override public String[] readStringArray(String fieldName) throws PortableException {
+        return readStringArray(fieldId(fieldName));
+    }
+
+    /** {@inheritDoc} */
+    @Nullable @Override public String[] readStringArray() throws PortableException {
+        byte flag = doReadByte(true);
+
+        if (flag == NULL)
+            return null;
+
+        if (flag != STRING_ARR)
+            throw new PortableException("Invalid flag value: " + flag);
+
+        return doReadStringArray(true);
+    }
+
+    /** {@inheritDoc} */
+    @Nullable @Override public UUID[] readUuidArray(String fieldName) throws PortableException {
+        return readUuidArray(fieldId(fieldName));
+    }
+
+    /** {@inheritDoc} */
+    @Nullable @Override public UUID[] readUuidArray() throws PortableException {
+        byte flag = doReadByte(true);
+
+        if (flag == NULL)
+            return null;
+
+        if (flag != UUID_ARR)
+            throw new PortableException("Invalid flag value: " + flag);
+
+        return doReadUuidArray(true);
+    }
+
+    /** {@inheritDoc} */
+    @Nullable @Override public Date[] readDateArray(String fieldName) throws PortableException {
+        return readDateArray(fieldId(fieldName));
+    }
+
+    /** {@inheritDoc} */
+    @Nullable @Override public Date[] readDateArray() throws PortableException {
+        byte flag = doReadByte(true);
+
+        if (flag == NULL)
+            return null;
+
+        if (flag != DATE_ARR)
+            throw new PortableException("Invalid flag value: " + flag);
+
+        return doReadDateArray(true);
+    }
+
+    /** {@inheritDoc} */
+    @Nullable @Override public Object[] readObjectArray(String fieldName) throws PortableException {
+        return readObjectArray(fieldId(fieldName));
+    }
+
+    /** {@inheritDoc} */
+    @Nullable @Override public Object[] readObjectArray() throws PortableException {
+        byte flag = doReadByte(true);
+
+        if (flag == NULL)
+            return null;
+
+        if (flag != OBJ_ARR)
+            throw new PortableException("Invalid flag value: " + flag);
+
+        return doReadObjectArray(true, true);
+    }
+
+    /** {@inheritDoc} */
+    @Nullable @Override public <T> Collection<T> readCollection(String fieldName) throws PortableException {
+        return readCollection(fieldId(fieldName), null);
+    }
+
+    /** {@inheritDoc} */
+    @Nullable @Override public <T> Collection<T> readCollection() throws PortableException {
+        byte flag = doReadByte(true);
+
+        if (flag == NULL)
+            return null;
+
+        if (flag != COL)
+            throw new PortableException("Invalid flag value: " + flag);
+
+        return (Collection<T>)doReadCollection(true, true, null);
+    }
+
+    /** {@inheritDoc} */
+    @Nullable @Override public <T> Collection<T> readCollection(String fieldName,
+        Class<? extends Collection<T>> colCls) throws PortableException {
+        return readCollection(fieldId(fieldName), colCls);
+    }
+
+    /** {@inheritDoc} */
+    @Nullable @Override public <T> Collection<T> readCollection(Class<? extends Collection<T>> colCls)
+        throws PortableException {
+        byte flag = doReadByte(true);
+
+        if (flag == NULL)
+            return null;
+
+        if (flag != COL)
+            throw new PortableException("Invalid flag value: " + flag);
+
+        return (Collection<T>)doReadCollection(true, true, colCls);
+    }
+
+    /** {@inheritDoc} */
+    @Nullable @Override public <K, V> Map<K, V> readMap(String fieldName) throws PortableException {
+        return (Map<K, V>)readMap(fieldId(fieldName), null);
+    }
+
+    /** {@inheritDoc} */
+    @Nullable @Override public <K, V> Map<K, V> readMap() throws PortableException {
+        byte flag = doReadByte(true);
+
+        if (flag == NULL)
+            return null;
+
+        if (flag != MAP)
+            throw new PortableException("Invalid flag value: " + flag);
+
+        return (Map<K, V>)doReadMap(true, true, null);
+    }
+
+    /** {@inheritDoc} */
+    @Nullable @Override public <K, V> Map<K, V> readMap(String fieldName, Class<? extends Map<K, V>> mapCls)
+        throws PortableException {
+        return (Map<K, V>)readMap(fieldId(fieldName), mapCls);
+    }
+
+    /** {@inheritDoc} */
+    @Nullable @Override public <K, V> Map<K, V> readMap(Class<? extends Map<K, V>> mapCls)
+        throws PortableException {
+        byte flag = doReadByte(true);
+
+        if (flag == NULL)
+            return null;
+
+        if (flag != MAP)
+            throw new PortableException("Invalid flag value: " + flag);
+
+        return (Map<K, V>)doReadMap(true, true, mapCls);
+    }
+
+    /** {@inheritDoc} */
+    @Nullable @Override public <T extends Enum<?>> T readEnum(String fieldName)
+        throws PortableException {
+        return (T)readEnum(fieldId(fieldName), null);
+    }
+
+    /** {@inheritDoc} */
+    @Nullable @Override public <T extends Enum<?>> T readEnum() throws PortableException {
+        byte flag = doReadByte(true);
+
+        if (flag == NULL)
+            return null;
+
+        if (flag != ENUM)
+            throw new PortableException("Invalid flag value: " + flag);
+
+        Class cls = doReadClass(true);
+
+        return (T)doReadEnum(true, cls);
+    }
+
+    /** {@inheritDoc} */
+    @Nullable @Override public <T extends Enum<?>> T[] readEnumArray(String fieldName)
+        throws PortableException {
+        return (T[])readEnumArray(fieldId(fieldName), null);
+    }
+
+    /** {@inheritDoc} */
+    @Nullable @Override public <T extends Enum<?>> T[] readEnumArray() throws PortableException {
+        byte flag = doReadByte(true);
+
+        if (flag == NULL)
+            return null;
+
+        if (flag != ENUM_ARR)
+            throw new PortableException("Invalid flag value: " + flag);
+
+        Class cls = doReadClass(true);
+
+        return (T[])doReadEnumArray(true, cls);
+    }
+
+    /**
+     * @param fieldName Field name.
+     * @return {@code true} if field is set.
+     */
+    public boolean hasField(String fieldName) {
+        return fieldOffset(fieldId(fieldName)) != -1;
+    }
+
+    /** {@inheritDoc} */
+    @Override public PortableRawReader rawReader() {
+        return this;
+    }
+
+    /**
+     * @param raw Raw flag.
+     * @return Unmarshalled value.
+     * @throws PortableException In case of error.
+     */
+    @Nullable private Object unmarshal(boolean raw) throws PortableException {
+        return unmarshal(raw, false);
+    }
+
+    /**
+     * @param raw Raw flag.
+     * @return Unmarshalled value.
+     * @throws PortableException In case of error.
+     */
+    @Nullable private Object unmarshal(boolean raw, boolean detach) throws PortableException {
+        int start = raw ? rawOff : off;
+
+        byte flag = doReadByte(raw);
+
+        switch (flag) {
+            case NULL:
+                return null;
+
+            case HANDLE:
+                int handle = start - doReadInt(raw);
+
+                PortableObject handledPo = rCtx.getPortableByHandle(handle);
+
+                if (handledPo != null)
+                    return handledPo;
+
+                off = handle;
+
+                return unmarshal(false);
+
+            case OBJ:
+                PortableObjectEx po;
+
+                if (detach) {
+                    in.position(start + GridPortableMarshaller.TOTAL_LEN_POS);
+
+                    int len = in.readInt();
+
+                    in.position(start);
+
+                    po = new PortableObjectImpl(ctx, in.readByteArray(len), 0);
+                }
+                else
+                    po = in.offheapPointer() > 0
+                        ? new PortableObjectOffheapImpl(ctx, in.offheapPointer(), start,
+                                                            in.remaining() + in.position())
+                        : new PortableObjectImpl(ctx, in.array(), start);
+
+                rCtx.setPortableHandler(start, po);
+
+                if (raw)
+                    rawOff = start + po.length();
+                else
+                    off = start + po.length();
+
+                return po;
+
+            case BYTE:
+                return doReadByte(raw);
+
+            case SHORT:
+                return doReadShort(raw);
+
+            case INT:
+                return doReadInt(raw);
+
+            case LONG:
+                return doReadLong(raw);
+
+            case FLOAT:
+                return doReadFloat(raw);
+
+            case DOUBLE:
+                return doReadDouble(raw);
+
+            case CHAR:
+                return doReadChar(raw);
+
+            case BOOLEAN:
+                return doReadBoolean(raw);
+
+            case DECIMAL:
+                return doReadDecimal(raw);
+
+            case STRING:
+                return doReadString(raw);
+
+            case UUID:
+                return doReadUuid(raw);
+
+            case DATE:
+                return isUseTimestamp() ? doReadTimestamp(raw) : doReadDate(raw);
+
+            case BYTE_ARR:
+                return doReadByteArray(raw);
+
+            case SHORT_ARR:
+                return doReadShortArray(raw);
+
+            case INT_ARR:
+                return doReadIntArray(raw);
+
+            case LONG_ARR:
+                return doReadLongArray(raw);
+
+            case FLOAT_ARR:
+                return doReadFloatArray(raw);
+
+            case DOUBLE_ARR:
+                return doReadDoubleArray(raw);
+
+            case CHAR_ARR:
+                return doReadCharArray(raw);
+
+            case BOOLEAN_ARR:
+                return doReadBooleanArray(raw);
+
+            case DECIMAL_ARR:
+                return doReadDecimalArray(raw);
+
+            case STRING_ARR:
+                return doReadStringArray(raw);
+
+            case UUID_ARR:
+                return doReadUuidArray(raw);
+
+            case DATE_ARR:
+                return doReadDateArray(raw);
+
+            case OBJ_ARR:
+                return doReadObjectArray(raw, false);
+
+            case COL:
+                return doReadCollection(raw, false, null);
+
+            case MAP:
+                return doReadMap(raw, false, null);
+
+            case MAP_ENTRY:
+                return doReadMapEntry(raw, false);
+
+            case PORTABLE_OBJ:
+                return doReadPortableObject(raw);
+
+            case ENUM:
+                return doReadEnum(raw, doReadClass(raw));
+
+            case ENUM_ARR:
+                return doReadEnumArray(raw, doReadClass(raw));
+
+            case CLASS:
+                return doReadInt(raw);
+
+            case OPTM_MARSH:
+                int len = doReadInt(true);
+
+                ByteArrayInputStream input = new ByteArrayInputStream(in.array(), in.position(), len);
+
+                Object obj;
+
+                try {
+                    obj = ctx.optimizedMarsh().unmarshal(input, null);
+                }
+                catch (IgniteCheckedException e) {
+                    throw new PortableException("Failed to unmarshal object with optmMarsh marshaller", e);
+                }
+
+                if (raw)
+                    rawOff += len;
+                else
+                    off += len;
+
+                return obj;
+
+
+            default:
+                throw new PortableException("Invalid flag value: " + flag);
+        }
+    }
+
+    /**
+     * @param raw Raw flag.
+     * @return Value.
+     */
+    private byte doReadByte(boolean raw) {
+        in.position(raw ? rawOff++ : off++);
+
+        return in.readByte();
+    }
+
+    /**
+     * @param raw Raw flag.
+     * @return Value.
+     */
+    private short doReadShort(boolean raw) {
+        in.position(raw ? rawOff : off);
+
+        short val = in.readShort();
+
+        if (raw)
+            rawOff += 2;
+        else
+            off += 2;
+
+        return val;
+    }
+
+    /**
+     * @param raw Raw flag.
+     * @return Value.
+     */
+    private int doReadInt(boolean raw) {
+        in.position(raw ? rawOff : off);
+
+        int val = in.readInt();
+
+        if (raw)
+            rawOff += 4;
+        else
+            off += 4;
+
+        return val;
+    }
+
+    /**
+     * @param raw Raw flag.
+     * @return Value.
+     */
+    private long doReadLong(boolean raw) {
+        in.position(raw ? rawOff : off);
+
+        long val = in.readLong();
+
+        if (raw)
+            rawOff += 8;
+        else
+            off += 8;
+
+        return val;
+    }
+
+    /**
+     * @param raw Raw flag.
+     * @return Value.
+     */
+    private float doReadFloat(boolean raw) {
+        in.position(raw ? rawOff : off);
+
+        float val = in.readFloat();
+
+        if (raw)
+            rawOff += 4;
+        else
+            off += 4;
+
+        return val;
+    }
+
+    /**
+     * @param raw Raw flag.
+     * @return Value.
+     */
+    private double doReadDouble(boolean raw) {
+        in.position(raw ? rawOff : off);
+
+        double val = in.readDouble();
+
+        if (raw)
+            rawOff += 8;
+        else
+            off += 8;
+
+        return val;
+    }
+
+    /**
+     * @param raw Raw flag.
+     * @return Value.
+     */
+    private char doReadChar(boolean raw) {
+        in.position(raw ? rawOff : off);
+
+        char val = in.readChar();
+
+        if (raw)
+            rawOff += 2;
+        else
+            off += 2;
+
+        return val;
+    }
+
+    /**
+     * @param raw Raw flag.
+     * @return Value.
+     */
+    private boolean doReadBoolean(boolean raw) {
+        in.position(raw ? rawOff++ : off++);
+
+        return in.readBoolean();
+    }
+
+    /**
+     * @param raw Raw flag.
+     * @return Value.
+     */
+    private BigDecimal doReadDecimal(boolean raw) {
+        int scale = doReadInt(raw);
+        byte[] mag = doReadByteArray(raw);
+
+        BigInteger intVal = new BigInteger(mag);
+
+        if (scale < 0) {
+            scale &= 0x7FFFFFFF;
+
+            intVal = intVal.negate();
+        }
+
+        return new BigDecimal(intVal, scale);
+    }
+
+    /**
+     * @param raw Raw flag.
+     * @return Value.
+     */
+    private String doReadString(boolean raw) {
+        if (doReadBoolean(raw)) {
+            if (!in.hasArray())
+                return new String(doReadByteArray(raw), UTF_8);
+
+            int strLen = doReadInt(raw);
+            int strOff = raw ? rawOff : off;
+
+            String res = new String(in.array(), strOff, strLen, UTF_8);
+
+            if (raw)
+                rawOff += strLen;
+            else
+                off += strLen;
+
+            return res;
+        }
+        else
+            return String.valueOf(doReadCharArray(raw));
+    }
+
+    /**
+     * @param raw Raw flag.
+     * @return Value.
+     */
+    private UUID doReadUuid(boolean raw) {
+        return new UUID(doReadLong(raw), doReadLong(raw));
+    }
+
+    /**
+     * @param raw Raw flag.
+     * @return Value.
+     */
+    private Date doReadDate(boolean raw) {
+        long time = doReadLong(raw);
+
+        // Skip remainder.
+        if (raw)
+            rawOff += 4;
+        else
+            off += 4;
+
+        return new Date(time);
+    }
+
+    /**
+     * @param raw Raw flag.
+     * @return Value.
+     */
+    private Timestamp doReadTimestamp(boolean raw) {
+        long time = doReadLong(raw);
+
+        int nanos = doReadInt(raw);
+
+        Timestamp ts = new Timestamp(time);
+
+        ts.setNanos(ts.getNanos() + nanos);
+
+        return ts;
+    }
+
+    /**
+     * @param raw Raw flag.
+     * @return Object.
+     * @throws PortableException In case of error.
+     */
+    @Nullable private Object doReadObject(boolean raw) throws PortableException {
+        PortableReaderExImpl reader = new PortableReaderExImpl(ctx, in, raw ? rawOff : off, ldr, rCtx);
+
+        Object obj = reader.deserialize();
+
+        if (raw)
+            rawOff += reader.len;
+        else
+            off += reader.len;
+
+        return obj;
+    }
+
+    /**
+     * @return Deserialized object.
+     * @throws PortableException If failed.
+     */
+    @Nullable Object deserialize() throws PortableException {
+        Object obj;
+
+        byte flag = doReadByte(true);
+
+        switch (flag) {
+            case NULL:
+                obj = null;
+
+                break;
+
+            case HANDLE:
+                int handle = start - doReadInt(true);
+
+                obj = rCtx.getObjectByHandle(handle);
+
+                if (obj == null) {
+                    off = handle;
+
+                    obj = doReadObject(false);
+                }
+
+                break;
+
+            case OBJ:
+                if (typeId == null)
+                    readObjectTypeId(true);
+
+                assert typeId != UNREGISTERED_TYPE_ID;
+
+                boolean userType = doReadBoolean(true);
+
+                // Skip typeId and hash code.
+                rawOff += 8;
+
+                desc = ctx.descriptorForTypeId(userType, typeId, ldr);
+
+                len = doReadInt(true);
+
+                rawOff = start + doReadInt(true);
+
+                if (desc == null)
+                    throw new PortableInvalidClassException("Unknown type ID: " + typeId);
+
+                // Skip clsName field if any.
+                rawOff += clsNameLen;
+
+                obj = desc.read(this);
+
+                break;
+
+            case BYTE:
+                obj = doReadByte(true);
+
+                break;
+
+            case SHORT:
+                obj = doReadShort(true);
+
+                break;
+
+            case INT:
+                obj = doReadInt(true);
+
+                break;
+
+            case LONG:
+                obj = doReadLong(true);
+
+                break;
+
+            case FLOAT:
+                obj = doReadFloat(true);
+
+                break;
+
+            case DOUBLE:
+                obj = doReadDouble(true);
+
+                break;
+
+            case CHAR:
+                obj = doReadChar(true);
+
+                break;
+
+            case BOOLEAN:
+                obj = doReadBoolean(true);
+
+                break;
+
+            case DECIMAL:
+                obj = doReadDecimal(true);
+
+                break;
+
+            case STRING:
+                obj = doReadString(true);
+
+                break;
+
+            case UUID:
+                obj = doReadUuid(true);
+
+                break;
+
+            case DATE:
+                obj = isUseTimestamp() ? doReadTimestamp(true) : doReadDate(true);
+
+                break;
+
+            case BYTE_ARR:
+                obj = doReadByteArray(true);
+
+                break;
+
+            case SHORT_ARR:
+                obj = doReadShortArray(true);
+
+                break;
+
+            case INT_ARR:
+                obj = doReadIntArray(true);
+
+                break;
+
+            case LONG_ARR:
+                obj = doReadLongArray(true);
+
+                break;
+
+            case FLOAT_ARR:
+                obj = doReadFloatArray(true);
+
+                break;
+
+            case DOUBLE_ARR:
+                obj = doReadDoubleArray(true);
+
+                break;
+
+            case CHAR_ARR:
+                obj = doReadCharArray(true);
+
+                break;
+
+            case BOOLEAN_ARR:
+                obj = doReadBooleanArray(true);
+
+                break;
+
+            case DECIMAL_ARR:
+                obj = doReadDecimalArray(true);
+
+                break;
+
+            case STRING_ARR:
+                obj = doReadStringArray(true);
+
+                break;
+
+            case UUID_ARR:
+                obj = doReadUuidArray(true);
+
+                break;
+
+            case DATE_ARR:
+                obj = doReadDateArray(true);
+
+                break;
+
+            case OBJ_ARR:
+                obj = doReadObjectArray(true, true);
+
+                break;
+
+            case COL:
+                obj = doReadCollection(true, true, null);
+
+                break;
+
+            case MAP:
+                obj = doReadMap(true, true, null);
+
+                break;
+
+            case MAP_ENTRY:
+                obj = doReadMapEntry(true, true);
+
+                break;
+
+            case PORTABLE_OBJ:
+                obj = doReadPortableObject(true);
+
+                ((PortableObjectImpl)obj).context(ctx);
+
+                if (!GridPortableMarshaller.KEEP_PORTABLES.get())
+                    obj = ((PortableObject)obj).deserialize();
+
+                break;
+
+            case ENUM:
+                obj = doReadEnum(true, doReadClass(true));
+
+                break;
+
+            case ENUM_ARR:
+                obj = doReadEnumArray(true, doReadClass(true));
+
+                break;
+
+            case CLASS:
+                obj = doReadClass(true);
+
+                break;
+
+            case OPTM_MARSH:
+                int len = doReadInt(true);
+
+                ByteArrayInputStream input = new ByteArrayInputStream(in.array(), in.position(), len);
+
+                try {
+                    obj = ctx.optimizedMarsh().unmarshal(input, null);
+                }
+                catch (IgniteCheckedException e) {
+                    throw new PortableException("Failed to unmarshal object with optimized marshaller", e);
+                }
+
+                rawOff += len;
+
+                break;
+
+            default:
+                throw new PortableException("Invalid flag value: " + flag);
+        }
+
+        if (len == 0)
+            len = rawOff - start;
+
+        return obj;
+    }
+
+    /**
+     * @return Use timestamp flag.
+     * @throws PortableInvalidClassException If fails to find object type descriptor.
+     */
+    private boolean isUseTimestamp() throws PortableInvalidClassException {
+        in.position(start);
+
+        boolean dateObj = in.readByte() == DATE;
+
+        if (!dateObj) {
+            in.position(start + 2);
+
+            int typeId = in.readInt(start + 2);
+
+            return ctx.isUseTimestamp(typeId);
+        }
+
+        return ctx.isUseTimestamp();
+    }
+
+    /**
+     * @param raw Raw flag.
+     * @return Value.
+     */
+    private byte[] doReadByteArray(boolean raw) {
+        int len = doReadInt(raw);
+
+        in.position(raw ? rawOff : off);
+
+        byte[] arr = in.readByteArray(len);
+
+        if (raw)
+            rawOff += len;
+        else
+            off += len;
+
+        return arr;
+    }
+
+    /**
+     * @param raw Raw flag.
+     * @return Value.
+     */
+    private short[] doReadShortArray(boolean raw) {
+        int len = doReadInt(raw);
+
+        in.position(raw ? rawOff : off);
+
+        short[] arr = in.readShortArray(len);
+
+        int bytes = len << 1;
+
+        if (raw)
+            rawOff += bytes;
+        else
+            off += bytes;
+
+        return arr;
+    }
+
+    /**
+     * @param raw Raw flag.
+     * @return Value.
+     */
+    private int[] doReadIntArray(boolean raw) {
+        int len = doReadInt(raw);
+
+        in.position(raw ? rawOff : off);
+
+        int[] arr = in.readIntArray(len);
+
+        int bytes = len << 2;
+
+        if (raw)
+            rawOff += bytes;
+        else
+            off += bytes;
+
+        return arr;
+    }
+
+    /**
+     * @param raw Raw flag.
+     * @return Value.
+     */
+    private long[] doReadLongArray(boolean raw) {
+        int len = doReadInt(raw);
+
+        in.position(raw ? rawOff : off);
+
+        long[] arr = in.readLongArray(len);
+
+        int bytes = len << 3;
+
+        if (raw)
+            rawOff += bytes;
+        else
+            off += bytes;
+
+        return arr;
+    }
+
+    /**
+     * @param raw Raw flag.
+     * @return Value.
+     */
+    private float[] doReadFloatArray(boolean raw) {
+        int len = doReadInt(raw);
+
+        in.position(raw ? rawOff : off);
+
+        float[] arr = in.readFloatArray(len);
+
+        int bytes = len << 2;
+
+        if (raw)
+            rawOff += bytes;
+        else
+            off += bytes;
+
+        return arr;
+    }
+
+    /**
+     * @param raw Raw flag.
+     * @return Value.
+     */
+    private double[] doReadDoubleArray(boolean raw) {
+        int len = doReadInt(raw);
+
+        in.position(raw ? rawOff : off);
+
+        double[] arr = in.readDoubleArray(len);
+
+        int bytes = len << 3;
+
+        if (raw)
+            rawOff += bytes;
+        else
+            off += bytes;
+
+        return arr;
+    }
+
+    /**
+     * @param raw Raw flag.
+     * @return Value.
+     */
+    private char[] doReadCharArray(boolean raw) {
+        int len = doReadInt(raw);
+
+        in.position(raw ? rawOff : off);
+
+        char[] arr = in.readCharArray(len);
+
+        int bytes = len << 1;
+
+        if (raw)
+            rawOff += bytes;
+        else
+            off += bytes;
+
+        return arr;
+    }
+
+    /**
+     * @param raw Raw flag.
+     * @return Value.
+     */
+    private boolean[] doReadBooleanArray(boolean raw) {
+        int len = doReadInt(raw);
+
+        in.position(raw ? rawOff : off);
+
+        boolean[] arr = in.readBooleanArray(len);
+
+        if (raw)
+            rawOff += len;
+        else
+            off += len;
+
+        return arr;
+    }
+
+    /**
+     * @param raw Raw flag.
+     * @return Value.
+     * @throws PortableException In case of error.
+     */
+    private BigDecimal[] doReadDecimalArray(boolean raw) throws PortableException {
+        int len = doReadInt(raw);
+
+        BigDecimal[] arr = new BigDecimal[len];
+
+        for (int i = 0; i < len; i++) {
+            byte flag = doReadByte(raw);
+
+            if (flag == NULL)
+                arr[i] = null;
+            else {
+                if (flag != DECIMAL)
+                    throw new PortableException("Invalid flag value: " + flag);
+
+                arr[i] = doReadDecimal(raw);
+            }
+        }
+
+        return arr;
+    }
+
+    /**
+     * @param raw Raw flag.
+     * @return Value.
+     * @throws PortableException In case of error.
+     */
+    private String[] doReadStringArray(boolean raw) throws PortableException {
+        int len = doReadInt(raw);
+
+        String[] arr = new String[len];
+
+        for (int i = 0; i < len; i++) {
+            byte flag = doReadByte(raw);
+
+            if (flag == NULL)
+                arr[i] = null;
+            else {
+                if (flag != STRING)
+                    throw new PortableException("Invalid flag value: " + flag);
+
+                arr[i] = doReadString(raw);
+            }
+        }
+
+        return arr;
+    }
+
+    /**
+     * @param raw Raw flag.
+     * @return Value.
+     * @throws PortableException In case of error.
+     */
+    private UUID[] doReadUuidArray(boolean raw) throws PortableException {
+        int len = doReadInt(raw);
+
+        UUID[] arr = new UUID[len];
+
+        for (int i = 0; i < len; i++) {
+            byte flag = doReadByte(raw);
+
+            if (flag == NULL)
+                arr[i] = null;
+            else {
+                if (flag != UUID)
+                    throw new PortableException("Invalid flag value: " + flag);
+
+                arr[i] = doReadUuid(raw);
+            }
+        }
+
+        return arr;
+    }
+
+    /**
+     * @param raw Raw flag.
+     * @return Value.
+     * @throws PortableException In case of error.
+     */
+    private Date[] doReadDateArray(boolean raw) throws PortableException {
+        int len = doReadInt(raw);
+
+        Date[] arr = new Date[len];
+
+        for (int i = 0; i < len; i++) {
+            byte flag = doReadByte(raw);
+
+            if (flag == NULL)
+                arr[i] = null;
+            else {
+                if (flag != DATE)
+                    throw new PortableException("Invalid flag value: " + flag);
+
+                arr[i] = doReadDate(raw);
+            }
+        }
+
+        return arr;
+    }
+
+    /**
+     * @param raw Raw flag.
+     * @param deep Deep flag.
+     * @return Value.
+     * @throws PortableException In case of error.
+     */
+    private Object[] doReadObjectArray(boolean raw, boolean deep) throws PortableException {
+        Class compType = doReadClass(raw);
+
+        int len = doReadInt(raw);
+
+        Object[] arr = deep ? (Object[])Array.newInstance(compType, len) : new Object[len];
+
+        for (int i = 0; i < len; i++)
+            arr[i] = deep ? doReadObject(raw) : unmarshal(raw);
+
+        return arr;
+    }
+
+    /**
+     * @param raw Raw flag.
+     * @param deep Deep flag.
+     * @param cls Collection class.
+     * @return Value.
+     * @throws PortableException In case of error.
+     */
+    @SuppressWarnings("unchecked")
+    private Collection<?> doReadCollection(boolean raw, boolean deep, @Nullable Class<? extends Collection> cls)
+        throws PortableException {
+        int size = doReadInt(raw);
+
+        assert size >= 0;
+
+        byte colType = doReadByte(raw);
+
+        Collection<Object> col;
+
+        if (cls != null) {
+            try {
+                Constructor<? extends Collection> cons = cls.getConstructor();
+
+                col = cons.newInstance();
+            }
+            catch (NoSuchMethodException ignored) {
+                throw new PortableException("Collection class doesn't have public default constructor: " +
+                    cls.getName());
+            }
+            catch (InvocationTargetException | InstantiationException | IllegalAccessException e) {
+                throw new PortableException("Failed to instantiate collection: " + cls.getName(), e);
+            }
+        }
+        else {
+            switch (colType) {
+                case ARR_LIST:
+                    col = new ArrayList<>(size);
+
+                    break;
+
+                case LINKED_LIST:
+                    col = new LinkedList<>();
+
+                    break;
+
+                case HASH_SET:
+                    col = U.newHashSet(size);
+
+                    break;
+
+                case LINKED_HASH_SET:
+                    col = U.newLinkedHashSet(size);
+
+                    break;
+
+                case TREE_SET:
+                    col = new TreeSet<>();
+
+                    break;
+
+                case CONC_SKIP_LIST_SET:
+                    col = new ConcurrentSkipListSet<>();
+
+                    break;
+
+                case USER_SET:
+                    col = U.newHashSet(size);
+
+                    break;
+
+                case USER_COL:
+                    col = new ArrayList<>(size);
+
+                    break;
+
+                default:
+                    throw new PortableException("Invalid collection type: " + colType);
+            }
+        }
+
+        for (int i = 0; i < size; i++)
+            col.add(deep ? doReadObject(raw) : unmarshal(raw));
+
+        return col;
+    }
+
+    /**
+     * @param raw Raw flag.
+     * @param deep Deep flag.
+     * @param cls Map class.
+     * @return Value.
+     * @throws PortableException In case of error.
+     */
+    @SuppressWarnings("unchecked")
+    private Map<?, ?> doReadMap(boolean raw, boolean deep, @Nullable Class<? extends Map> cls)
+        throws PortableException {
+        int size = doReadInt(raw);
+
+        assert size >= 0;
+
+        byte mapType = doReadByte(raw);
+
+        Map<Object, Object> map;
+
+        if (cls != null) {
+            try {
+                Constructor<? extends Map> cons = cls.getConstructor();
+
+                map = cons.newInstance();
+            }
+            catch (NoSuchMethodException ignored) {
+                throw new PortableException("Map class doesn't have public default constructor: " +
+                    cls.getName());
+            }
+            catch (InvocationTargetException | InstantiationException | IllegalAccessException e) {
+                throw new PortableException("Failed to instantiate map: " + cls.getName(), e);
+            }
+        }
+        else {
+            switch (mapType) {
+                case HASH_MAP:
+                    map = U.newHashMap(size);
+
+                    break;
+
+                case LINKED_HASH_MAP:
+                    map = U.newLinkedHashMap(size);
+
+                    break;
+
+                case TREE_MAP:
+                    map = new TreeMap<>();
+
+                    break;
+
+                case CONC_HASH_MAP:
+                    map = new ConcurrentHashMap<>(size);
+
+                    break;
+
+                case USER_COL:
+                    map = U.newHashMap(size);
+
+                    break;
+
+                case PROPERTIES_MAP:
+                    map = new Properties();
+
+                    break;
+
+                default:
+                    throw new PortableException("Invalid map type: " + mapType);
+            }
+        }
+
+        for (int i = 0; i < size; i++)
+            map.put(deep ? doReadObject(raw) : unmarshal(raw), deep ? doReadObject(raw) : unmarshal(raw));
+
+        return map;
+    }
+
+    /**
+     * @param raw Raw flag.
+     * @param deep Deep flag.
+     * @return Value.
+     * @throws PortableException In case of error.
+     */
+    private Map.Entry<?, ?> doReadMapEntry(boolean raw, boolean deep) throws PortableException {
+        Object val1 = deep ? doReadObject(raw) : unmarshal(raw);
+        Object val2 = deep ? doReadObject(raw) : unmarshal(raw);
+
+        return new GridMapEntry<>(val1, val2);
+    }
+
+    /**
+     * @param raw Raw flag.
+     * @return Value.
+     */
+    private PortableObject doReadPortableObject(boolean raw) {
+        if (in.offheapPointer() > 0) {
+            int len = doReadInt(raw);
+
+            int pos = raw ? rawOff : off;
+
+            if (raw)
+                rawOff += len;
+            else
+                off += len;
+
+            int start = doReadInt(raw);
+
+            return new PortableObjectOffheapImpl(ctx, in.offheapPointer() + pos, start, len);
+        }
+        else {
+            byte[] arr = doReadByteArray(raw);
+            int start = doReadInt(raw);
+
+            return new PortableObjectImpl(ctx, arr, start);
+        }
+    }
+
+    /**
+     * @param raw Raw flag.
+     * @param cls Enum class.
+     * @return Value.
+     */
+    private Enum<?> doReadEnum(boolean raw, Class<?> cls) throws PortableException {
+        if (!cls.isEnum())
+            throw new PortableException("Class does not represent enum type: " + cls.getName());
+
+        int ord = doReadInt(raw);
+
+        return ord >= 0 ? (Enum<?>)GridEnumCache.get(cls)[ord] : null;
+    }
+
+    /**
+     * @param raw Raw flag.
+     * @param cls Enum class.
+     * @return Value.
+     */
+    private Object[] doReadEnumArray(boolean raw, Class<?> cls) throws PortableException {
+        int len = doReadInt(raw);
+
+        Object[] arr = (Object[])Array.newInstance(cls, len);
+
+        for (int i = 0; i < len; i++) {
+            byte flag = doReadByte(raw);
+
+            if (flag == NULL)
+                arr[i] = null;
+            else
+                arr[i] = doReadEnum(raw, doReadClass(raw));
+        }
+
+        return arr;
+    }
+
+    /**
+     * @param raw Raw flag.
+     * @return Value.
+     */
+    private Class doReadClass(boolean raw) throws PortableException {
+        return doReadClass(raw, doReadInt(raw));
+    }
+
+    /**
+     * @param raw Raw flag.
+     * @param typeId Type id.
+     * @return Value.
+     */
+    private Class doReadClass(boolean raw, int typeId) throws PortableException {
+        Class cls;
+
+        if (typeId == OBJECT_TYPE_ID)
+            return Object.class;
+
+        if (typeId != UNREGISTERED_TYPE_ID)
+            cls = ctx.descriptorForTypeId(true, typeId, ldr).describedClass();
+        else {
+            byte flag = doReadByte(raw);
+
+            if (flag != STRING)
+                throw new PortableException("No class definition for typeId: " + typeId);
+
+            String clsName = doReadString(raw);
+
+            try {
+                cls = U.forName(clsName, ldr);
+            }
+            catch (ClassNotFoundException e) {
+                throw new PortableInvalidClassException("Failed to load the class: " + clsName, e);
+            }
+
+            // forces registering of class by type id, at least locally
+            ctx.descriptorForClass(cls);
+        }
+
+        return cls;
+    }
+
+    /**
+     * @param name Field name.
+     * @return Field offset.
+     */
+    private int fieldId(String name) {
+        assert name != null;
+
+        if (typeId == null)
+            readObjectTypeId(false);
+
+        assert typeId != UNREGISTERED_TYPE_ID;
+
+        return ctx.fieldId(typeId, name);
+    }
+
+    /**
+     * @param id Field ID.
+     * @return Field offset.
+     */
+    private int fieldOffset(int id) {
+        assert hdrLen != 0;
+
+        int off = start + hdrLen;
+
+        int end = start + in.readInt(start + RAW_DATA_OFF_POS);
+
+        while (true) {
+            if (off >= end)
+                return -1;
+
+            int id0 = in.readInt(off);
+
+            if (id0 == id)
+                return off + 8;
+
+            int len = in.readInt(off + 4);
+
+            off += (8 + len);
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override public int readUnsignedByte() throws IOException {
+        return readByte() & 0xff;
+    }
+
+    /** {@inheritDoc} */
+    @Override public int readUnsignedShort() throws IOException {
+        return readShort() & 0xffff;
+    }
+
+    /** {@inheritDoc} */
+    @Override public String readLine() throws IOException {
+        SB sb = new SB();
+
+        int b;
+
+        while ((b = read()) >= 0) {
+            char c = (char)b;
+
+            switch (c) {
+                case '\n':
+                    return sb.toString();
+
+                case '\r':
+                    b = read();
+
+                    if (b < 0 || b == '\n')
+                        return sb.toString();
+                    else
+                        sb.a((char)b);
+
+                    break;
+
+                default:
+                    sb.a(c);
+            }
+        }
+
+        return sb.toString();
+    }
+
+    /** {@inheritDoc} */
+    @NotNull @Override public String readUTF() throws IOException {
+        return readString();
+    }
+
+    /** {@inheritDoc} */
+    @Override public void readFully(byte[] b) throws IOException {
+        readFully(b, 0, b.length);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void readFully(byte[] b, int off, int len) throws IOException {
+        in.position(rawOff);
+
+        int cnt = in.read(b, off, len);
+
+        if (cnt < len)
+            throw new EOFException();
+
+        rawOff += len;
+    }
+
+    /** {@inheritDoc} */
+    @Override public int skipBytes(int n) throws IOException {
+        int toSkip = Math.min(in.remaining(), n);
+
+        in.position(in.position() + toSkip);
+
+        rawOff += toSkip;
+
+        return toSkip;
+    }
+
+    /** {@inheritDoc} */
+    @Override public int read() throws IOException {
+        return readByte();
+    }
+
+    /** {@inheritDoc} */
+    @Override public int read(byte[] b) throws IOException {
+        return read(b, 0, b.length);
+    }
+
+    /** {@inheritDoc} */
+    @Override public int read(byte[] b, int off, int len) throws IOException {
+        in.position(rawOff);
+
+        int cnt = in.read(b, off, len);
+
+        rawOff += len;
+
+        return cnt;
+    }
+
+    /** {@inheritDoc} */
+    @Override public long skip(long n) throws IOException {
+        return skipBytes((int)n);
+    }
+
+    /** {@inheritDoc} */
+    @Override public int available() throws IOException {
+        return in.remaining();
+    }
+
+    /** {@inheritDoc} */
+    @Override public void close() throws IOException {
+        // No-op.
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableThreadLocalMemoryAllocator.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableThreadLocalMemoryAllocator.java b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableThreadLocalMemoryAllocator.java
new file mode 100644
index 0000000..f3b3739
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableThreadLocalMemoryAllocator.java
@@ -0,0 +1,163 @@
+/*
+ * 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.portable;
+
+import org.apache.ignite.internal.portable.streams.*;
+import org.apache.ignite.internal.util.*;
+import org.apache.ignite.internal.util.typedef.internal.*;
+
+import sun.misc.*;
+
+import static org.apache.ignite.IgniteSystemProperties.*;
+
+/**
+ * Thread-local memory allocator.
+ */
+public class PortableThreadLocalMemoryAllocator implements PortableMemoryAllocator {
+    /** Memory allocator instance. */
+    public static final PortableThreadLocalMemoryAllocator THREAD_LOCAL_ALLOC =
+        new PortableThreadLocalMemoryAllocator();
+
+    /** Holders. */
+    private static final ThreadLocal<ByteArrayHolder> holders = new ThreadLocal<>();
+
+    /** Unsafe instance. */
+    protected static final Unsafe UNSAFE = GridUnsafe.unsafe();
+
+    /** Array offset: byte. */
+    protected static final long BYTE_ARR_OFF = UNSAFE.arrayBaseOffset(byte[].class);
+
+    /**
+     * Ensures singleton.
+     */
+    private PortableThreadLocalMemoryAllocator() {
+        // No-op.
+    }
+
+    /** {@inheritDoc} */
+    @Override public byte[] allocate(int size) {
+        ByteArrayHolder holder = holders.get();
+
+        if (holder == null)
+            holders.set(holder = new ByteArrayHolder());
+
+        if (holder.acquired)
+            return new byte[size];
+
+        holder.acquired = true;
+
+        if (holder.data == null || size > holder.data.length)
+            holder.data = new byte[size];
+
+        return holder.data;
+    }
+
+    /** {@inheritDoc} */
+    @Override public byte[] reallocate(byte[] data, int size) {
+        ByteArrayHolder holder = holders.get();
+
+        assert holder != null;
+
+        byte[] newData = new byte[size];
+
+        if (holder.data == data)
+            holder.data = newData;
+
+        UNSAFE.copyMemory(data, BYTE_ARR_OFF, newData, BYTE_ARR_OFF, data.length);
+
+        return newData;
+    }
+
+    /** {@inheritDoc} */
+    @Override public void release(byte[] data, int maxMsgSize) {
+        ByteArrayHolder holder = holders.get();
+
+        assert holder != null;
+
+        if (holder.data != data)
+            return;
+
+        holder.maxMsgSize = maxMsgSize;
+        holder.acquired = false;
+
+        holder.shrink();
+    }
+
+    /** {@inheritDoc} */
+    @Override public long allocateDirect(int size) {
+        return 0;
+    }
+
+    /** {@inheritDoc} */
+    @Override public long reallocateDirect(long addr, int size) {
+        return 0;
+    }
+
+    /** {@inheritDoc} */
+    @Override public void releaseDirect(long addr) {
+        // No-op
+    }
+
+    /**
+     * Checks whether a thread-local array is acquired or not.
+     * The function is used by Unit tests.
+     *
+     * @return {@code true} if acquired {@code false} otherwise.
+     */
+    public boolean isThreadLocalArrayAcquired() {
+        ByteArrayHolder holder = holders.get();
+
+        return holder != null && holder.acquired;
+    }
+
+    /**
+     * Thread-local byte array holder.
+     */
+    private static class ByteArrayHolder {
+        /** */
+        private static final Long CHECK_FREQ = Long.getLong(IGNITE_MARSHAL_BUFFERS_RECHECK, 10000);
+
+        /** Data array */
+        private byte[] data;
+
+        /** Max message size detected between checks. */
+        private int maxMsgSize;
+
+        /** Last time array size is checked. */
+        private long lastCheck = U.currentTimeMillis();
+
+        /** Whether the holder is acquired or not. */
+        private boolean acquired;
+
+        /**
+         * Shrinks array size if needed.
+         */
+        private void shrink() {
+            long now = U.currentTimeMillis();
+
+            if (now - lastCheck >= CHECK_FREQ) {
+                int halfSize = data.length >> 1;
+
+                if (maxMsgSize < halfSize)
+                    data = new byte[halfSize];
+
+                lastCheck = now;
+            }
+        }
+    }
+}
\ No newline at end of file


[17/59] [abbrv] ignite git commit: Minor changes to PortablePrimitives.

Posted by vk...@apache.org.
Minor changes to PortablePrimitives.


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

Branch: refs/heads/ignite-884
Commit: 14718f9645eafcb1e7c3b7349e705251250bfc89
Parents: 3fbb99c
Author: vozerov-gridgain <vo...@gridgain.com>
Authored: Tue Aug 25 12:31:26 2015 +0300
Committer: vozerov-gridgain <vo...@gridgain.com>
Committed: Tue Aug 25 12:31:26 2015 +0300

----------------------------------------------------------------------
 .../internal/portable/PortablePrimitives.java   | 196 +++++++++----------
 1 file changed, 98 insertions(+), 98 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/14718f96/modules/core/src/main/java/org/apache/ignite/internal/portable/PortablePrimitives.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/portable/PortablePrimitives.java b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortablePrimitives.java
index 10f3479..ce29458 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/portable/PortablePrimitives.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortablePrimitives.java
@@ -26,7 +26,7 @@ import static java.nio.ByteOrder.*;
 /**
  * Primitives writer.
  */
-abstract class PortablePrimitives {
+public abstract class PortablePrimitives {
     /** */
     private static final PortablePrimitives INSTANCE =
         nativeOrder() == LITTLE_ENDIAN ? new UnsafePrimitives() : new BytePrimitives();
@@ -34,7 +34,7 @@ abstract class PortablePrimitives {
     /**
      * @return Primitives writer.
      */
-    static PortablePrimitives get() {
+    public static PortablePrimitives get() {
         return INSTANCE;
     }
 
@@ -43,224 +43,224 @@ abstract class PortablePrimitives {
      * @param off Offset.
      * @param val Value.
      */
-    abstract void writeByte(byte[] arr, int off, byte val);
+    public abstract void writeByte(byte[] arr, int off, byte val);
 
     /**
      * @param arr Array.
      * @param off Offset.
      * @return Value.
      */
-    abstract byte readByte(byte[] arr, int off);
+    public abstract byte readByte(byte[] arr, int off);
 
     /**
      * @param arr Array.
      * @param off Offset.
      * @param val Value.
      */
-    abstract void writeShort(byte[] arr, int off, short val);
+    public abstract void writeShort(byte[] arr, int off, short val);
 
     /**
      * @param arr Array.
      * @param off Offset.
      * @return Value.
      */
-    abstract short readShort(byte[] arr, int off);
+    public abstract short readShort(byte[] arr, int off);
 
     /**
      * @param arr Array.
      * @param off Offset.
      * @param val Value.
      */
-    abstract void writeInt(byte[] arr, int off, int val);
+    public abstract void writeInt(byte[] arr, int off, int val);
 
     /**
      * @param arr Array.
      * @param off Offset.
      * @return Value.
      */
-    abstract int readInt(byte[] arr, int off);
+    public abstract int readInt(byte[] arr, int off);
 
     /**
      * @param arr Array.
      * @param off Offset.
      * @param val Value.
      */
-    abstract void writeLong(byte[] arr, int off, long val);
+    public abstract void writeLong(byte[] arr, int off, long val);
 
     /**
      * @param arr Array.
      * @param off Offset.
      * @return Value.
      */
-    abstract long readLong(byte[] arr, int off);
+    public abstract long readLong(byte[] arr, int off);
 
     /**
      * @param arr Array.
      * @param off Offset.
      * @param val Value.
      */
-    abstract void writeFloat(byte[] arr, int off, float val);
+    public abstract void writeFloat(byte[] arr, int off, float val);
 
     /**
      * @param arr Array.
      * @param off Offset.
      * @return Value.
      */
-    abstract float readFloat(byte[] arr, int off);
+    public abstract float readFloat(byte[] arr, int off);
 
     /**
      * @param arr Array.
      * @param off Offset.
      * @param val Value.
      */
-    abstract void writeDouble(byte[] arr, int off, double val);
+    public abstract void writeDouble(byte[] arr, int off, double val);
 
     /**
      * @param arr Array.
      * @param off Offset.
      * @return Value.
      */
-    abstract double readDouble(byte[] arr, int off);
+    public abstract double readDouble(byte[] arr, int off);
 
     /**
      * @param arr Array.
      * @param off Offset.
      * @param val Value.
      */
-    abstract void writeChar(byte[] arr, int off, char val);
+    public abstract void writeChar(byte[] arr, int off, char val);
 
     /**
      * @param arr Array.
      * @param off Offset.
      * @return Value.
      */
-    abstract char readChar(byte[] arr, int off);
+    public abstract char readChar(byte[] arr, int off);
 
     /**
      * @param arr Array.
      * @param off Offset.
      * @param val Value.
      */
-    abstract void writeBoolean(byte[] arr, int off, boolean val);
+    public abstract void writeBoolean(byte[] arr, int off, boolean val);
 
     /**
      * @param arr Array.
      * @param off Offset.
      * @return Value.
      */
-    abstract boolean readBoolean(byte[] arr, int off);
+    public abstract boolean readBoolean(byte[] arr, int off);
 
     /**
      * @param arr Array.
      * @param off Offset.
      * @param val Value.
      */
-    abstract void writeByteArray(byte[] arr, int off, byte[] val);
+    public abstract void writeByteArray(byte[] arr, int off, byte[] val);
 
     /**
      * @param arr Array.
      * @param off Offset.
      * @return Value.
      */
-    abstract byte[] readByteArray(byte[] arr, int off, int len);
+    public abstract byte[] readByteArray(byte[] arr, int off, int len);
 
     /**
      * @param arr Array.
      * @param off Offset.
      * @param val Value.
      */
-    abstract void writeShortArray(byte[] arr, int off, short[] val);
+    public abstract void writeShortArray(byte[] arr, int off, short[] val);
 
     /**
      * @param arr Array.
      * @param off Offset.
      * @return Value.
      */
-    abstract short[] readShortArray(byte[] arr, int off, int len);
+    public abstract short[] readShortArray(byte[] arr, int off, int len);
 
     /**
      * @param arr Array.
      * @param off Offset.
      * @param val Value.
      */
-    abstract void writeIntArray(byte[] arr, int off, int[] val);
+    public abstract void writeIntArray(byte[] arr, int off, int[] val);
 
     /**
      * @param arr Array.
      * @param off Offset.
      * @return Value.
      */
-    abstract int[] readIntArray(byte[] arr, int off, int len);
+    public abstract int[] readIntArray(byte[] arr, int off, int len);
 
     /**
      * @param arr Array.
      * @param off Offset.
      * @param val Value.
      */
-    abstract void writeLongArray(byte[] arr, int off, long[] val);
+    public abstract void writeLongArray(byte[] arr, int off, long[] val);
 
     /**
      * @param arr Array.
      * @param off Offset.
      * @return Value.
      */
-    abstract long[] readLongArray(byte[] arr, int off, int len);
+    public abstract long[] readLongArray(byte[] arr, int off, int len);
 
     /**
      * @param arr Array.
      * @param off Offset.
      * @param val Value.
      */
-    abstract void writeFloatArray(byte[] arr, int off, float[] val);
+    public abstract void writeFloatArray(byte[] arr, int off, float[] val);
 
     /**
      * @param arr Array.
      * @param off Offset.
      * @return Value.
      */
-    abstract float[] readFloatArray(byte[] arr, int off, int len);
+    public abstract float[] readFloatArray(byte[] arr, int off, int len);
 
     /**
      * @param arr Array.
      * @param off Offset.
      * @param val Value.
      */
-    abstract void writeDoubleArray(byte[] arr, int off, double[] val);
+    public abstract void writeDoubleArray(byte[] arr, int off, double[] val);
 
     /**
      * @param arr Array.
      * @param off Offset.
      * @return Value.
      */
-    abstract double[] readDoubleArray(byte[] arr, int off, int len);
+    public abstract double[] readDoubleArray(byte[] arr, int off, int len);
 
     /**
      * @param arr Array.
      * @param off Offset.
      * @param val Value.
      */
-    abstract void writeCharArray(byte[] arr, int off, char[] val);
+    public abstract void writeCharArray(byte[] arr, int off, char[] val);
 
     /**
      * @param arr Array.
      * @param off Offset.
      * @return Value.
      */
-    abstract char[] readCharArray(byte[] arr, int off, int len);
+    public abstract char[] readCharArray(byte[] arr, int off, int len);
 
     /**
      * @param arr Array.
      * @param off Offset.
      * @param val Value.
      */
-    abstract void writeBooleanArray(byte[] arr, int off, boolean[] val);
+    public abstract void writeBooleanArray(byte[] arr, int off, boolean[] val);
 
     /**
      * @param arr Array.
      * @param off Offset.
      * @return Value.
      */
-    abstract boolean[] readBooleanArray(byte[] arr, int off, int len);
+    public abstract boolean[] readBooleanArray(byte[] arr, int off, int len);
 
     /** */
     private static class UnsafePrimitives extends PortablePrimitives {
@@ -292,92 +292,92 @@ abstract class PortablePrimitives {
         private static final long BOOLEAN_ARR_OFF = UNSAFE.arrayBaseOffset(boolean[].class);
 
         /** {@inheritDoc} */
-        @Override void writeByte(byte[] arr, int off, byte val) {
+        @Override public void writeByte(byte[] arr, int off, byte val) {
             UNSAFE.putByte(arr, BYTE_ARR_OFF + off, val);
         }
 
         /** {@inheritDoc} */
-        @Override byte readByte(byte[] arr, int off) {
+        @Override public byte readByte(byte[] arr, int off) {
             return UNSAFE.getByte(arr, BYTE_ARR_OFF + off);
         }
 
         /** {@inheritDoc} */
-        @Override void writeShort(byte[] arr, int off, short val) {
+        @Override public void writeShort(byte[] arr, int off, short val) {
             UNSAFE.putShort(arr, BYTE_ARR_OFF + off, val);
         }
 
         /** {@inheritDoc} */
-        @Override short readShort(byte[] arr, int off) {
+        @Override public short readShort(byte[] arr, int off) {
             return UNSAFE.getShort(arr, BYTE_ARR_OFF + off);
         }
 
         /** {@inheritDoc} */
-        @Override void writeInt(byte[] arr, int off, int val) {
+        @Override public void writeInt(byte[] arr, int off, int val) {
             UNSAFE.putInt(arr, BYTE_ARR_OFF + off, val);
         }
 
         /** {@inheritDoc} */
-        @Override int readInt(byte[] arr, int off) {
+        @Override public int readInt(byte[] arr, int off) {
             return UNSAFE.getInt(arr, BYTE_ARR_OFF + off);
         }
 
         /** {@inheritDoc} */
-        @Override void writeLong(byte[] arr, int off, long val) {
+        @Override public void writeLong(byte[] arr, int off, long val) {
             UNSAFE.putLong(arr, BYTE_ARR_OFF + off, val);
         }
 
         /** {@inheritDoc} */
-        @Override long readLong(byte[] arr, int off) {
+        @Override public long readLong(byte[] arr, int off) {
             return UNSAFE.getLong(arr, BYTE_ARR_OFF + off);
         }
 
         /** {@inheritDoc} */
-        @Override void writeFloat(byte[] arr, int off, float val) {
+        @Override public void writeFloat(byte[] arr, int off, float val) {
             UNSAFE.putFloat(arr, BYTE_ARR_OFF + off, val);
         }
 
         /** {@inheritDoc} */
-        @Override float readFloat(byte[] arr, int off) {
+        @Override public float readFloat(byte[] arr, int off) {
             return UNSAFE.getFloat(arr, BYTE_ARR_OFF + off);
         }
 
         /** {@inheritDoc} */
-        @Override void writeDouble(byte[] arr, int off, double val) {
+        @Override public void writeDouble(byte[] arr, int off, double val) {
             UNSAFE.putDouble(arr, BYTE_ARR_OFF + off, val);
         }
 
         /** {@inheritDoc} */
-        @Override double readDouble(byte[] arr, int off) {
+        @Override public double readDouble(byte[] arr, int off) {
             return UNSAFE.getDouble(arr, BYTE_ARR_OFF + off);
         }
 
         /** {@inheritDoc} */
-        @Override void writeChar(byte[] arr, int off, char val) {
+        @Override public void writeChar(byte[] arr, int off, char val) {
             UNSAFE.putChar(arr, BYTE_ARR_OFF + off, val);
         }
 
         /** {@inheritDoc} */
-        @Override char readChar(byte[] arr, int off) {
+        @Override public char readChar(byte[] arr, int off) {
             return UNSAFE.getChar(arr, BYTE_ARR_OFF + off);
         }
 
         /** {@inheritDoc} */
-        @Override void writeBoolean(byte[] arr, int off, boolean val) {
+        @Override public void writeBoolean(byte[] arr, int off, boolean val) {
             UNSAFE.putBoolean(arr, BYTE_ARR_OFF + off, val);
         }
 
         /** {@inheritDoc} */
-        @Override boolean readBoolean(byte[] arr, int off) {
+        @Override public boolean readBoolean(byte[] arr, int off) {
             return UNSAFE.getBoolean(arr, BYTE_ARR_OFF + off);
         }
 
         /** {@inheritDoc} */
-        @Override void writeByteArray(byte[] arr, int off, byte[] val) {
+        @Override public void writeByteArray(byte[] arr, int off, byte[] val) {
             UNSAFE.copyMemory(val, BYTE_ARR_OFF, arr, BYTE_ARR_OFF + off, val.length);
         }
 
         /** {@inheritDoc} */
-        @Override byte[] readByteArray(byte[] arr, int off, int len) {
+        @Override public byte[] readByteArray(byte[] arr, int off, int len) {
             byte[] arr0 = new byte[len];
 
             UNSAFE.copyMemory(arr, BYTE_ARR_OFF + off, arr0, BYTE_ARR_OFF, len);
@@ -386,12 +386,12 @@ abstract class PortablePrimitives {
         }
 
         /** {@inheritDoc} */
-        @Override void writeShortArray(byte[] arr, int off, short[] val) {
+        @Override public void writeShortArray(byte[] arr, int off, short[] val) {
             UNSAFE.copyMemory(val, SHORT_ARR_OFF, arr, BYTE_ARR_OFF + off, val.length << 1);
         }
 
         /** {@inheritDoc} */
-        @Override short[] readShortArray(byte[] arr, int off, int len) {
+        @Override public short[] readShortArray(byte[] arr, int off, int len) {
             short[] arr0 = new short[len];
 
             UNSAFE.copyMemory(arr, BYTE_ARR_OFF + off, arr0, SHORT_ARR_OFF, len << 1);
@@ -400,12 +400,12 @@ abstract class PortablePrimitives {
         }
 
         /** {@inheritDoc} */
-        @Override void writeIntArray(byte[] arr, int off, int[] val) {
+        @Override public void writeIntArray(byte[] arr, int off, int[] val) {
             UNSAFE.copyMemory(val, INT_ARR_OFF, arr, BYTE_ARR_OFF + off, val.length << 2);
         }
 
         /** {@inheritDoc} */
-        @Override int[] readIntArray(byte[] arr, int off, int len) {
+        @Override public int[] readIntArray(byte[] arr, int off, int len) {
             int[] arr0 = new int[len];
 
             UNSAFE.copyMemory(arr, BYTE_ARR_OFF + off, arr0, INT_ARR_OFF, len << 2);
@@ -414,12 +414,12 @@ abstract class PortablePrimitives {
         }
 
         /** {@inheritDoc} */
-        @Override void writeLongArray(byte[] arr, int off, long[] val) {
+        @Override public void writeLongArray(byte[] arr, int off, long[] val) {
             UNSAFE.copyMemory(val, LONG_ARR_OFF, arr, BYTE_ARR_OFF + off, val.length << 3);
         }
 
         /** {@inheritDoc} */
-        @Override long[] readLongArray(byte[] arr, int off, int len) {
+        @Override public long[] readLongArray(byte[] arr, int off, int len) {
             long[] arr0 = new long[len];
 
             UNSAFE.copyMemory(arr, BYTE_ARR_OFF + off, arr0, LONG_ARR_OFF, len << 3);
@@ -428,12 +428,12 @@ abstract class PortablePrimitives {
         }
 
         /** {@inheritDoc} */
-        @Override void writeFloatArray(byte[] arr, int off, float[] val) {
+        @Override public void writeFloatArray(byte[] arr, int off, float[] val) {
             UNSAFE.copyMemory(val, FLOAT_ARR_OFF, arr, BYTE_ARR_OFF + off, val.length << 2);
         }
 
         /** {@inheritDoc} */
-        @Override float[] readFloatArray(byte[] arr, int off, int len) {
+        @Override public float[] readFloatArray(byte[] arr, int off, int len) {
             float[] arr0 = new float[len];
 
             UNSAFE.copyMemory(arr, BYTE_ARR_OFF + off, arr0, FLOAT_ARR_OFF, len << 2);
@@ -442,12 +442,12 @@ abstract class PortablePrimitives {
         }
 
         /** {@inheritDoc} */
-        @Override void writeDoubleArray(byte[] arr, int off, double[] val) {
+        @Override public void writeDoubleArray(byte[] arr, int off, double[] val) {
             UNSAFE.copyMemory(val, DOUBLE_ARR_OFF, arr, BYTE_ARR_OFF + off, val.length << 3);
         }
 
         /** {@inheritDoc} */
-        @Override double[] readDoubleArray(byte[] arr, int off, int len) {
+        @Override public double[] readDoubleArray(byte[] arr, int off, int len) {
             double[] arr0 = new double[len];
 
             UNSAFE.copyMemory(arr, BYTE_ARR_OFF + off, arr0, DOUBLE_ARR_OFF, len << 3);
@@ -456,12 +456,12 @@ abstract class PortablePrimitives {
         }
 
         /** {@inheritDoc} */
-        @Override void writeCharArray(byte[] arr, int off, char[] val) {
+        @Override public void writeCharArray(byte[] arr, int off, char[] val) {
             UNSAFE.copyMemory(val, CHAR_ARR_OFF, arr, BYTE_ARR_OFF + off, val.length << 1);
         }
 
         /** {@inheritDoc} */
-        @Override char[] readCharArray(byte[] arr, int off, int len) {
+        @Override public char[] readCharArray(byte[] arr, int off, int len) {
             char[] arr0 = new char[len];
 
             UNSAFE.copyMemory(arr, BYTE_ARR_OFF + off, arr0, CHAR_ARR_OFF, len << 1);
@@ -470,12 +470,12 @@ abstract class PortablePrimitives {
         }
 
         /** {@inheritDoc} */
-        @Override void writeBooleanArray(byte[] arr, int off, boolean[] val) {
+        @Override public void writeBooleanArray(byte[] arr, int off, boolean[] val) {
             UNSAFE.copyMemory(val, BOOLEAN_ARR_OFF, arr, BYTE_ARR_OFF + off, val.length);
         }
 
         /** {@inheritDoc} */
-        @Override boolean[] readBooleanArray(byte[] arr, int off, int len) {
+        @Override public boolean[] readBooleanArray(byte[] arr, int off, int len) {
             boolean[] arr0 = new boolean[len];
 
             UNSAFE.copyMemory(arr, BYTE_ARR_OFF + off, arr0, BOOLEAN_ARR_OFF, len);
@@ -487,23 +487,23 @@ abstract class PortablePrimitives {
     /** */
     private static class BytePrimitives extends PortablePrimitives {
         /** {@inheritDoc} */
-        @Override void writeByte(byte[] arr, int off, byte val) {
+        @Override public void writeByte(byte[] arr, int off, byte val) {
             arr[off] = val;
         }
 
         /** {@inheritDoc} */
-        @Override byte readByte(byte[] arr, int off) {
+        @Override public byte readByte(byte[] arr, int off) {
             return arr[off];
         }
 
         /** {@inheritDoc} */
-        @Override void writeShort(byte[] arr, int off, short val) {
+        @Override public void writeShort(byte[] arr, int off, short val) {
             arr[off++] = (byte)(val & 0xff);
             arr[off] = (byte)((val >>> 8) & 0xff);
         }
 
         /** {@inheritDoc} */
-        @Override short readShort(byte[] arr, int off) {
+        @Override public short readShort(byte[] arr, int off) {
             short val = 0;
 
             val |= (arr[off++] & 0xff);
@@ -513,7 +513,7 @@ abstract class PortablePrimitives {
         }
 
         /** {@inheritDoc} */
-        @Override void writeInt(byte[] arr, int off, int val) {
+        @Override public void writeInt(byte[] arr, int off, int val) {
             arr[off++] = (byte)(val & 0xff);
             arr[off++] = (byte)((val >>> 8) & 0xff);
             arr[off++] = (byte)((val >>> 16) & 0xff);
@@ -521,7 +521,7 @@ abstract class PortablePrimitives {
         }
 
         /** {@inheritDoc} */
-        @Override int readInt(byte[] arr, int off) {
+        @Override public int readInt(byte[] arr, int off) {
             int val = 0;
 
             val |= (arr[off++] & 0xff);
@@ -533,7 +533,7 @@ abstract class PortablePrimitives {
         }
 
         /** {@inheritDoc} */
-        @Override void writeLong(byte[] arr, int off, long val) {
+        @Override public void writeLong(byte[] arr, int off, long val) {
             arr[off++] = (byte)(val & 0xffL);
             arr[off++] = (byte)((val >>> 8) & 0xffL);
             arr[off++] = (byte)((val >>> 16) & 0xffL);
@@ -545,7 +545,7 @@ abstract class PortablePrimitives {
         }
 
         /** {@inheritDoc} */
-        @Override long readLong(byte[] arr, int off) {
+        @Override public long readLong(byte[] arr, int off) {
             long val = 0;
 
             val |= (arr[off++] & 0xffL);
@@ -561,33 +561,33 @@ abstract class PortablePrimitives {
         }
 
         /** {@inheritDoc} */
-        @Override void writeFloat(byte[] arr, int off, float val) {
+        @Override public void writeFloat(byte[] arr, int off, float val) {
             writeInt(arr, off, Float.floatToIntBits(val));
         }
 
         /** {@inheritDoc} */
-        @Override float readFloat(byte[] arr, int off) {
+        @Override public float readFloat(byte[] arr, int off) {
             return Float.intBitsToFloat(readInt(arr, off));
         }
 
         /** {@inheritDoc} */
-        @Override void writeDouble(byte[] arr, int off, double val) {
+        @Override public void writeDouble(byte[] arr, int off, double val) {
             writeLong(arr, off, Double.doubleToLongBits(val));
         }
 
         /** {@inheritDoc} */
-        @Override double readDouble(byte[] arr, int off) {
+        @Override public double readDouble(byte[] arr, int off) {
             return Double.longBitsToDouble(readLong(arr, off));
         }
 
         /** {@inheritDoc} */
-        @Override void writeChar(byte[] arr, int off, char val) {
+        @Override public void writeChar(byte[] arr, int off, char val) {
             arr[off++] = (byte)(val & 0xff);
             arr[off] = (byte)((val >>> 8) & 0xff);
         }
 
         /** {@inheritDoc} */
-        @Override char readChar(byte[] arr, int off) {
+        @Override public char readChar(byte[] arr, int off) {
             char val = 0;
 
             val |= (arr[off++] & 0xff);
@@ -597,23 +597,23 @@ abstract class PortablePrimitives {
         }
 
         /** {@inheritDoc} */
-        @Override void writeBoolean(byte[] arr, int off, boolean val) {
+        @Override public void writeBoolean(byte[] arr, int off, boolean val) {
             arr[off] = (byte)(val ? 1 : 0);
         }
 
         /** {@inheritDoc} */
-        @Override boolean readBoolean(byte[] arr, int off) {
+        @Override public boolean readBoolean(byte[] arr, int off) {
             return arr[off] != 0;
         }
 
         /** {@inheritDoc} */
-        @Override void writeByteArray(byte[] arr, int off, byte[] val) {
+        @Override public void writeByteArray(byte[] arr, int off, byte[] val) {
             for (byte b : val)
                 arr[off++] = b;
         }
 
         /** {@inheritDoc} */
-        @Override byte[] readByteArray(byte[] arr, int off, int len) {
+        @Override public byte[] readByteArray(byte[] arr, int off, int len) {
             byte[] val = new byte[len];
 
             for (int i = 0; i < len; i++)
@@ -623,7 +623,7 @@ abstract class PortablePrimitives {
         }
 
         /** {@inheritDoc} */
-        @Override void writeShortArray(byte[] arr, int off, short[] val) {
+        @Override public void writeShortArray(byte[] arr, int off, short[] val) {
             for (short s : val) {
                 writeShort(arr, off, s);
 
@@ -632,7 +632,7 @@ abstract class PortablePrimitives {
         }
 
         /** {@inheritDoc} */
-        @Override short[] readShortArray(byte[] arr, int off, int len) {
+        @Override public short[] readShortArray(byte[] arr, int off, int len) {
             short[] val = new short[len];
 
             for (int i = 0; i < len; i++) {
@@ -645,7 +645,7 @@ abstract class PortablePrimitives {
         }
 
         /** {@inheritDoc} */
-        @Override void writeIntArray(byte[] arr, int off, int[] val) {
+        @Override public void writeIntArray(byte[] arr, int off, int[] val) {
             for (int i : val) {
                 writeInt(arr, off, i);
 
@@ -654,7 +654,7 @@ abstract class PortablePrimitives {
         }
 
         /** {@inheritDoc} */
-        @Override int[] readIntArray(byte[] arr, int off, int len) {
+        @Override public int[] readIntArray(byte[] arr, int off, int len) {
             int[] val = new int[len];
 
             for (int i = 0; i < len; i++) {
@@ -667,7 +667,7 @@ abstract class PortablePrimitives {
         }
 
         /** {@inheritDoc} */
-        @Override void writeLongArray(byte[] arr, int off, long[] val) {
+        @Override public void writeLongArray(byte[] arr, int off, long[] val) {
             for (long l : val) {
                 writeLong(arr, off, l);
 
@@ -676,7 +676,7 @@ abstract class PortablePrimitives {
         }
 
         /** {@inheritDoc} */
-        @Override long[] readLongArray(byte[] arr, int off, int len) {
+        @Override public long[] readLongArray(byte[] arr, int off, int len) {
             long[] val = new long[len];
 
             for (int i = 0; i < len; i++) {
@@ -689,7 +689,7 @@ abstract class PortablePrimitives {
         }
 
         /** {@inheritDoc} */
-        @Override void writeFloatArray(byte[] arr, int off, float[] val) {
+        @Override public void writeFloatArray(byte[] arr, int off, float[] val) {
             for (float f : val) {
                 writeFloat(arr, off, f);
 
@@ -698,7 +698,7 @@ abstract class PortablePrimitives {
         }
 
         /** {@inheritDoc} */
-        @Override float[] readFloatArray(byte[] arr, int off, int len) {
+        @Override public float[] readFloatArray(byte[] arr, int off, int len) {
             float[] val = new float[len];
 
             for (int i = 0; i < len; i++) {
@@ -711,7 +711,7 @@ abstract class PortablePrimitives {
         }
 
         /** {@inheritDoc} */
-        @Override void writeDoubleArray(byte[] arr, int off, double[] val) {
+        @Override public void writeDoubleArray(byte[] arr, int off, double[] val) {
             for (double d : val) {
                 writeDouble(arr, off, d);
 
@@ -720,7 +720,7 @@ abstract class PortablePrimitives {
         }
 
         /** {@inheritDoc} */
-        @Override double[] readDoubleArray(byte[] arr, int off, int len) {
+        @Override public double[] readDoubleArray(byte[] arr, int off, int len) {
             double[] val = new double[len];
 
             for (int i = 0; i < len; i++) {
@@ -733,7 +733,7 @@ abstract class PortablePrimitives {
         }
 
         /** {@inheritDoc} */
-        @Override void writeCharArray(byte[] arr, int off, char[] val) {
+        @Override public void writeCharArray(byte[] arr, int off, char[] val) {
             for (char c : val) {
                 writeChar(arr, off, c);
 
@@ -742,7 +742,7 @@ abstract class PortablePrimitives {
         }
 
         /** {@inheritDoc} */
-        @Override char[] readCharArray(byte[] arr, int off, int len) {
+        @Override public char[] readCharArray(byte[] arr, int off, int len) {
             char[] val = new char[len];
 
             for (int i = 0; i < len; i++) {
@@ -755,13 +755,13 @@ abstract class PortablePrimitives {
         }
 
         /** {@inheritDoc} */
-        @Override void writeBooleanArray(byte[] arr, int off, boolean[] val) {
+        @Override public void writeBooleanArray(byte[] arr, int off, boolean[] val) {
             for (boolean b : val)
                 writeBoolean(arr, off++, b);
         }
 
         /** {@inheritDoc} */
-        @Override boolean[] readBooleanArray(byte[] arr, int off, int len) {
+        @Override public boolean[] readBooleanArray(byte[] arr, int off, int len) {
             boolean[] val = new boolean[len];
 
             for (int i = 0; i < len; i++)


[50/59] [abbrv] ignite git commit: IGNITE-1308: Moved regular (not continuous!) queries to Ignite.

Posted by vk...@apache.org.
IGNITE-1308: Moved regular (not continuous!) queries to Ignite.


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

Branch: refs/heads/ignite-884
Commit: 8529e10855e71c63c4fc5a83a9cdb2300109bb19
Parents: 975f47e
Author: vozerov-gridgain <vo...@gridgain.com>
Authored: Wed Aug 26 15:43:34 2015 +0300
Committer: vozerov-gridgain <vo...@gridgain.com>
Committed: Wed Aug 26 15:43:34 2015 +0300

----------------------------------------------------------------------
 .../query/PlatformAbstractQueryCursor.java      | 192 +++++++++++++++++++
 .../cache/query/PlatformFieldsQueryCursor.java  |  50 +++++
 .../cache/query/PlatformQueryCursor.java        |  46 +++++
 3 files changed, 288 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/8529e108/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/cache/query/PlatformAbstractQueryCursor.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/cache/query/PlatformAbstractQueryCursor.java b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/cache/query/PlatformAbstractQueryCursor.java
new file mode 100644
index 0000000..cdd29fd
--- /dev/null
+++ b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/cache/query/PlatformAbstractQueryCursor.java
@@ -0,0 +1,192 @@
+/*
+ * 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.platform.cache.query;
+
+import org.apache.ignite.*;
+import org.apache.ignite.internal.portable.*;
+import org.apache.ignite.internal.processors.cache.query.*;
+import org.apache.ignite.internal.processors.platform.*;
+import org.apache.ignite.internal.processors.platform.utils.*;
+
+import java.util.*;
+
+/**
+ *
+ */
+public abstract class PlatformAbstractQueryCursor<T> extends PlatformAbstractTarget implements AutoCloseable {
+    /** Get multiple entries. */
+    private static final int OP_GET_ALL = 1;
+
+    /** Get all entries. */
+    private static final int OP_GET_BATCH = 2;
+
+    /** Get single entry. */
+    private static final int OP_GET_SINGLE = 3;
+
+    /** Underlying cursor. */
+    private final QueryCursorEx<T> cursor;
+
+    /** Batch size size. */
+    private final int batchSize;
+
+    /** Underlying iterator. */
+    private Iterator<T> iter;
+
+    /**
+     * Constructor.
+     *
+     * @param interopCtx Interop context.
+     * @param cursor Underlying cursor.
+     * @param batchSize Batch size.
+     */
+    public PlatformAbstractQueryCursor(PlatformContext interopCtx, QueryCursorEx<T> cursor, int batchSize) {
+        super(interopCtx);
+
+        this.cursor = cursor;
+        this.batchSize = batchSize;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void processOutOp(int type, final PortableRawWriterEx writer) throws IgniteCheckedException {
+        switch (type) {
+            case OP_GET_BATCH: {
+                assert iter != null : "iterator() has not been called";
+
+                try {
+                    int cntPos = writer.reserveInt();
+
+                    int cnt;
+
+                    for (cnt = 0; cnt < batchSize; cnt++) {
+                        if (iter.hasNext())
+                            write(writer, iter.next());
+                        else
+                            break;
+                    }
+
+                    writer.writeInt(cntPos, cnt);
+                }
+                catch (Exception err) {
+                    throw PlatformUtils.unwrapQueryException(err);
+                }
+
+                break;
+            }
+
+            case OP_GET_SINGLE: {
+                assert iter != null : "iterator() has not been called";
+
+                try {
+                    if (iter.hasNext()) {
+                        write(writer, iter.next());
+
+                        return;
+                    }
+                }
+                catch (Exception err) {
+                    throw PlatformUtils.unwrapQueryException(err);
+                }
+
+                throw new IgniteCheckedException("No more data available.");
+            }
+
+            case OP_GET_ALL: {
+                try {
+                    int pos = writer.reserveInt();
+
+                    Consumer<T> consumer = new Consumer<>(this, writer);
+
+                    cursor.getAll(consumer);
+
+                    writer.writeInt(pos, consumer.cnt);
+                }
+                catch (Exception err) {
+                    throw PlatformUtils.unwrapQueryException(err);
+                }
+
+                break;
+            }
+
+            default:
+                throwUnsupported(type);
+        }
+    }
+
+    /**
+     * Get cursor iterator.
+     */
+    public void iterator() {
+        iter = cursor.iterator();
+    }
+
+    /**
+     * Check whether next iterator entry exists.
+     *
+     * @return {@code True} if exists.
+     */
+    @SuppressWarnings("UnusedDeclaration")
+    public boolean iteratorHasNext() {
+        assert iter != null : "iterator() has not been called";
+
+        return iter.hasNext();
+    }
+
+    /** {@inheritDoc} */
+    @Override public void close() throws Exception {
+        cursor.close();
+    }
+
+    /**
+     * Write value to the stream. Extension point to perform conversions on the object before writing it.
+     *
+     * @param writer Writer.
+     * @param val Value.
+     */
+    protected abstract void write(PortableRawWriterEx writer, T val);
+
+    /**
+     * Query cursor consumer.
+     */
+    private static class Consumer<T> implements QueryCursorEx.Consumer<T> {
+        /** Current query cursor. */
+        private final PlatformAbstractQueryCursor<T> cursor;
+
+        /** Writer. */
+        private final PortableRawWriterEx writer;
+
+        /** Count. */
+        private int cnt;
+
+        /**
+         * Constructor.
+         *
+         * @param writer Writer.
+         */
+        public Consumer(PlatformAbstractQueryCursor<T> cursor, PortableRawWriterEx writer) {
+            this.cursor = cursor;
+            this.writer = writer;
+        }
+
+        /** {@inheritDoc} */
+        @Override public void consume(T val) throws IgniteCheckedException {
+            cursor.write(writer, val);
+
+            cnt++;
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/8529e108/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/cache/query/PlatformFieldsQueryCursor.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/cache/query/PlatformFieldsQueryCursor.java b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/cache/query/PlatformFieldsQueryCursor.java
new file mode 100644
index 0000000..f18a79a
--- /dev/null
+++ b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/cache/query/PlatformFieldsQueryCursor.java
@@ -0,0 +1,50 @@
+/*
+ * 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.platform.cache.query;
+
+import org.apache.ignite.internal.portable.*;
+import org.apache.ignite.internal.processors.cache.query.*;
+import org.apache.ignite.internal.processors.platform.*;
+
+import java.util.*;
+
+/**
+ * Interop cursor for fields query.
+ */
+public class PlatformFieldsQueryCursor extends PlatformAbstractQueryCursor<List<?>> {
+    /**
+     * Constructor.
+     *
+     * @param interopCtx Interop context.
+     * @param cursor Backing cursor.
+     * @param batchSize Batch size.
+     */
+    public PlatformFieldsQueryCursor(PlatformContext interopCtx, QueryCursorEx<List<?>> cursor, int batchSize) {
+        super(interopCtx, cursor, batchSize);
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void write(PortableRawWriterEx writer, List vals) {
+        assert vals != null;
+
+        writer.writeInt(vals.size());
+
+        for (Object val : vals)
+            writer.writeObjectDetached(val);
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/8529e108/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/cache/query/PlatformQueryCursor.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/cache/query/PlatformQueryCursor.java b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/cache/query/PlatformQueryCursor.java
new file mode 100644
index 0000000..cc96d6f
--- /dev/null
+++ b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/cache/query/PlatformQueryCursor.java
@@ -0,0 +1,46 @@
+/*
+ * 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.platform.cache.query;
+
+import org.apache.ignite.internal.portable.*;
+import org.apache.ignite.internal.processors.cache.query.*;
+import org.apache.ignite.internal.processors.platform.*;
+
+import javax.cache.*;
+
+/**
+ * Interop cursor for regular queries.
+ */
+public class PlatformQueryCursor extends PlatformAbstractQueryCursor<Cache.Entry> {
+    /**
+     * Constructor.
+     *
+     * @param interopCtx Interop context.
+     * @param cursor Backing cursor.
+     * @param batchSize Batch size.
+     */
+    public PlatformQueryCursor(PlatformContext interopCtx, QueryCursorEx<Cache.Entry> cursor, int batchSize) {
+        super(interopCtx, cursor, batchSize);
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void write(PortableRawWriterEx writer, Cache.Entry val) {
+        writer.writeObjectDetached(val.getKey());
+        writer.writeObjectDetached(val.getValue());
+    }
+}


[28/59] [abbrv] ignite git commit: Moving platform utility closures to Ignite.

Posted by vk...@apache.org.
Moving platform utility closures to Ignite.


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

Branch: refs/heads/ignite-884
Commit: c47a7061f042f60a73fd9014091e98b2c656bfb4
Parents: 2e6d915
Author: vozerov-gridgain <vo...@gridgain.com>
Authored: Wed Aug 26 09:13:45 2015 +0300
Committer: vozerov-gridgain <vo...@gridgain.com>
Committed: Wed Aug 26 09:13:45 2015 +0300

----------------------------------------------------------------------
 .../platform/utils/PlatformReaderBiClosure.java | 34 ++++++++++++++++++++
 .../platform/utils/PlatformReaderClosure.java   | 34 ++++++++++++++++++++
 .../platform/utils/PlatformWriterBiClosure.java | 34 ++++++++++++++++++++
 .../platform/utils/PlatformWriterClosure.java   | 33 +++++++++++++++++++
 4 files changed, 135 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/c47a7061/modules/platform/src/main/java/org/apache/ignite/internal/platform/utils/PlatformReaderBiClosure.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/platform/utils/PlatformReaderBiClosure.java b/modules/platform/src/main/java/org/apache/ignite/internal/platform/utils/PlatformReaderBiClosure.java
new file mode 100644
index 0000000..0280ba8
--- /dev/null
+++ b/modules/platform/src/main/java/org/apache/ignite/internal/platform/utils/PlatformReaderBiClosure.java
@@ -0,0 +1,34 @@
+/*
+ * 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.platform.utils;
+
+import org.apache.ignite.internal.portable.*;
+import org.apache.ignite.lang.*;
+
+/**
+ * Reader bi-closure.
+ */
+public interface PlatformReaderBiClosure<T1, T2> {
+    /**
+     * Read object from reader.
+     *
+     * @param reader Reader.
+     * @return Object.
+     */
+    IgniteBiTuple<T1, T2> read(PortableRawReaderEx reader);
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/c47a7061/modules/platform/src/main/java/org/apache/ignite/internal/platform/utils/PlatformReaderClosure.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/platform/utils/PlatformReaderClosure.java b/modules/platform/src/main/java/org/apache/ignite/internal/platform/utils/PlatformReaderClosure.java
new file mode 100644
index 0000000..73a24d1
--- /dev/null
+++ b/modules/platform/src/main/java/org/apache/ignite/internal/platform/utils/PlatformReaderClosure.java
@@ -0,0 +1,34 @@
+/*
+ * 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.platform.utils;
+
+import org.apache.ignite.internal.portable.*;
+
+/**
+ * Reader closure.
+ */
+public interface PlatformReaderClosure<T> {
+
+    /**
+     * Read object from reader.
+     *
+     * @param reader Reader.
+     * @return Object.
+     */
+    T read(PortableRawReaderEx reader);
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/c47a7061/modules/platform/src/main/java/org/apache/ignite/internal/platform/utils/PlatformWriterBiClosure.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/platform/utils/PlatformWriterBiClosure.java b/modules/platform/src/main/java/org/apache/ignite/internal/platform/utils/PlatformWriterBiClosure.java
new file mode 100644
index 0000000..cbd34fa
--- /dev/null
+++ b/modules/platform/src/main/java/org/apache/ignite/internal/platform/utils/PlatformWriterBiClosure.java
@@ -0,0 +1,34 @@
+/*
+ * 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.platform.utils;
+
+import org.apache.ignite.internal.portable.*;
+
+/**
+ * Interop writer bi-closure.
+ */
+public interface PlatformWriterBiClosure<T1, T2> {
+    /**
+     * Write values.
+     *
+     * @param writer Writer.
+     * @param val1 Value 1.
+     * @param val2 Value 2.
+     */
+    public void write(PortableRawWriterEx writer, T1 val1, T2 val2);
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/c47a7061/modules/platform/src/main/java/org/apache/ignite/internal/platform/utils/PlatformWriterClosure.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/platform/utils/PlatformWriterClosure.java b/modules/platform/src/main/java/org/apache/ignite/internal/platform/utils/PlatformWriterClosure.java
new file mode 100644
index 0000000..d9953ca
--- /dev/null
+++ b/modules/platform/src/main/java/org/apache/ignite/internal/platform/utils/PlatformWriterClosure.java
@@ -0,0 +1,33 @@
+/*
+ * 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.platform.utils;
+
+import org.apache.ignite.internal.portable.*;
+
+/**
+ * Interop writer closure.
+ */
+public interface PlatformWriterClosure<T> {
+    /**
+     * Write value.
+     *
+     * @param writer Writer.
+     * @param val Value.
+     */
+    public void write(PortableRawWriterEx writer, T val);
+}


[55/59] [abbrv] ignite git commit: Platforms: moved several cache store classes to Ignite.

Posted by vk...@apache.org.
Platforms: moved several cache store classes to Ignite.


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

Branch: refs/heads/ignite-884
Commit: 2938a9b4a06b0e0a9f19625ce1b168e4a4a2f87d
Parents: 536af49
Author: vozerov-gridgain <vo...@gridgain.com>
Authored: Wed Aug 26 17:11:46 2015 +0300
Committer: vozerov-gridgain <vo...@gridgain.com>
Committed: Wed Aug 26 17:11:46 2015 +0300

----------------------------------------------------------------------
 .../cache/store/PlatformCacheStore.java         | 25 ++++++++
 .../cache/store/PlatformCacheStoreCallback.java | 61 ++++++++++++++++++++
 2 files changed, 86 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/2938a9b4/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/cache/store/PlatformCacheStore.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/cache/store/PlatformCacheStore.java b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/cache/store/PlatformCacheStore.java
new file mode 100644
index 0000000..6e0c1d9
--- /dev/null
+++ b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/cache/store/PlatformCacheStore.java
@@ -0,0 +1,25 @@
+/*
+ * 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.platform.cache.store;
+
+/**
+ * Marker interface denoting that this instance is platform cache store.
+ */
+public interface PlatformCacheStore {
+    // No-op.
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/2938a9b4/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/cache/store/PlatformCacheStoreCallback.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/cache/store/PlatformCacheStoreCallback.java b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/cache/store/PlatformCacheStoreCallback.java
new file mode 100644
index 0000000..32e0ab7
--- /dev/null
+++ b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/cache/store/PlatformCacheStoreCallback.java
@@ -0,0 +1,61 @@
+/*
+ * 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.platform.cache.store;
+
+import org.apache.ignite.internal.portable.*;
+import org.apache.ignite.internal.processors.platform.*;
+import org.apache.ignite.internal.processors.platform.memory.*;
+
+/**
+ * Platform cache store callback.
+ */
+public abstract class PlatformCacheStoreCallback {
+    /** Context. */
+    protected final PlatformContext ctx;
+
+    /**
+     * Constructor.
+     *
+     * @param ctx Context.
+     */
+    protected PlatformCacheStoreCallback(PlatformContext ctx) {
+        this.ctx = ctx;
+    }
+
+    /**
+     * Invoke the callback.
+     *
+     * @param memPtr Memory pointer.
+     */
+    public void invoke(long memPtr) {
+        if (memPtr > 0) {
+            try (PlatformMemory mem = ctx.memory().get(memPtr)) {
+                PortableRawReaderEx reader = ctx.reader(mem);
+
+                invoke0(reader);
+            }
+        }
+    }
+
+    /**
+     * Internal invoke routine.
+     *
+     * @param reader Reader.
+     */
+    protected abstract void invoke0(PortableRawReaderEx reader);
+}


[26/59] [abbrv] ignite git commit: IGNITE-1269. ignite-hadoop assembly needs to include ignite-indexing

Posted by vk...@apache.org.
IGNITE-1269. ignite-hadoop assembly needs to include ignite-indexing

Signed-off-by: Konstantin Boudnik <co...@wandisco.com>


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

Branch: refs/heads/ignite-884
Commit: 21cff74e081308fb2ed94b115419ed46c2bc6a77
Parents: 89e94b6
Author: iveselovskiy <iv...@gridgain.com>
Authored: Thu Aug 20 18:48:31 2015 +0300
Committer: Konstantin Boudnik <co...@wandisco.com>
Committed: Tue Aug 25 20:06:11 2015 -0700

----------------------------------------------------------------------
 assembly/dependencies-hadoop.xml | 1 +
 1 file changed, 1 insertion(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/21cff74e/assembly/dependencies-hadoop.xml
----------------------------------------------------------------------
diff --git a/assembly/dependencies-hadoop.xml b/assembly/dependencies-hadoop.xml
index 4638643..0e282a4 100644
--- a/assembly/dependencies-hadoop.xml
+++ b/assembly/dependencies-hadoop.xml
@@ -34,6 +34,7 @@
             <includes>
                 <include>org.apache.ignite:ignite-spring</include>
                 <include>org.apache.ignite:ignite-log4j</include>
+                <include>org.apache.ignite:ignite-indexing</include>
             </includes>
             <sources>
                 <includeModuleDirectory>true</includeModuleDirectory>


[29/59] [abbrv] ignite git commit: Moving platform classes to "...internal.processors..." package to follow Ignite common approach.

Posted by vk...@apache.org.
http://git-wip-us.apache.org/repos/asf/ignite/blob/2225f8d2/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/utils/PlatformWriterClosure.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/utils/PlatformWriterClosure.java b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/utils/PlatformWriterClosure.java
new file mode 100644
index 0000000..697335e
--- /dev/null
+++ b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/utils/PlatformWriterClosure.java
@@ -0,0 +1,33 @@
+/*
+ * 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.platform.utils;
+
+import org.apache.ignite.internal.portable.*;
+
+/**
+ * Interop writer closure.
+ */
+public interface PlatformWriterClosure<T> {
+    /**
+     * Write value.
+     *
+     * @param writer Writer.
+     * @param val Value.
+     */
+    public void write(PortableRawWriterEx writer, T val);
+}


[49/59] [abbrv] ignite git commit: Merge remote-tracking branch 'origin/master'

Posted by vk...@apache.org.
Merge remote-tracking branch 'origin/master'


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

Branch: refs/heads/ignite-884
Commit: c9a5340e0e6a261f68bf352dfce27853d6125239
Parents: 7ad43fc 975f47e
Author: sboikov <sb...@gridgain.com>
Authored: Wed Aug 26 15:41:48 2015 +0300
Committer: sboikov <sb...@gridgain.com>
Committed: Wed Aug 26 15:41:48 2015 +0300

----------------------------------------------------------------------
 .../internal/portable/PortableContext.java      |   1 -
 .../internal/processors/igfs/IgfsProcessor.java |   8 -
 .../processors/igfs/IgfsAbstractSelfTest.java   |  34 +-
 .../igfs/IgfsBackupFailoverSelfTest.java        | 488 ++++++++++++++++
 .../igfs/IgfsBackupsDualAsyncSelfTest.java      |  40 ++
 .../igfs/IgfsBackupsDualSyncSelfTest.java       |  40 ++
 .../igfs/IgfsBackupsPrimarySelfTest.java        |  40 ++
 .../ignite/testsuites/IgniteIgfsTestSuite.java  |   7 +
 .../Apache.Ignite.Core.csproj                   |   3 +
 .../Apache.Ignite.Core/Impl/Handle/Handle.cs    |  69 +++
 .../Impl/Handle/HandleRegistry.cs               | 340 +++++++++++
 .../Apache.Ignite.Core/Impl/Handle/IHandle.cs   |  35 ++
 .../platform/PlatformAbstractBootstrap.java     |   1 +
 .../platform/PlatformAbstractTarget.java        | 276 +++++++++
 .../processors/platform/PlatformContext.java    | 114 ++++
 .../platform/PlatformExtendedException.java     |  39 ++
 .../processors/platform/PlatformTarget.java     |  76 +++
 .../lifecycle/PlatformLifecycleBean.java        |  72 +++
 .../transactions/PlatformTransactions.java      | 255 ++++++++
 .../platform/utils/PlatformFutureUtils.java     | 326 +++++++++++
 .../platform/utils/PlatformUtils.java           | 585 +++++++++++++++++++
 parent/pom.xml                                  |   1 +
 22 files changed, 2835 insertions(+), 15 deletions(-)
----------------------------------------------------------------------



[22/59] [abbrv] ignite git commit: Minor fixes to examples

Posted by vk...@apache.org.
Minor fixes to examples


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

Branch: refs/heads/ignite-884
Commit: 2c86d60f526588056c828ac11a3ba81b6568b4e6
Parents: e5358de
Author: Yakov Zhdanov <yz...@gridgain.com>
Authored: Tue Aug 25 16:56:14 2015 +0300
Committer: Yakov Zhdanov <yz...@gridgain.com>
Committed: Tue Aug 25 16:56:14 2015 +0300

----------------------------------------------------------------------
 .../ignite/examples/igfs/IgfsMapReduceExample.java     |  3 +++
 .../ignite/examples/servicegrid/ServicesExample.java   | 13 ++++++++++---
 2 files changed, 13 insertions(+), 3 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/2c86d60f/examples/src/main/java/org/apache/ignite/examples/igfs/IgfsMapReduceExample.java
----------------------------------------------------------------------
diff --git a/examples/src/main/java/org/apache/ignite/examples/igfs/IgfsMapReduceExample.java b/examples/src/main/java/org/apache/ignite/examples/igfs/IgfsMapReduceExample.java
index ed0abe4..f4fa95e 100644
--- a/examples/src/main/java/org/apache/ignite/examples/igfs/IgfsMapReduceExample.java
+++ b/examples/src/main/java/org/apache/ignite/examples/igfs/IgfsMapReduceExample.java
@@ -79,6 +79,9 @@ public class IgfsMapReduceExample {
                     System.out.println("No lines were found.");
                 }
                 else {
+                    System.out.println();
+                    System.out.println("Found lines:");
+
                     for (Line line : lines)
                         print(line.fileLine());
                 }

http://git-wip-us.apache.org/repos/asf/ignite/blob/2c86d60f/examples/src/main/java/org/apache/ignite/examples/servicegrid/ServicesExample.java
----------------------------------------------------------------------
diff --git a/examples/src/main/java/org/apache/ignite/examples/servicegrid/ServicesExample.java b/examples/src/main/java/org/apache/ignite/examples/servicegrid/ServicesExample.java
index 1a10211..ec8e54e 100644
--- a/examples/src/main/java/org/apache/ignite/examples/servicegrid/ServicesExample.java
+++ b/examples/src/main/java/org/apache/ignite/examples/servicegrid/ServicesExample.java
@@ -62,7 +62,10 @@ public class ServicesExample {
                 svcs.deployNodeSingleton("myNodeSingletonService", new SimpleMapServiceImpl());
 
                 // Deploy 2 instances, regardless of number nodes.
-                svcs.deployMultiple("myMultiService", new SimpleMapServiceImpl(), 2 /*total number*/, 0 /*0 for unlimited*/);
+                svcs.deployMultiple("myMultiService",
+                    new SimpleMapServiceImpl(),
+                    2 /*total number*/,
+                    0 /*0 for unlimited*/);
 
                 // Example for using a service proxy
                 // to access a remotely deployed service.
@@ -91,7 +94,9 @@ public class ServicesExample {
         System.out.println(">>>");
 
         // Get a sticky proxy for node-singleton map service.
-        SimpleMapService<Integer, String> mapSvc = ignite.services().serviceProxy("myNodeSingletonService", SimpleMapService.class, true);
+        SimpleMapService<Integer, String> mapSvc = ignite.services().serviceProxy("myNodeSingletonService",
+            SimpleMapService.class,
+            true);
 
         int cnt = 10;
 
@@ -121,7 +126,9 @@ public class ServicesExample {
         System.out.println(">>>");
 
         // Get a sticky proxy for cluster-singleton map service.
-        SimpleMapService<Integer, String> mapSvc = ignite.services().serviceProxy("myClusterSingletonService", SimpleMapService.class, true);
+        SimpleMapService<Integer, String> mapSvc = ignite.services().serviceProxy("myClusterSingletonService",
+            SimpleMapService.class,
+            true);
 
         int cnt = 10;
 


[37/59] [abbrv] ignite git commit: Merge remote-tracking branch 'origin/master'

Posted by vk...@apache.org.
Merge remote-tracking branch 'origin/master'


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

Branch: refs/heads/ignite-884
Commit: 4f3c9a2a1b54c6a61c790b668292a0ed1c33140e
Parents: 28d64d5 76bc7d6
Author: vozerov-gridgain <vo...@gridgain.com>
Authored: Wed Aug 26 11:00:44 2015 +0300
Committer: vozerov-gridgain <vo...@gridgain.com>
Committed: Wed Aug 26 11:00:44 2015 +0300

----------------------------------------------------------------------
 .../IgniteCacheManyAsyncOperationsTest.java     | 107 +++++++++++++++++++
 1 file changed, 107 insertions(+)
----------------------------------------------------------------------



[47/59] [abbrv] ignite git commit: Moved platform transactions to Ignite.

Posted by vk...@apache.org.
Moved platform transactions to Ignite.


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

Branch: refs/heads/ignite-884
Commit: 975f47eabdaba54ddf0974c2a2b7a2d13c6ea03c
Parents: 6c46e47
Author: vozerov-gridgain <vo...@gridgain.com>
Authored: Wed Aug 26 15:07:08 2015 +0300
Committer: vozerov-gridgain <vo...@gridgain.com>
Committed: Wed Aug 26 15:07:08 2015 +0300

----------------------------------------------------------------------
 .../internal/portable/PortableContext.java      |   1 -
 .../transactions/PlatformTransactions.java      | 255 +++++++++++++++++++
 2 files changed, 255 insertions(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/975f47ea/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableContext.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableContext.java b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableContext.java
index 83dd01d..2d3cbf0 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableContext.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableContext.java
@@ -206,7 +206,6 @@ public class PortableContext implements Externalizable {
 //
 //        registerPredefinedType(InteropClusterNode.class, 67);
 //        registerPredefinedType(InteropClusterMetrics.class, 68);
-//        registerPredefinedType(InteropTransactionMetrics.class, 69);
 //        registerPredefinedType(InteropMetadata.class, 70);
 //
 //        registerPredefinedType(InteropDotNetConfiguration.class, 71);

http://git-wip-us.apache.org/repos/asf/ignite/blob/975f47ea/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/transactions/PlatformTransactions.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/transactions/PlatformTransactions.java b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/transactions/PlatformTransactions.java
new file mode 100644
index 0000000..fa63840
--- /dev/null
+++ b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/transactions/PlatformTransactions.java
@@ -0,0 +1,255 @@
+/*
+ * 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.platform.transactions;
+
+import org.apache.ignite.*;
+import org.apache.ignite.configuration.*;
+import org.apache.ignite.internal.portable.*;
+import org.apache.ignite.internal.processors.platform.*;
+import org.apache.ignite.internal.processors.platform.utils.*;
+import org.apache.ignite.internal.util.*;
+import org.apache.ignite.internal.util.typedef.*;
+import org.apache.ignite.lang.*;
+import org.apache.ignite.transactions.*;
+
+import java.util.*;
+import java.util.concurrent.*;
+import java.util.concurrent.atomic.*;
+
+/**
+ * Native transaction wrapper implementation.
+ */
+@SuppressWarnings({"unchecked", "UnusedDeclaration", "TryFinallyCanBeTryWithResources"})
+public class PlatformTransactions extends PlatformAbstractTarget {
+    /** */
+    public static final int OP_CACHE_CONFIG_PARAMETERS = 1;
+
+    /** */
+    public static final int OP_METRICS = 2;
+
+    /** */
+    private final IgniteTransactions txs;
+
+    /** Map with currently active transactions. */
+    private final ConcurrentMap<Long, Transaction> txMap = GridConcurrentFactory.newMap();
+
+    /** Transaction ID sequence. Must be static to ensure uniqueness across different caches. */
+    private static final AtomicLong TX_ID_GEN = new AtomicLong();
+
+    /**
+     * Constructor.
+     *
+     * @param interopCtx Interop context.
+     */
+    public PlatformTransactions(PlatformContext interopCtx) {
+        super(interopCtx);
+
+        txs = interopCtx.kernalContext().grid().transactions();
+    }
+
+    /**
+     * @param concurrency Concurrency.
+     * @param isolation Isolation.
+     * @param timeout Timeout
+     * @param txSize Number of entries participating in transaction.
+     * @return Transaction thread ID.
+     */
+    public long txStart(int concurrency, int isolation, long timeout, int txSize) {
+        TransactionConcurrency txConcurrency = TransactionConcurrency.fromOrdinal(concurrency);
+
+        assert txConcurrency != null;
+
+        TransactionIsolation txIsolation = TransactionIsolation.fromOrdinal(isolation);
+
+        assert txIsolation != null;
+
+        Transaction tx = txs.txStart(txConcurrency, txIsolation);
+
+        return registerTx(tx);
+    }
+
+    /**
+     * @param id Transaction ID.
+     * @throws org.apache.ignite.IgniteCheckedException In case of error.
+     */
+    public int txCommit(long id) throws IgniteCheckedException {
+        tx(id).commit();
+
+        return txClose(id);
+    }
+
+    /**
+     * @param id Transaction ID.
+     * @throws org.apache.ignite.IgniteCheckedException In case of error.
+     */
+    public int txRollback(long id) throws IgniteCheckedException {
+        tx(id).rollback();
+
+        return txClose(id);
+    }
+
+    /**
+     * @param id Transaction ID.
+     * @throws org.apache.ignite.IgniteCheckedException In case of error.
+     * @return Transaction state.
+     */
+    public int txClose(long id) throws IgniteCheckedException {
+        Transaction tx = tx(id);
+
+        try {
+            tx.close();
+
+            return tx.state().ordinal();
+        }
+        finally {
+            unregisterTx(id);
+        }
+    }
+
+    /**
+     * @param id Transaction ID.
+     * @return Transaction state.
+     */
+    public int txState(long id) {
+        Transaction tx = tx(id);
+
+        return tx.state().ordinal();
+    }
+
+    /**
+     * @param id Transaction ID.
+     * @return {@code True} if rollback only flag was set.
+     */
+    public boolean txSetRollbackOnly(long id) {
+        Transaction tx = tx(id);
+
+        return tx.setRollbackOnly();
+    }
+
+    /**
+     * Commits tx in async mode.
+     */
+    public void txCommitAsync(final long txId, final long futId) {
+        final Transaction asyncTx = (Transaction)tx(txId).withAsync();
+
+        asyncTx.commit();
+
+        listenAndNotifyIntFuture(futId, asyncTx);
+    }
+
+    /**
+     * Rolls back tx in async mode.
+     */
+    public void txRollbackAsync(final long txId, final long futId) {
+        final Transaction asyncTx = (Transaction)tx(txId).withAsync();
+
+        asyncTx.rollback();
+
+        listenAndNotifyIntFuture(futId, asyncTx);
+    }
+
+    /**
+     * Listens to the transaction future and notifies .NET int future.
+     */
+    private void listenAndNotifyIntFuture(final long futId, final Transaction asyncTx) {
+        IgniteFuture fut = asyncTx.future().chain(new C1<IgniteFuture, Object>() {
+            private static final long serialVersionUID = 0L;
+
+            @Override public Object apply(IgniteFuture fut) {
+                return null;
+            }
+        });
+
+        PlatformFutureUtils.listen(interopCtx, fut, futId, PlatformFutureUtils.TYP_OBJ);
+    }
+
+    /**
+     * Resets transaction metrics.
+     */
+    public void resetMetrics() {
+       txs.resetMetrics();
+    }
+
+    /**
+     * Register transaction.
+     *
+     * @param tx Transaction.
+     * @return Transaction ID.
+     */
+    private long registerTx(Transaction tx) {
+        long id = TX_ID_GEN.incrementAndGet();
+
+        Transaction old = txMap.put(id, tx);
+
+        assert old == null : "Duplicate TX ids: " + old;
+
+        return id;
+    }
+
+    /**
+     * Unregister transaction.
+     *
+     * @param id Transaction ID.
+     */
+    private void unregisterTx(long id) {
+        Transaction tx = txMap.remove(id);
+
+        assert tx != null : "Failed to unregister transaction: " + id;
+    }
+
+    /**
+     * Get transaction by ID.
+     *
+     * @param id ID.
+     * @return Transaction.
+     */
+    private Transaction tx(long id) {
+        Transaction tx = txMap.get(id);
+
+        assert tx != null : "Transaction not found for ID: " + id;
+
+        return tx;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void processOutOp(int type, PortableRawWriterEx writer) throws IgniteCheckedException {
+        switch (type) {
+            case OP_CACHE_CONFIG_PARAMETERS:
+                TransactionConfiguration txCfg = interopCtx.kernalContext().config().getTransactionConfiguration();
+
+                writer.writeEnum(txCfg.getDefaultTxConcurrency());
+                writer.writeEnum(txCfg.getDefaultTxIsolation());
+                writer.writeLong(txCfg.getDefaultTxTimeout());
+
+                break;
+
+            case OP_METRICS:
+                TransactionMetrics metrics = txs.metrics();
+
+                writer.writeDate(new Date(metrics.commitTime()));
+                writer.writeDate(new Date(metrics.rollbackTime()));
+                writer.writeInt(metrics.txCommits());
+                writer.writeInt(metrics.txRollbacks());
+
+                break;
+
+            default:
+                throwUnsupported(type);
+        }
+    }
+}
\ No newline at end of file


[52/59] [abbrv] ignite git commit: IGNITE-1302: Moving some common .Net classes to Ignite.

Posted by vk...@apache.org.
IGNITE-1302: Moving some common .Net classes to Ignite.


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

Branch: refs/heads/ignite-884
Commit: 8df6b935c32d8b801ead4deb0470f84df435ff5a
Parents: 824cfa4
Author: Pavel Tupitsyn <pt...@gridgain.com>
Authored: Wed Aug 26 15:55:24 2015 +0300
Committer: vozerov-gridgain <vo...@gridgain.com>
Committed: Wed Aug 26 15:55:24 2015 +0300

----------------------------------------------------------------------
 .../Apache.Ignite.Core.csproj                   |  22 ++
 .../Common/AsyncSupportedAttribute.cs           |  33 +++
 .../Apache.Ignite.Core/Common/IAsyncSupport.cs  |  52 ++++
 .../dotnet/Apache.Ignite.Core/Common/IFuture.cs | 115 ++++++++
 .../Common/IgniteException.cs                   |  66 +++++
 .../Impl/Collections/CollectionExtensions.cs    |  45 +++
 .../Impl/Collections/MultiValueDictionary.cs    | 143 ++++++++++
 .../Impl/Collections/ReadOnlyCollection.cs      | 102 +++++++
 .../Impl/Collections/ReadOnlyDictionary.cs      | 149 ++++++++++
 .../Impl/Common/AsyncResult.cs                  |  71 +++++
 .../Impl/Common/CompletedAsyncResult.cs         |  70 +++++
 .../Common/CopyOnWriteConcurrentDictionary.cs   |  70 +++++
 .../Impl/Common/DelegateConverter.cs            | 253 ++++++++++++++++
 .../Apache.Ignite.Core/Impl/Common/Future.cs    | 286 +++++++++++++++++++
 .../Impl/Common/FutureType.cs                   |  52 ++++
 .../Impl/Common/GridArgumentCheck.cs            |  76 +++++
 .../Impl/Common/IFutureConverter.cs             |  32 +++
 .../Impl/Common/IFutureInternal.cs              |  45 +++
 .../Impl/Common/LoadedAssembliesResolver.cs     |  96 +++++++
 .../Impl/Common/TypeCaster.cs                   |  72 +++++
 20 files changed, 1850 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/8df6b935/modules/platform/src/main/dotnet/Apache.Ignite.Core/Apache.Ignite.Core.csproj
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Apache.Ignite.Core.csproj b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Apache.Ignite.Core.csproj
index 658e5fb..12e335a 100644
--- a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Apache.Ignite.Core.csproj
+++ b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Apache.Ignite.Core.csproj
@@ -16,6 +16,7 @@
     <PlatformTarget>x64</PlatformTarget>
     <OutputPath>bin\x64\Debug\</OutputPath>
     <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
+    <DefineConstants>DEBUG</DefineConstants>
   </PropertyGroup>
   <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x64'">
     <PlatformTarget>x64</PlatformTarget>
@@ -26,6 +27,7 @@
     <PlatformTarget>x86</PlatformTarget>
     <OutputPath>bin\x86\Debug\</OutputPath>
     <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
+    <DefineConstants>DEBUG</DefineConstants>
   </PropertyGroup>
   <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x86'">
     <PlatformTarget>x86</PlatformTarget>
@@ -47,7 +49,26 @@
     <Reference Include="System.Core" />
   </ItemGroup>
   <ItemGroup>
+    <Compile Include="Common\IgniteException.cs" />
+    <Compile Include="Common\IAsyncSupport.cs" />
+    <Compile Include="Common\IFuture.cs" />
     <Compile Include="Ignition.cs" />
+    <Compile Include="Common\AsyncSupportedAttribute.cs" />
+    <Compile Include="Impl\Collections\CollectionExtensions.cs" />
+    <Compile Include="Impl\Collections\MultiValueDictionary.cs" />
+    <Compile Include="Impl\Collections\ReadOnlyCollection.cs" />
+    <Compile Include="Impl\Collections\ReadOnlyDictionary.cs" />
+    <Compile Include="Impl\Common\AsyncResult.cs" />
+    <Compile Include="Impl\Common\CompletedAsyncResult.cs" />
+    <Compile Include="Impl\Common\CopyOnWriteConcurrentDictionary.cs" />
+    <Compile Include="Impl\Common\DelegateConverter.cs" />
+    <Compile Include="Impl\Common\Future.cs" />
+    <Compile Include="Impl\Common\FutureType.cs" />
+    <Compile Include="Impl\Common\GridArgumentCheck.cs" />
+    <Compile Include="Impl\Common\IFutureConverter.cs" />
+    <Compile Include="Impl\Common\IFutureInternal.cs" />
+    <Compile Include="Impl\Common\LoadedAssembliesResolver.cs" />
+    <Compile Include="Impl\Common\TypeCaster.cs" />
     <Compile Include="Impl\Handle\Handle.cs" />
     <Compile Include="Impl\Handle\HandleRegistry.cs" />
     <Compile Include="Impl\Handle\IHandle.cs" />
@@ -64,6 +85,7 @@
     <Compile Include="Impl\Portable\IO\IPortableStream.cs" />
     <Compile Include="Properties\AssemblyInfo.cs" />
   </ItemGroup>
+  <ItemGroup />
   <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
   <!-- To modify your build process, add your task inside one of the targets below and uncomment it. 
        Other similar extension points exist, see Microsoft.Common.targets.

http://git-wip-us.apache.org/repos/asf/ignite/blob/8df6b935/modules/platform/src/main/dotnet/Apache.Ignite.Core/Common/AsyncSupportedAttribute.cs
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Common/AsyncSupportedAttribute.cs b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Common/AsyncSupportedAttribute.cs
new file mode 100644
index 0000000..094a93c
--- /dev/null
+++ b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Common/AsyncSupportedAttribute.cs
@@ -0,0 +1,33 @@
+/*
+ * 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.
+ */
+
+namespace Apache.Ignite.Core.Common
+{
+    using System;
+
+    /// <summary>
+    /// Attribute to indicate that method can be executed asynchronously if async mode is enabled.
+    /// To enable async mode, invoke <see cref="IAsyncSupport{TWithAsync}.WithAsync"/> method on the API.
+    /// The future for the async method can be retrieved via 
+    /// <see cref="IFuture{T}"/> right after the execution of an asynchronous method.
+    /// </summary>
+    [AttributeUsage(AttributeTargets.Method)]
+    public sealed class AsyncSupportedAttribute : Attribute
+    {
+        // No-op.
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ignite/blob/8df6b935/modules/platform/src/main/dotnet/Apache.Ignite.Core/Common/IAsyncSupport.cs
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Common/IAsyncSupport.cs b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Common/IAsyncSupport.cs
new file mode 100644
index 0000000..f6b6551
--- /dev/null
+++ b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Common/IAsyncSupport.cs
@@ -0,0 +1,52 @@
+/*
+ * 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.
+ */
+
+namespace Apache.Ignite.Core.Common
+{
+    /// <summary>
+    /// Allows to enable asynchronous mode on Grid APIs.
+    /// </summary>
+    /// <typeparam name="TWithAsync">Type of WithAsync method result.</typeparam>
+    public interface IAsyncSupport<out TWithAsync> where TWithAsync : IAsyncSupport<TWithAsync>
+    {
+        /// <summary>
+        /// Gets component with asynchronous mode enabled.
+        /// </summary>
+        /// <returns>Component with asynchronous mode enabled.</returns>
+        TWithAsync WithAsync();
+
+        /// <summary>
+        /// Gets a value indicating whether this instance is in asynchronous mode.
+        /// </summary>
+        /// <value>
+        /// <c>true</c> if asynchronous mode is enabled.
+        /// </value>
+        bool IsAsync { get; }
+
+        /// <summary>
+        /// Gets and resets future for previous asynchronous operation.
+        /// </summary>
+        /// <returns>Future for previous asynchronous operation.</returns>
+        IFuture GetFuture();
+
+        /// <summary>
+        /// Gets and resets future for previous asynchronous operation.
+        /// </summary>
+        /// <returns>Future for previous asynchronous operation.</returns>
+        IFuture<TResult> GetFuture<TResult>();
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ignite/blob/8df6b935/modules/platform/src/main/dotnet/Apache.Ignite.Core/Common/IFuture.cs
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Common/IFuture.cs b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Common/IFuture.cs
new file mode 100644
index 0000000..2e94cd4
--- /dev/null
+++ b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Common/IFuture.cs
@@ -0,0 +1,115 @@
+/*
+ * 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.
+ */
+
+namespace Apache.Ignite.Core.Common
+{
+    using System;
+    using System.Threading.Tasks;
+
+    /// <summary>
+    /// Non-generic Future. Represents an asynchronous operation that can return a value.
+    /// <para/>
+    /// All members are thread-safe and may be used concurrently from multiple threads.
+    /// </summary>
+    public interface IFuture
+    {
+        /// <summary>
+        /// Gets a value indicating whether this instance is done.
+        /// </summary>
+        bool IsDone
+        {
+            get;
+        }
+
+        /// <summary>
+        /// Gets the future result.
+        /// </summary>
+        /// <returns>Future result.</returns>
+        object Get();
+
+        /// <summary>
+        /// Gets the future result with a timeout.
+        /// </summary>
+        /// <param name="timeout">The timeout.</param>
+        /// <returns>
+        /// Future result, if it is obtained within specified timeout; otherwise, throws <see cref="TimeoutException"/>
+        /// </returns>
+        /// <exception cref="TimeoutException">Thrown if Get operation exceeded specified timeout.</exception>
+        object Get(TimeSpan timeout);
+
+        /// <summary>
+        /// Listens this instance and invokes callback upon future completion.
+        /// </summary>
+        /// <param name="callback">The callback to execute upon future completion.</param>
+        void Listen(Action callback);
+
+        /// <summary>
+        /// Listens this instance and invokes callback upon future completion.
+        /// </summary>
+        /// <param name="callback">The callback to execute upon future completion.</param>
+        void Listen(Action<IFuture> callback);
+
+        /// <summary>
+        /// Gets an IAsyncResult indicating the state of this Future.
+        /// </summary>
+        /// <returns>Future state representation in form of IAsyncResult.</returns>
+        IAsyncResult ToAsyncResult();
+
+        /// <summary>
+        /// Gets a Task that returns the result of this Future.
+        /// </summary>
+        /// <returns>Task that completes when this future gets done and returns the result.</returns>
+        Task<object> ToTask();
+    }
+
+    /// <summary>
+    /// Generic Future. Represents an asynchronous operation that can return a value.
+    /// <para/>
+    /// All members are thread-safe and may be used concurrently from multiple threads.
+    /// </summary>
+    /// <typeparam name="T">Future result type.</typeparam>
+    public interface IFuture<T> : IFuture
+    {
+        /// <summary>
+        /// Gets the future result.
+        /// </summary>
+        /// <returns>Future result.</returns>
+        new T Get();
+
+        /// <summary>
+        /// Gets the future result with a timeout.
+        /// </summary>
+        /// <param name="timeout">The timeout.</param>
+        /// <returns>
+        /// Future result, if it is obtained within specified timeout; otherwise, throws <see cref="TimeoutException"/>
+        /// </returns>
+        /// <exception cref="TimeoutException">Thrown if Get operation exceeded specified timeout.</exception>
+        new T Get(TimeSpan timeout);
+
+        /// <summary>
+        /// Gets a Task that returns the result of this Future.
+        /// </summary>
+        /// <returns>Task that completes when this future gets done and returns the result.</returns>
+        new Task<T> ToTask();
+
+        /// <summary>
+        /// Listens this instance and invokes callback upon future completion.
+        /// </summary>
+        /// <param name="callback">The callback to execute upon future completion.</param>
+        void Listen(Action<IFuture<T>> callback);
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/8df6b935/modules/platform/src/main/dotnet/Apache.Ignite.Core/Common/IgniteException.cs
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Common/IgniteException.cs b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Common/IgniteException.cs
new file mode 100644
index 0000000..4626407
--- /dev/null
+++ b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Common/IgniteException.cs
@@ -0,0 +1,66 @@
+/*
+ * 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.
+ */
+
+namespace Apache.Ignite.Core.Common
+{
+    using System;
+    using System.Runtime.Serialization;
+
+    /// <summary>
+    /// General grid exception. Indicates any error condition within Grid.
+    /// </summary>
+    [Serializable]
+    public class IgniteException : Exception
+    {
+        /// <summary>
+        /// Initializes a new instance of the <see cref="IgniteException"/> class.
+        /// </summary>
+        public IgniteException()
+        {
+            // No-op.
+        }
+
+        /// <summary>
+        /// Initializes a new instance of the <see cref="IgniteException" /> class.
+        /// </summary>
+        /// <param name="message">The message that describes the error.</param>
+        public IgniteException(string message) : base(message)
+        {
+            // No-op.
+        }
+
+        /// <summary>
+        /// Initializes a new instance of the <see cref="IgniteException" /> class.
+        /// </summary>
+        /// <param name="message">The message.</param>
+        /// <param name="cause">The cause.</param>
+        public IgniteException(string message, Exception cause) : base(message, cause)
+        {
+            // No-op.
+        }
+
+        /// <summary>
+        /// Initializes a new instance of the <see cref="IgniteException"/> class.
+        /// </summary>
+        /// <param name="info">Serialization information.</param>
+        /// <param name="ctx">Streaming context.</param>
+        protected IgniteException(SerializationInfo info, StreamingContext ctx) : base(info, ctx)
+        {
+            // No-op.
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/8df6b935/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Collections/CollectionExtensions.cs
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Collections/CollectionExtensions.cs b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Collections/CollectionExtensions.cs
new file mode 100644
index 0000000..57295cb
--- /dev/null
+++ b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Collections/CollectionExtensions.cs
@@ -0,0 +1,45 @@
+/*
+ * 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.
+ */
+
+namespace Apache.Ignite.Core.Impl.Collections
+{
+    using System.Collections.Generic;
+
+    /// <summary>
+    /// Collection extension methods.
+    /// </summary>
+    public static class CollectionExtensions
+    {
+        /// <summary>
+        /// Returns a read-only System.Collections.Generic.IDictionary{K, V} wrapper for the current collection.
+        /// </summary>
+        public static IDictionary<TKey, TValue> AsReadOnly<TKey, TValue>(this IDictionary<TKey, TValue> dict)
+        {
+            return new ReadOnlyDictionary<TKey, TValue>(dict);
+        }
+
+        /// <summary>
+        /// Returns a read-only System.Collections.Generic.ICollection{K, V} wrapper for the current collection.
+        /// </summary>
+        public static ICollection<T> AsReadOnly<T>(this ICollection<T> col)
+        {
+            var list = col as List<T>;
+
+            return list != null ? (ICollection<T>) list.AsReadOnly() : new ReadOnlyCollection<T>(col);
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ignite/blob/8df6b935/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Collections/MultiValueDictionary.cs
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Collections/MultiValueDictionary.cs b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Collections/MultiValueDictionary.cs
new file mode 100644
index 0000000..bd7e895
--- /dev/null
+++ b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Collections/MultiValueDictionary.cs
@@ -0,0 +1,143 @@
+/*
+ * 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.
+ */
+
+namespace Apache.Ignite.Core.Impl.Collections
+{
+    using System.Collections.Generic;
+
+    /// <summary>
+    /// Multiple-values-per-key dictionary.
+    /// </summary>
+    public class MultiValueDictionary<TKey, TValue>
+    {
+        /** Inner dictionary */
+        private readonly Dictionary<TKey, object> _dict = new Dictionary<TKey, object>();
+
+        /// <summary>
+        /// Adds a value.
+        /// </summary>
+        /// <param name="key">The key.</param>
+        /// <param name="val">The value.</param>
+        public void Add(TKey key, TValue val)
+        {
+            object val0;
+
+            if (_dict.TryGetValue(key, out val0))
+            {
+                var list = val0 as List<TValue>;
+
+                if (list != null)
+                    list.Add(val);
+                else
+                    _dict[key] = new List<TValue> {(TValue) val0, val};
+            }
+            else
+                _dict[key] = val;
+        }
+
+        /// <summary>
+        /// Tries the get a value. In case of multiple values for a key, returns the last one.
+        /// </summary>
+        /// <param name="key">The key.</param>
+        /// <param name="val">The value.</param>
+        /// <returns>True if value has been found for specified key; otherwise false.</returns>
+        public bool TryGetValue(TKey key, out TValue val)
+        {
+            object val0;
+            
+            if (!_dict.TryGetValue(key, out val0))
+            {
+                val = default(TValue);
+                return false;
+            }
+
+            var list = val0 as List<TValue>;
+
+            if (list != null)
+                val = list[list.Count - 1];
+            else
+                val = (TValue) val0;
+
+            return true;
+        }
+
+        /// <summary>
+        /// Removes the specified value for the specified key.
+        /// </summary>
+        /// <param name="key">The key.</param>
+        /// <param name="val">The value.</param>
+        public void Remove(TKey key, TValue val)
+        {
+            object val0;
+
+            if (!_dict.TryGetValue(key, out val0))
+                return;
+
+            var list = val0 as List<TValue>;
+
+            if (list != null)
+            {
+                list.Remove(val);
+
+                if (list.Count == 0)
+                    _dict.Remove(key);
+            }
+            else if (Equals(val0, val))
+                _dict.Remove(key);
+        }
+
+        /// <summary>
+        /// Removes the last value for the specified key and returns it.
+        /// </summary>
+        /// <param name="key">The key.</param>
+        /// <param name="val">The value.</param>
+        /// <returns>True if value has been found for specified key; otherwise false.</returns>
+        public bool TryRemove(TKey key, out TValue val)
+        {
+            object val0;
+
+            if (!_dict.TryGetValue(key, out val0))
+            {
+                val = default(TValue);
+
+                return false;
+            }
+
+            var list = val0 as List<TValue>;
+
+            if (list != null)
+            {
+                var index = list.Count - 1;
+
+                val = list[index];
+
+                list.RemoveAt(index);
+
+                if (list.Count == 0)
+                    _dict.Remove(key);
+
+                return true;
+            }
+            
+            val = (TValue) val0;
+
+            _dict.Remove(key);
+
+            return true;
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ignite/blob/8df6b935/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Collections/ReadOnlyCollection.cs
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Collections/ReadOnlyCollection.cs b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Collections/ReadOnlyCollection.cs
new file mode 100644
index 0000000..23cae6b
--- /dev/null
+++ b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Collections/ReadOnlyCollection.cs
@@ -0,0 +1,102 @@
+/*
+ * 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.
+ */
+
+namespace Apache.Ignite.Core.Impl.Collections
+{
+    using System;
+    using System.Collections;
+    using System.Collections.Generic;
+
+    /// <summary>
+    /// Read-only wrapper over ICollection{T}.
+    /// </summary>
+    internal struct ReadOnlyCollection<T> : ICollection<T>
+    {
+        /** Wrapped collection. */
+        private readonly ICollection<T> _col;
+
+        /// <summary>
+        /// Initializes a new instance of the <see cref="ReadOnlyCollection{T}"/> class.
+        /// </summary>
+        public ReadOnlyCollection(ICollection<T> col)
+        {
+            _col = col;
+        }
+
+        /** <inheritdoc /> */
+        public IEnumerator<T> GetEnumerator()
+        {
+            return _col.GetEnumerator();
+        }
+
+        /** <inheritdoc /> */
+        IEnumerator IEnumerable.GetEnumerator()
+        {
+            return ((IEnumerable) _col).GetEnumerator();
+        }
+
+        /** <inheritdoc /> */
+        public void Add(T item)
+        {
+            throw GetReadOnlyException();
+        }
+
+        /** <inheritdoc /> */
+        public void Clear()
+        {
+            throw GetReadOnlyException();
+        }
+
+        /** <inheritdoc /> */
+        public bool Contains(T item)
+        {
+            return _col.Contains(item);
+        }
+
+        /** <inheritdoc /> */
+        public void CopyTo(T[] array, int arrayIndex)
+        {
+            _col.CopyTo(array, arrayIndex);
+        }
+
+        /** <inheritdoc /> */
+        public bool Remove(T item)
+        {
+            throw GetReadOnlyException();
+        }
+
+        /** <inheritdoc /> */
+        public int Count
+        {
+            get { return _col.Count; }
+        }
+
+        /** <inheritdoc /> */
+        public bool IsReadOnly
+        {
+            get { return true; }
+        }
+
+        /// <summary>
+        /// Gets the readonly exception.
+        /// </summary>
+        private static Exception GetReadOnlyException()
+        {
+            return new NotSupportedException("Collection is read-only.");
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ignite/blob/8df6b935/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Collections/ReadOnlyDictionary.cs
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Collections/ReadOnlyDictionary.cs b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Collections/ReadOnlyDictionary.cs
new file mode 100644
index 0000000..60ec9d0
--- /dev/null
+++ b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Collections/ReadOnlyDictionary.cs
@@ -0,0 +1,149 @@
+/*
+ * 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.
+ */
+
+namespace Apache.Ignite.Core.Impl.Collections
+{
+    using System;
+    using System.Collections;
+    using System.Collections.Generic;
+    using System.Diagnostics;
+
+    /// <summary>
+    /// Read-only wrapper over IDictionary{K, V}.
+    /// </summary>
+    internal struct ReadOnlyDictionary<TKey, TValue> : IDictionary<TKey, TValue>
+    {
+        /** Inner dict. */
+        private readonly IDictionary<TKey, TValue> _dict;
+
+        /// <summary>
+        /// Initializes a new instance of the <see cref="ReadOnlyDictionary{K, V}"/> class.
+        /// </summary>
+        /// <param name="dict">The dictionary to wrap.</param>
+        public ReadOnlyDictionary(IDictionary<TKey, TValue> dict)
+        {
+            Debug.Assert(dict != null);
+
+            _dict = dict;
+        }
+
+        /** <inheritdoc /> */
+        public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
+        {
+            return _dict.GetEnumerator();
+        }
+
+        /** <inheritdoc /> */
+        IEnumerator IEnumerable.GetEnumerator()
+        {
+            return ((IEnumerable) _dict).GetEnumerator();
+        }
+
+        /** <inheritdoc /> */
+        public void Add(KeyValuePair<TKey, TValue> item)
+        {
+            throw GetReadonlyException();
+        }
+
+        /** <inheritdoc /> */
+        public void Clear()
+        {
+            throw GetReadonlyException();
+        }
+
+        /** <inheritdoc /> */
+        public bool Contains(KeyValuePair<TKey, TValue> item)
+        {
+            return _dict.Contains(item);
+        }
+
+        /** <inheritdoc /> */
+        public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
+        {
+            _dict.CopyTo(array, arrayIndex);
+        }
+
+        /** <inheritdoc /> */
+        public bool Remove(KeyValuePair<TKey, TValue> item)
+        {
+            throw GetReadonlyException();
+        }
+
+        /** <inheritdoc /> */
+        public int Count
+        {
+            get { return _dict.Count; }
+        }
+
+        /** <inheritdoc /> */
+        public bool IsReadOnly
+        {
+            get { return true; }
+        }
+
+        /** <inheritdoc /> */
+        public bool ContainsKey(TKey key)
+        {
+            return _dict.ContainsKey(key);
+        }
+
+        /** <inheritdoc /> */
+        public void Add(TKey key, TValue value)
+        {
+            throw GetReadonlyException();
+        }
+
+        /** <inheritdoc /> */
+        public bool Remove(TKey key)
+        {
+            return _dict.Remove(key);
+        }
+
+        /** <inheritdoc /> */
+        public bool TryGetValue(TKey key, out TValue value)
+        {
+            return _dict.TryGetValue(key, out value);
+        }
+
+        /** <inheritdoc /> */
+        public TValue this[TKey key]
+        {
+            get { return _dict[key]; }
+            set { throw GetReadonlyException(); }
+        }
+
+        /** <inheritdoc /> */
+        public ICollection<TKey> Keys
+        {
+            get { return _dict.Keys; }
+        }
+
+        /** <inheritdoc /> */
+        public ICollection<TValue> Values
+        {
+            get { return _dict.Values; }
+        }
+
+        /// <summary>
+        /// Gets the readonly exception.
+        /// </summary>
+        private static Exception GetReadonlyException()
+        {
+            return new NotSupportedException("Dictionary is read-only.");
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/8df6b935/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Common/AsyncResult.cs
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Common/AsyncResult.cs b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Common/AsyncResult.cs
new file mode 100644
index 0000000..4e5c396
--- /dev/null
+++ b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Common/AsyncResult.cs
@@ -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.
+ */
+
+namespace Apache.Ignite.Core.Impl.Common
+{
+    using System;
+    using System.Diagnostics.CodeAnalysis;
+    using System.Threading;
+    using Apache.Ignite.Core.Common;
+
+    /// <summary>
+    /// Adapts IGridFuture to the IAsyncResult.
+    /// </summary>
+    [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable",
+        Justification = "Implementing IDisposable has no point since we return this class as IAsyncResult " +
+                        "to the client, and IAsyncResult is not IDisposable.")]
+    public class AsyncResult : IAsyncResult
+    {
+        /** */
+        private readonly ManualResetEvent _waitHandle;
+
+        /// <summary>
+        /// Initializes a new instance of the <see cref="AsyncResult"/> class.
+        /// </summary>
+        /// <param name="fut">The future to wrap.</param>
+        public AsyncResult(IFuture fut)
+        {
+            _waitHandle = new ManualResetEvent(false);
+
+            fut.Listen(() => _waitHandle.Set());
+        }
+
+        /** <inheritdoc /> */
+        public bool IsCompleted
+        {
+            get { return _waitHandle.WaitOne(0); }
+        }
+
+        /** <inheritdoc /> */
+        public WaitHandle AsyncWaitHandle
+        {
+            get { return _waitHandle; }
+        }
+
+        /** <inheritdoc /> */
+        public object AsyncState
+        {
+            get { return null; }
+        }
+
+        /** <inheritdoc /> */
+        public bool CompletedSynchronously
+        {
+            get { return false; }
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ignite/blob/8df6b935/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Common/CompletedAsyncResult.cs
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Common/CompletedAsyncResult.cs b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Common/CompletedAsyncResult.cs
new file mode 100644
index 0000000..14195fd
--- /dev/null
+++ b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Common/CompletedAsyncResult.cs
@@ -0,0 +1,70 @@
+/*
+ * 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.
+ */
+
+namespace Apache.Ignite.Core.Impl.Common
+{
+    using System;
+    using System.Diagnostics.CodeAnalysis;
+    using System.Threading;
+
+    /// <summary>
+    /// Represents an IAsyncResult that is completed.
+    /// </summary>
+    [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", 
+        Justification = "Implementing IDisposable has no point since we return this class as IAsyncResult " +
+                        "to the client, and IAsyncResult is not IDisposable.")]
+    public class CompletedAsyncResult : IAsyncResult
+    {
+        /** Singleton instance. */
+        public static readonly IAsyncResult Instance = new CompletedAsyncResult();
+
+        /** */
+        private readonly WaitHandle _asyncWaitHandle = new ManualResetEvent(true);
+
+        /// <summary>
+        /// Prevents a default instance of the <see cref="CompletedAsyncResult"/> class from being created.
+        /// </summary>
+        private CompletedAsyncResult()
+        {
+            // No-op.
+        }
+
+        /** <inheritdoc /> */
+        public bool IsCompleted
+        {
+            get { return true; }
+        }
+
+        /** <inheritdoc /> */
+        public WaitHandle AsyncWaitHandle
+        {
+            get { return _asyncWaitHandle; }
+        }
+
+        /** <inheritdoc /> */
+        public object AsyncState
+        {
+            get { return null; }
+        }
+
+        /** <inheritdoc /> */
+        public bool CompletedSynchronously
+        {
+            get { return false; }
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ignite/blob/8df6b935/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Common/CopyOnWriteConcurrentDictionary.cs
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Common/CopyOnWriteConcurrentDictionary.cs b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Common/CopyOnWriteConcurrentDictionary.cs
new file mode 100644
index 0000000..fa785b2
--- /dev/null
+++ b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Common/CopyOnWriteConcurrentDictionary.cs
@@ -0,0 +1,70 @@
+/*
+ * 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.
+ */
+
+namespace Apache.Ignite.Core.Impl.Common
+{
+    using System;
+    using System.Collections.Generic;
+
+    /// <summary>
+    /// Concurrent dictionary with CopyOnWrite mechanism inside. 
+    /// Good for frequent reads / infrequent writes scenarios.
+    /// </summary>
+    public class CopyOnWriteConcurrentDictionary<TKey, TValue>
+    {
+        /** */
+        private volatile Dictionary<TKey, TValue> _dict = new Dictionary<TKey, TValue>();
+
+        /// <summary>
+        /// Gets the value associated with the specified key.
+        /// </summary>
+        /// <param name="key">The key.</param>
+        /// <param name="val">The value.</param>
+        /// <returns>true if the dictionary contains an element with the specified key; otherwise, false.</returns>
+        public bool TryGetValue(TKey key, out TValue val)
+        {
+            return _dict.TryGetValue(key, out val);
+        }
+
+        /// <summary>
+        /// Adds a key/value pair if the key does not already exist.
+        /// </summary>
+        /// <param name="key">The key.</param>
+        /// <param name="valueFactory">The function used to generate a value for the key.</param>
+        /// <returns>The value for the key.</returns>
+        public TValue GetOrAdd(TKey key, Func<TKey, TValue> valueFactory)
+        {
+            lock (this)
+            {
+                TValue res;
+
+                if (_dict.TryGetValue(key, out res))
+                    return res;
+
+                var dict0 = new Dictionary<TKey, TValue>(_dict);
+
+                res = valueFactory(key);
+
+                dict0[key] = res;
+
+                _dict = dict0;
+
+                return res;
+            }
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ignite/blob/8df6b935/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Common/DelegateConverter.cs
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Common/DelegateConverter.cs b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Common/DelegateConverter.cs
new file mode 100644
index 0000000..7f83588
--- /dev/null
+++ b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Common/DelegateConverter.cs
@@ -0,0 +1,253 @@
+/*
+ * 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.
+ */
+
+namespace Apache.Ignite.Core.Impl.Common
+{
+    using System;
+    using System.Diagnostics;
+    using System.Linq.Expressions;
+    using System.Reflection;
+    using System.Reflection.Emit;
+
+    /// <summary>
+    /// Converts generic and non-generic delegates.
+    /// </summary>
+    public static class DelegateConverter
+    {
+        /** */
+        private const string DefaultMethodName = "Invoke";
+        
+        /// <summary>
+        /// Compiles a function without arguments.
+        /// </summary>
+        /// <param name="targetType">Type of the target.</param>
+        /// <returns>Compiled function that calls specified method on specified target.</returns>
+        public static Func<object, object> CompileFunc(Type targetType)
+        {
+            var method = targetType.GetMethod(DefaultMethodName);
+
+            var targetParam = Expression.Parameter(typeof(object));
+            var targetParamConverted = Expression.Convert(targetParam, targetType);
+
+            var callExpr = Expression.Call(targetParamConverted, method);
+            var convertResultExpr = Expression.Convert(callExpr, typeof(object));
+
+            return Expression.Lambda<Func<object, object>>(convertResultExpr, targetParam).Compile();
+        }
+
+        /// <summary>
+        /// Compiles a function with arbitrary number of arguments.
+        /// </summary>
+        /// <typeparam name="T">Resulting delegate type.</typeparam>
+        /// <param name="targetType">Type of the target.</param>
+        /// <param name="argTypes">Argument types.</param>
+        /// <param name="convertToObject">
+        /// Flags that indicate whether func params and/or return value should be converted from/to object.
+        /// </param>
+        /// <param name="methodName">Name of the method.</param>
+        /// <returns>
+        /// Compiled function that calls specified method on specified target.
+        /// </returns>
+        public static T CompileFunc<T>(Type targetType, Type[] argTypes, bool[] convertToObject = null,
+            string methodName = null)
+            where T : class
+        {
+            var method = targetType.GetMethod(methodName ?? DefaultMethodName, argTypes);
+
+            return CompileFunc<T>(targetType, method, argTypes, convertToObject);
+        }
+
+        /// <summary>
+        /// Compiles a function with arbitrary number of arguments.
+        /// </summary>
+        /// <typeparam name="T">Resulting delegate type.</typeparam>
+        /// <param name="method">Method.</param>
+        /// <param name="targetType">Type of the target.</param>
+        /// <param name="argTypes">Argument types.</param>
+        /// <param name="convertToObject">
+        /// Flags that indicate whether func params and/or return value should be converted from/to object.
+        /// </param>
+        /// <returns>
+        /// Compiled function that calls specified method on specified target.
+        /// </returns>
+        public static T CompileFunc<T>(Type targetType, MethodInfo method, Type[] argTypes, 
+            bool[] convertToObject = null)
+            where T : class
+        {
+            if (argTypes == null)
+            {
+                var args = method.GetParameters();
+                argTypes = new Type[args.Length];
+
+                for (int i = 0; i < args.Length; i++)
+                    argTypes[i] = args[i].ParameterType;
+            }
+
+            Debug.Assert(convertToObject == null || (convertToObject.Length == argTypes.Length + 1));
+            Debug.Assert(method != null);
+
+            targetType = method.IsStatic ? null : (targetType ?? method.DeclaringType);
+
+            var targetParam = Expression.Parameter(typeof(object));
+            
+            Expression targetParamConverted = null;
+            ParameterExpression[] argParams;
+            int argParamsOffset = 0;
+
+            if (targetType != null)
+            {
+                targetParamConverted = Expression.Convert(targetParam, targetType);
+                argParams = new ParameterExpression[argTypes.Length + 1];
+                argParams[0] = targetParam;
+                argParamsOffset = 1;
+            }
+            else
+                argParams = new ParameterExpression[argTypes.Length];  // static method
+
+            var argParamsConverted = new Expression[argTypes.Length];
+
+            for (var i = 0; i < argTypes.Length; i++)
+            {
+                if (convertToObject == null || convertToObject[i])
+                {
+                    var argParam = Expression.Parameter(typeof (object));
+                    argParams[i + argParamsOffset] = argParam;
+                    argParamsConverted[i] = Expression.Convert(argParam, argTypes[i]);
+                }
+                else
+                {
+                    var argParam = Expression.Parameter(argTypes[i]);
+                    argParams[i + argParamsOffset] = argParam;
+                    argParamsConverted[i] = argParam;
+                }
+            }
+
+            Expression callExpr = Expression.Call(targetParamConverted, method, argParamsConverted);
+
+            if (convertToObject == null || convertToObject[argTypes.Length])
+                callExpr = Expression.Convert(callExpr, typeof(object));
+
+            return Expression.Lambda<T>(callExpr, argParams).Compile();
+        }
+
+        /// <summary>
+        /// Compiles a generic ctor with arbitrary number of arguments.
+        /// </summary>
+        /// <typeparam name="T">Result func type.</typeparam>
+        /// <param name="type">Type to be created by ctor.</param>
+        /// <param name="argTypes">Argument types.</param>
+        /// <param name="convertResultToObject">if set to <c>true</c> [convert result to object].
+        /// Flag that indicates whether ctor return value should be converted to object.
+        /// </param>
+        /// <returns>
+        /// Compiled generic constructor.
+        /// </returns>
+        public static T CompileCtor<T>(Type type, Type[] argTypes, bool convertResultToObject = true)
+        {
+            var ctor = type.GetConstructor(argTypes);
+
+            Debug.Assert(ctor != null);
+
+            var args = new ParameterExpression[argTypes.Length];
+            var argsConverted = new Expression[argTypes.Length];
+
+            for (var i = 0; i < argTypes.Length; i++)
+            {
+                var arg = Expression.Parameter(typeof(object));
+                args[i] = arg;
+                argsConverted[i] = Expression.Convert(arg, argTypes[i]);
+            }
+
+            Expression ctorExpr = Expression.New(ctor, argsConverted);  // ctor takes args of specific types
+
+            if (convertResultToObject)
+                ctorExpr = Expression.Convert(ctorExpr, typeof (object)); // convert ctor result to object
+
+            return Expression.Lambda<T>(ctorExpr, args).Compile();  // lambda takes args as objects
+        }
+
+        /// <summary>
+        /// Compiles the field setter.
+        /// </summary>
+        /// <param name="field">The field.</param>
+        /// <returns>Compiled field setter.</returns>
+        public static Action<object, object> CompileFieldSetter(FieldInfo field)
+        {
+            Debug.Assert(field != null);
+            Debug.Assert(field.DeclaringType != null);   // non-static
+
+            var targetParam = Expression.Parameter(typeof(object));
+            var targetParamConverted = Expression.Convert(targetParam, field.DeclaringType);
+
+            var valParam = Expression.Parameter(typeof(object));
+            var valParamConverted = Expression.Convert(valParam, field.FieldType);
+
+            var assignExpr = Expression.Call(GetWriteFieldMethod(field), targetParamConverted, valParamConverted);
+
+            return Expression.Lambda<Action<object, object>>(assignExpr, targetParam, valParam).Compile();
+        }
+
+        /// <summary>
+        /// Compiles the property setter.
+        /// </summary>
+        /// <param name="prop">The property.</param>
+        /// <returns>Compiled property setter.</returns>
+        public static Action<object, object> CompilePropertySetter(PropertyInfo prop)
+        {
+            Debug.Assert(prop != null);
+            Debug.Assert(prop.DeclaringType != null);   // non-static
+
+            var targetParam = Expression.Parameter(typeof(object));
+            var targetParamConverted = Expression.Convert(targetParam, prop.DeclaringType);
+
+            var valParam = Expression.Parameter(typeof(object));
+            var valParamConverted = Expression.Convert(valParam, prop.PropertyType);
+
+            var fld = Expression.Property(targetParamConverted, prop);
+
+            var assignExpr = Expression.Assign(fld, valParamConverted);
+
+            return Expression.Lambda<Action<object, object>>(assignExpr, targetParam, valParam).Compile();
+        }
+
+        /// <summary>
+        /// Gets a method to write a field (including private and readonly).
+        /// NOTE: Expression Trees can't write readonly fields.
+        /// </summary>
+        /// <param name="field">The field.</param>
+        /// <returns>Resulting MethodInfo.</returns>
+        public static DynamicMethod GetWriteFieldMethod(FieldInfo field)
+        {
+            Debug.Assert(field != null);
+
+            var module = Assembly.GetExecutingAssembly().GetModules()[0];
+
+            var method = new DynamicMethod(string.Empty, null, new[] { field.DeclaringType, field.FieldType }, module,
+                true);
+
+            var il = method.GetILGenerator();
+
+            il.Emit(OpCodes.Ldarg_0);
+            il.Emit(OpCodes.Ldarg_1);
+            il.Emit(OpCodes.Stfld, field);
+            il.Emit(OpCodes.Ret);
+
+            return method;
+        }
+
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ignite/blob/8df6b935/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Common/Future.cs
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Common/Future.cs b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Common/Future.cs
new file mode 100644
index 0000000..c62cfd2
--- /dev/null
+++ b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Common/Future.cs
@@ -0,0 +1,286 @@
+/*
+ * 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.
+ */
+
+namespace Apache.Ignite.Core.Impl.Common
+{
+    using System;
+    using System.Collections.Generic;
+    using System.Diagnostics.CodeAnalysis;
+    using System.Threading;
+    using System.Threading.Tasks;
+    
+    using Apache.Ignite.Core.Common;
+    using Apache.Ignite.Core.Impl.Portable.IO;
+
+    /// <summary>
+    /// Grid future implementation.
+    /// </summary>
+    [SuppressMessage("ReSharper", "ParameterHidesMember")]
+    public sealed class Future<T> : IFutureInternal, IFuture<T>
+    {
+        /** Converter. */
+        private readonly IFutureConverter<T> _converter;
+
+        /** Result. */
+        private T _res;
+
+        /** Caught cxception. */
+        private Exception _err;
+
+        /** Done flag. */
+        private volatile bool _done;
+
+        /** Listener(s). Either Action or List{Action}. */
+        private object _callbacks;
+
+        /// <summary>
+        /// Constructor.
+        /// </summary>
+        /// <param name="converter">Future result marshaller and converter.</param>
+        public Future(IFutureConverter<T> converter = null)
+        {
+            _converter = converter;
+        }
+
+        /** <inheritdoc/> */
+        public bool IsDone
+        {
+            get { return _done; }
+        }
+
+        /** <inheritdoc/> */
+        public T Get()
+        {
+            if (!_done)
+            {
+                lock (this)
+                {
+                    while (!_done)
+                        Monitor.Wait(this);
+                }
+            }
+
+            return Get0();
+        }
+
+        /** <inheritdoc/> */
+        public T Get(TimeSpan timeout)
+        {
+            long ticks = timeout.Ticks;
+
+            if (ticks < 0)
+                throw new ArgumentException("Timeout cannot be negative.");
+
+            if (ticks == 0)
+                return Get();
+
+            if (!_done)
+            {
+                // Fallback to locked mode.
+                lock (this)
+                {
+                    long endTime = DateTime.Now.Ticks + ticks;
+
+                    if (!_done)
+                    {
+                        while (true)
+                        {
+                            Monitor.Wait(this, timeout);
+
+                            if (_done)
+                                break;
+
+                            ticks = endTime - DateTime.Now.Ticks;
+
+                            if (ticks <= 0)
+                                throw new TimeoutException("Timeout waiting for future completion.");
+
+                            timeout = TimeSpan.FromTicks(ticks);
+                        }
+                    }
+                }
+            }
+
+            return Get0();
+        }
+
+        /** <inheritdoc/> */
+        public void Listen(Action callback)
+        {
+            Listen((Action<IFuture<T>>) (fut => callback()));
+        }
+
+        /** <inheritdoc/> */
+        public void Listen(Action<IFuture> callback)
+        {
+            Listen((Action<IFuture<T>>)callback);
+        }
+
+        /** <inheritdoc/> */
+        public void Listen(Action<IFuture<T>> callback)
+        {
+            GridArgumentCheck.NotNull(callback, "callback");
+
+            if (!_done)
+            {
+                lock (this)
+                {
+                    if (!_done)
+                    {
+                        AddCallback(callback);
+
+                        return;
+                    }
+                }
+            }
+
+            callback(this);
+        }
+
+        /// <summary>
+        /// Get result or throw an error.
+        /// </summary>
+        private T Get0()
+        {
+            if (_err != null)
+                throw _err;
+
+            return _res;
+        }
+
+        /** <inheritdoc/> */
+        public IAsyncResult ToAsyncResult()
+        {
+            return _done ? CompletedAsyncResult.Instance : new AsyncResult(this);
+        }
+
+        /** <inheritdoc/> */
+        Task<object> IFuture.ToTask()
+        {
+            return Task.Factory.FromAsync(ToAsyncResult(), x => (object) Get());
+        }
+
+        /** <inheritdoc/> */
+        public Task<T> ToTask()
+        {
+            return Task.Factory.FromAsync(ToAsyncResult(), x => Get());
+        }
+
+        /** <inheritdoc/> */
+        object IFuture.Get(TimeSpan timeout)
+        {
+            return Get(timeout);
+        }
+
+        /** <inheritdoc/> */
+        object IFuture.Get()
+        {
+            return Get();
+        }
+
+        /** <inheritdoc /> */
+        public void OnResult(IPortableStream stream)
+        {
+            try
+            {
+                OnResult(_converter.Convert(stream));
+            }
+            catch (Exception ex)
+            {
+                OnError(ex);
+            }
+        }
+
+        /** <inheritdoc /> */
+        public void OnError(Exception err)
+        {
+            OnDone(default(T), err);
+        }
+
+        /** <inheritdoc /> */
+        public void OnNullResult()
+        {
+            OnResult(default(T));
+        }
+
+        /// <summary>
+        /// Set result.
+        /// </summary>
+        /// <param name="res">Result.</param>
+        internal void OnResult(T res)
+        {
+            OnDone(res, null);
+        }
+
+        /// <summary>
+        /// Set future to Done state.
+        /// </summary>
+        /// <param name="res">Result.</param>
+        /// <param name="err">Error.</param>
+        public void OnDone(T res, Exception err)
+        {
+            object callbacks0 = null;
+
+            lock (this)
+            {
+                if (!_done)
+                {
+                    _res = res;
+                    _err = err;
+
+                    _done = true;
+
+                    Monitor.PulseAll(this);
+
+                    // Notify listeners outside the lock
+                    callbacks0 = _callbacks;
+                    _callbacks = null;
+                }
+            }
+
+            if (callbacks0 != null)
+            {
+                var list = callbacks0 as List<Action<IFuture<T>>>;
+
+                if (list != null)
+                    list.ForEach(x => x(this));
+                else
+                    ((Action<IFuture<T>>) callbacks0)(this);
+            }
+        }
+
+        /// <summary>
+        /// Adds a callback.
+        /// </summary>
+        private void AddCallback(Action<IFuture<T>> callback)
+        {
+            if (_callbacks == null)
+            {
+                _callbacks = callback;
+
+                return;
+            }
+
+            var list = _callbacks as List<Action<IFuture<T>>> ??
+                new List<Action<IFuture<T>>> {(Action<IFuture<T>>) _callbacks};
+
+            list.Add(callback);
+
+            _callbacks = list;
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/8df6b935/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Common/FutureType.cs
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Common/FutureType.cs b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Common/FutureType.cs
new file mode 100644
index 0000000..0beff04
--- /dev/null
+++ b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Common/FutureType.cs
@@ -0,0 +1,52 @@
+/*
+ * 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.
+ */
+
+namespace Apache.Ignite.Core.Impl.Common
+{
+    /// <summary>
+    /// Future types.
+    /// </summary>
+    public enum FutureType
+    {
+        /** Future type: byte. */
+        Byte = 1,
+
+        /** Future type: boolean. */
+        Bool = 2,
+
+        /** Future type: short. */
+        Short = 3,
+
+        /** Future type: char. */
+        Char = 4,
+
+        /** Future type: int. */
+        Int = 5,
+
+        /** Future type: float. */
+        Float = 6,
+
+        /** Future type: long. */
+        Long = 7,
+
+        /** Future type: double. */
+        Double = 8,
+
+        /** Future type: object. */
+        Object = 9
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ignite/blob/8df6b935/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Common/GridArgumentCheck.cs
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Common/GridArgumentCheck.cs b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Common/GridArgumentCheck.cs
new file mode 100644
index 0000000..a1fadfe
--- /dev/null
+++ b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Common/GridArgumentCheck.cs
@@ -0,0 +1,76 @@
+/*
+ * 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.
+ */
+
+namespace Apache.Ignite.Core.Impl.Common
+{
+    using System;
+    using System.Collections.Generic;
+
+    /// <summary>
+    /// Arguments check helpers.
+    /// </summary>
+    public static class GridArgumentCheck
+    {
+        /// <summary>
+        /// Throws an ArgumentNullException if specified arg is null.
+        /// </summary>
+        /// <param name="arg">The argument.</param>
+        /// <param name="argName">Name of the argument.</param>
+        public static void NotNull(object arg, string argName)
+        {
+            if (arg == null)
+                throw new ArgumentNullException(argName);
+        }
+
+        /// <summary>
+        /// Throws an ArgumentException if specified arg is null or empty string.
+        /// </summary>
+        /// <param name="arg">The argument.</param>
+        /// <param name="argName">Name of the argument.</param>
+        public static void NotNullOrEmpty(string arg, string argName)
+        {
+            if (string.IsNullOrEmpty(arg))
+                throw new ArgumentException(string.Format("'{0}' argument should not be null or empty.", argName),
+                    argName);
+        }
+
+        /// <summary>
+        /// Throws an ArgumentException if specified arg is null or empty string.
+        /// </summary>
+        /// <param name="collection">The collection.</param>
+        /// <param name="argName">Name of the argument.</param>
+        public static void NotNullOrEmpty<T>(ICollection<T> collection, string argName)
+        {
+            if (collection == null || collection.Count == 0)
+                throw new ArgumentException(string.Format("'{0}' argument should not be null or empty.", argName),
+                    argName);
+        }
+
+        /// <summary>
+        /// Throws an ArgumentException if specified condition is false.
+        /// </summary>
+        /// <param name="condition">Condition.</param>
+        /// <param name="argName">Name of the argument.</param>
+        /// <param name="message">Message.</param>
+        public static void Ensure(bool condition, string argName, string message)
+        {
+            if (!condition)
+                throw new ArgumentException(string.Format("'{0}' argument is invalid: {1}", argName, message), 
+                    argName);
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ignite/blob/8df6b935/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Common/IFutureConverter.cs
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Common/IFutureConverter.cs b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Common/IFutureConverter.cs
new file mode 100644
index 0000000..4169c61
--- /dev/null
+++ b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Common/IFutureConverter.cs
@@ -0,0 +1,32 @@
+/*
+ * 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.
+ */
+
+namespace Apache.Ignite.Core.Impl.Common
+{
+    using Apache.Ignite.Core.Impl.Portable.IO;
+
+    /// <summary>
+    /// Marshals and converts future value.
+    /// </summary>
+    public interface IFutureConverter<out T>
+    {
+        /// <summary>
+        /// Reads and converts a value.
+        /// </summary>
+        T Convert(IPortableStream stream);
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ignite/blob/8df6b935/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Common/IFutureInternal.cs
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Common/IFutureInternal.cs b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Common/IFutureInternal.cs
new file mode 100644
index 0000000..8547545
--- /dev/null
+++ b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Common/IFutureInternal.cs
@@ -0,0 +1,45 @@
+/*
+ * 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.
+ */
+
+namespace Apache.Ignite.Core.Impl.Common
+{
+    using System;
+    using Apache.Ignite.Core.Impl.Portable.IO;
+
+    /// <summary>
+    /// Internal future interface.
+    /// </summary>
+    public interface IFutureInternal
+    {
+        /// <summary>
+        /// Set result from stream.
+        /// </summary>
+        /// <param name="stream">Stream.</param>
+        void OnResult(IPortableStream stream);
+
+        /// <summary>
+        /// Set null result.
+        /// </summary>
+        void OnNullResult();
+
+        /// <summary>
+        /// Set error result.
+        /// </summary>
+        /// <param name="err">Exception.</param>
+        void OnError(Exception err);
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ignite/blob/8df6b935/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Common/LoadedAssembliesResolver.cs
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Common/LoadedAssembliesResolver.cs b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Common/LoadedAssembliesResolver.cs
new file mode 100644
index 0000000..c158d5c
--- /dev/null
+++ b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Common/LoadedAssembliesResolver.cs
@@ -0,0 +1,96 @@
+/*
+ * 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.
+ */
+
+namespace Apache.Ignite.Core.Impl.Common
+{
+    using System;
+    using System.Collections.Generic;
+    using System.Diagnostics.CodeAnalysis;
+    using System.Reflection;
+
+    /// <summary>
+    /// Resolves loaded assemblies by name.
+    /// </summary>
+    public class LoadedAssembliesResolver
+    {
+        // The lazy singleton instance.
+        private static readonly Lazy<LoadedAssembliesResolver> LazyInstance = new Lazy<LoadedAssembliesResolver>();
+
+        // Assemblies map.
+        private volatile Dictionary<string, Assembly> _map;
+
+        /// <summary>
+        /// Initializes a new instance of the <see cref="LoadedAssembliesResolver"/> class.
+        /// </summary>
+        public LoadedAssembliesResolver()
+        {
+            lock (this)
+            {
+                AppDomain.CurrentDomain.AssemblyLoad += CurrentDomain_AssemblyLoad;
+
+                UpdateMap();
+            }
+        }
+
+        /// <summary>
+        /// Handles the AssemblyLoad event of the AppDomain.
+        /// </summary>
+        /// <param name="sender">The source of the event.</param>
+        /// <param name="args">The <see cref="AssemblyLoadEventArgs"/> instance containing the event data.</param>
+        private void CurrentDomain_AssemblyLoad(object sender, AssemblyLoadEventArgs args)
+        {
+            lock (this)
+            {
+                UpdateMap();
+            }
+        }
+
+        /// <summary>
+        /// Updates the assembly map according to the current list of loaded assemblies.
+        /// </summary>
+        private void UpdateMap()
+        {
+            var assemblies = AppDomain.CurrentDomain.GetAssemblies();
+
+            _map = new Dictionary<string, Assembly>(assemblies.Length);
+
+            foreach (var assembly in assemblies)
+                _map[assembly.FullName] = assembly;
+        }
+
+        /// <summary>
+        /// Gets the singleton instance.
+        /// </summary>
+        public static LoadedAssembliesResolver Instance
+        {
+            get { return LazyInstance.Value; }
+        }
+
+        /// <summary>
+        /// Gets the assembly by name.
+        /// </summary>
+        /// <param name="assemblyName">Name of the assembly.</param>
+        /// <returns>Assembly with specified name, or null.</returns>
+        [SuppressMessage("ReSharper", "InconsistentlySynchronizedField")]
+        public Assembly GetAssembly(string assemblyName)
+        {
+            Assembly asm;
+
+            return _map.TryGetValue(assemblyName, out asm) ? asm : null;
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ignite/blob/8df6b935/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Common/TypeCaster.cs
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Common/TypeCaster.cs b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Common/TypeCaster.cs
new file mode 100644
index 0000000..d0dd2a9
--- /dev/null
+++ b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Common/TypeCaster.cs
@@ -0,0 +1,72 @@
+/*
+ * 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.
+ */
+
+namespace Apache.Ignite.Core.Impl.Common
+{
+    using System;
+    using System.Linq.Expressions;
+
+    /// <summary>
+    /// Does type casts without extra boxing. 
+    /// Should be used when casting compile-time incompatible value types instead of "(T)(object)x".
+    /// </summary>
+    /// <typeparam name="T">Target type</typeparam>
+    public static class TypeCaster<T>
+    {
+        /// <summary>
+        /// Efficiently casts an object from TFrom to T.
+        /// Does not cause boxing for value types.
+        /// </summary>
+        /// <typeparam name="TFrom">Source type to cast from.</typeparam>
+        /// <param name="obj">The object to cast.</param>
+        /// <returns>Casted object.</returns>
+        public static T Cast<TFrom>(TFrom obj)
+        {
+            return Casters<TFrom>.Caster(obj);
+        }
+
+        /// <summary>
+        /// Inner class serving as a cache.
+        /// </summary>
+        private static class Casters<TFrom>
+        {
+            /// <summary>
+            /// Compiled caster delegate.
+            /// </summary>
+            internal static readonly Func<TFrom, T> Caster = Compile();
+
+            /// <summary>
+            /// Compiles caster delegate.
+            /// </summary>
+            private static Func<TFrom, T> Compile()
+            {
+                if (typeof (T) == typeof (TFrom))
+                {
+                    // Just return what we have
+                    var pExpr = Expression.Parameter(typeof(TFrom));
+                    
+                    return Expression.Lambda<Func<TFrom, T>>(pExpr, pExpr).Compile();
+                }
+
+                var paramExpr = Expression.Parameter(typeof(TFrom));
+                var convertExpr = Expression.Convert(paramExpr, typeof(T));
+
+                return Expression.Lambda<Func<TFrom, T>>(convertExpr, paramExpr).Compile();
+            }
+        }
+    }
+}
\ No newline at end of file


[14/59] [abbrv] ignite git commit: ignite-1258: portable objects API support in Ignite

Posted by vk...@apache.org.
ignite-1258: portable objects API support in Ignite


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

Branch: refs/heads/ignite-884
Commit: 878dcd924be66b3bdf92de3ec07afe3cafc4dc82
Parents: 2ce0209
Author: Denis Magda <dm...@gridgain.com>
Authored: Tue Aug 25 10:05:15 2015 +0300
Committer: Denis Magda <dm...@gridgain.com>
Committed: Tue Aug 25 10:05:16 2015 +0300

----------------------------------------------------------------------
 modules/core/pom.xml                            |   21 +
 .../src/main/java/org/apache/ignite/Ignite.java |    7 +
 .../java/org/apache/ignite/IgniteCache.java     |   41 +
 .../java/org/apache/ignite/IgnitePortables.java |  362 ++
 .../configuration/CacheConfiguration.java       |   40 +
 .../ignite/internal/GridKernalContextImpl.java  |    3 +-
 .../apache/ignite/internal/IgniteKernal.java    |    8 +-
 .../communication/GridIoMessageFactory.java     |    6 +
 .../portable/GridPortableMarshaller.java        |  304 ++
 .../portable/PortableAbstractLazyValue.java     |   57 +
 .../internal/portable/PortableBuilderEnum.java  |  114 +
 .../internal/portable/PortableBuilderImpl.java  |  519 +++
 .../portable/PortableBuilderReader.java         |  775 ++++
 .../PortableBuilderSerializationAware.java      |   29 +
 .../portable/PortableBuilderSerializer.java     |  210 +
 .../portable/PortableClassDescriptor.java       | 1344 +++++++
 .../internal/portable/PortableContext.java      | 1089 ++++++
 .../portable/PortableEnumArrayLazyValue.java    |  111 +
 .../portable/PortableLazyArrayList.java         |  156 +
 .../portable/PortableLazyLinkedList.java        |  210 +
 .../internal/portable/PortableLazyMap.java      |  214 +
 .../internal/portable/PortableLazyMapEntry.java |   66 +
 .../internal/portable/PortableLazySet.java      |   89 +
 .../internal/portable/PortableLazyValue.java    |   28 +
 .../portable/PortableMetaDataCollector.java     |  253 ++
 .../portable/PortableMetaDataHandler.java       |   43 +
 .../internal/portable/PortableMetaDataImpl.java |  140 +
 .../portable/PortableObjectArrayLazyValue.java  |   89 +
 .../internal/portable/PortableObjectEx.java     |  213 +
 .../internal/portable/PortableObjectImpl.java   |  383 ++
 .../portable/PortableObjectOffheapImpl.java     |  238 ++
 .../portable/PortablePlainLazyValue.java        |   47 +
 .../portable/PortablePlainPortableObject.java   |   50 +
 .../internal/portable/PortablePrimitives.java   |  773 ++++
 .../internal/portable/PortableRawReaderEx.java  |   33 +
 .../internal/portable/PortableRawWriterEx.java  |   44 +
 .../portable/PortableReaderContext.java         |   83 +
 .../internal/portable/PortableReaderExImpl.java | 2949 ++++++++++++++
 .../PortableThreadLocalMemoryAllocator.java     |  163 +
 .../ignite/internal/portable/PortableUtils.java |  419 ++
 .../portable/PortableValueWithType.java         |   74 +
 .../internal/portable/PortableWriterExImpl.java | 1769 +++++++++
 .../ignite/internal/portable/package-info.java  |   22 +
 .../streams/PortableAbstractInputStream.java    |  343 ++
 .../streams/PortableAbstractOutputStream.java   |  323 ++
 .../streams/PortableAbstractStream.java         |   82 +
 .../streams/PortableHeapInputStream.java        |  134 +
 .../streams/PortableHeapOutputStream.java       |  155 +
 .../portable/streams/PortableInputStream.java   |  168 +
 .../streams/PortableMemoryAllocator.java        |   76 +
 .../streams/PortableOffheapInputStream.java     |  129 +
 .../streams/PortableOffheapOutputStream.java    |  169 +
 .../portable/streams/PortableOutputStream.java  |  165 +
 .../streams/PortableSimpleMemoryAllocator.java  |   67 +
 .../portable/streams/PortableStream.java        |   53 +
 .../internal/portable/streams/package-info.java |   22 +
 .../processors/cache/GridCacheProcessor.java    |    7 +
 .../processors/cache/IgniteCacheProxy.java      |    5 +
 .../CacheDefaultPortableAffinityKeyMapper.java  |   51 +
 .../portable/CacheObjectPortableContext.java    |  187 +
 .../portable/CacheObjectPortableProcessor.java  |  101 +
 .../CacheObjectPortableProcessorImpl.java       |  956 +++++
 .../cache/portable/IgnitePortablesImpl.java     |  176 +
 .../cache/portable/PortableMetaDataKey.java     |   80 +
 .../processors/cache/portable/package-info.java |   22 +
 .../cache/store/CacheOsStoreManager.java        |    3 +-
 .../portable/GridPortableInputStream.java       |  168 -
 .../portable/GridPortableOutputStream.java      |  165 -
 .../processors/portable/GridPortableStream.java |   53 -
 .../processors/portable/package-info.java       |   22 -
 .../marshaller/portable/PortableMarshaller.java |  347 ++
 .../marshaller/portable/package-info.java       |   22 +
 .../apache/ignite/portable/PortableBuilder.java |  138 +
 .../ignite/portable/PortableException.java      |   58 +
 .../ignite/portable/PortableIdMapper.java       |   56 +
 .../portable/PortableInvalidClassException.java |   58 +
 .../ignite/portable/PortableMarshalAware.java   |   48 +
 .../ignite/portable/PortableMetadata.java       |   63 +
 .../apache/ignite/portable/PortableObject.java  |  153 +
 .../portable/PortableProtocolVersion.java       |   41 +
 .../ignite/portable/PortableRawReader.java      |  233 ++
 .../ignite/portable/PortableRawWriter.java      |  218 ++
 .../apache/ignite/portable/PortableReader.java  |  283 ++
 .../ignite/portable/PortableSerializer.java     |   49 +
 .../portable/PortableTypeConfiguration.java     |  197 +
 .../apache/ignite/portable/PortableWriter.java  |  265 ++
 .../apache/ignite/portable/package-info.java    |   22 +
 .../resources/META-INF/classnames.properties    |  285 +-
 .../GridPortableAffinityKeySelfTest.java        |  215 +
 .../GridPortableBuilderAdditionalSelfTest.java  | 1001 +++++
 .../portable/GridPortableBuilderSelfTest.java   | 1007 +++++
 ...eBuilderStringAsCharsAdditionalSelfTest.java |   28 +
 ...ridPortableBuilderStringAsCharsSelfTest.java |   28 +
 ...idPortableMarshallerCtxDisabledSelfTest.java |  128 +
 .../GridPortableMarshallerSelfTest.java         | 3691 ++++++++++++++++++
 .../GridPortableMetaDataDisabledSelfTest.java   |  218 ++
 .../portable/GridPortableMetaDataSelfTest.java  |  343 ++
 .../portable/GridPortableWildcardsSelfTest.java |  480 +++
 .../GridPortableMarshalerAwareTestClass.java    |   62 +
 .../mutabletest/GridPortableTestClasses.java    |  425 ++
 .../portable/mutabletest/package-info.java      |   22 +
 .../ignite/internal/portable/package-info.java  |   22 +
 .../portable/test/GridPortableTestClass1.java   |   28 +
 .../portable/test/GridPortableTestClass2.java   |   24 +
 .../internal/portable/test/package-info.java    |   22 +
 .../test/subpackage/GridPortableTestClass3.java |   24 +
 .../portable/test/subpackage/package-info.java  |   22 +
 ...ClientNodePortableMetadataMultinodeTest.java |  277 ++
 ...GridCacheClientNodePortableMetadataTest.java |  280 ++
 ...ableObjectsAbstractDataStreamerSelfTest.java |  183 +
 ...bleObjectsAbstractMultiThreadedSelfTest.java |  222 ++
 ...ridCachePortableObjectsAbstractSelfTest.java |  958 +++++
 .../GridCachePortableStoreAbstractSelfTest.java |  294 ++
 .../GridCachePortableStoreObjectsSelfTest.java  |   55 +
 ...GridCachePortableStorePortablesSelfTest.java |   67 +
 ...ridPortableCacheEntryMemorySizeSelfTest.java |   52 +
 ...leDuplicateIndexObjectsAbstractSelfTest.java |  153 +
 .../DataStreamProcessorPortableSelfTest.java    |   67 +
 .../GridDataStreamerImplSelfTest.java           |  338 ++
 ...ridCacheAffinityRoutingPortableSelfTest.java |   48 +
 ...lyPortableDataStreamerMultiNodeSelfTest.java |   29 +
 ...rtableDataStreamerMultithreadedSelfTest.java |   46 +
 ...artitionedOnlyPortableMultiNodeSelfTest.java |   28 +
 ...tionedOnlyPortableMultithreadedSelfTest.java |   46 +
 .../GridCacheMemoryModePortableSelfTest.java    |   36 +
 ...acheOffHeapTieredAtomicPortableSelfTest.java |   48 +
 ...eapTieredEvictionAtomicPortableSelfTest.java |   96 +
 ...heOffHeapTieredEvictionPortableSelfTest.java |   96 +
 .../GridCacheOffHeapTieredPortableSelfTest.java |   48 +
 ...ateIndexObjectPartitionedAtomicSelfTest.java |   37 +
 ...xObjectPartitionedTransactionalSelfTest.java |   40 +
 ...AtomicNearDisabledOffheapTieredSelfTest.java |   29 +
 ...rtableObjectsAtomicNearDisabledSelfTest.java |   50 +
 ...tableObjectsAtomicOffheapTieredSelfTest.java |   29 +
 .../GridCachePortableObjectsAtomicSelfTest.java |   50 +
 ...tionedNearDisabledOffheapTieredSelfTest.java |   30 +
 ...eObjectsPartitionedNearDisabledSelfTest.java |   50 +
 ...ObjectsPartitionedOffheapTieredSelfTest.java |   30 +
 ...CachePortableObjectsPartitionedSelfTest.java |   50 +
 ...sNearPartitionedByteArrayValuesSelfTest.java |   41 +
 ...sPartitionedOnlyByteArrayValuesSelfTest.java |   42 +
 ...dCachePortableObjectsReplicatedSelfTest.java |   50 +
 ...CachePortableObjectsAtomicLocalSelfTest.java |   32 +
 ...rtableObjectsLocalOffheapTieredSelfTest.java |   29 +
 .../GridCachePortableObjectsLocalSelfTest.java  |   50 +
 .../ignite/testframework/junits/IgniteMock.java |    5 +
 .../multijvm/IgniteCacheProcessProxy.java       |    5 +
 .../junits/multijvm/IgniteProcessProxy.java     |    5 +
 .../IgnitePortableCacheFullApiTestSuite.java    |   38 +
 .../IgnitePortableCacheTestSuite.java           |   86 +
 .../IgnitePortableObjectsTestSuite.java         |   74 +
 .../ignite/portable/test1/1.1/test1-1.1.jar     |  Bin 0 -> 2548 bytes
 .../ignite/portable/test1/1.1/test1-1.1.pom     |    9 +
 .../portable/test1/maven-metadata-local.xml     |   12 +
 .../ignite/portable/test2/1.1/test2-1.1.jar     |  Bin 0 -> 1361 bytes
 .../ignite/portable/test2/1.1/test2-1.1.pom     |    9 +
 .../portable/test2/maven-metadata-local.xml     |   12 +
 .../IgnitePortableCacheQueryTestSuite.java      |   95 +
 .../platform/memory/PlatformInputStream.java    |    4 +-
 .../platform/memory/PlatformOutputStream.java   |    4 +-
 .../org/apache/ignite/IgniteSpringBean.java     |    7 +
 parent/pom.xml                                  |    8 +
 162 files changed, 31734 insertions(+), 541 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/pom.xml
----------------------------------------------------------------------
diff --git a/modules/core/pom.xml b/modules/core/pom.xml
index c8abe15..6f1cbf8 100644
--- a/modules/core/pom.xml
+++ b/modules/core/pom.xml
@@ -33,6 +33,13 @@
     <artifactId>ignite-core</artifactId>
     <version>1.4.1-SNAPSHOT</version>
 
+    <repositories>
+        <repository>
+            <id>ignite-portables-test-repo</id>
+            <url>file://${basedir}/src/test/portables/repo</url>
+        </repository>
+    </repositories>
+
     <dependencies>
         <dependency>
             <groupId>javax.cache</groupId>
@@ -164,6 +171,20 @@
             <version>2.4</version>
             <scope>test</scope>
         </dependency>
+
+        <dependency>
+            <groupId>org.apache.ignite.portable</groupId>
+            <artifactId>test1</artifactId>
+            <version>1.1</version>
+            <scope>test</scope>
+        </dependency>
+
+        <dependency>
+            <groupId>org.apache.ignite.portable</groupId>
+            <artifactId>test2</artifactId>
+            <version>1.1</version>
+            <scope>test</scope>
+        </dependency>
     </dependencies>
 
     <build>

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/Ignite.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/Ignite.java b/modules/core/src/main/java/org/apache/ignite/Ignite.java
index 209946b..d70a3a1 100644
--- a/modules/core/src/main/java/org/apache/ignite/Ignite.java
+++ b/modules/core/src/main/java/org/apache/ignite/Ignite.java
@@ -455,6 +455,13 @@ public interface Ignite extends AutoCloseable {
     public <T extends IgnitePlugin> T plugin(String name) throws PluginNotFoundException;
 
     /**
+     * Gets an instance of {@link IgnitePortables} interface.
+     *
+     * @return Instance of {@link IgnitePortables} interface.
+     */
+    public IgnitePortables portables();
+
+    /**
      * Closes {@code this} instance of grid. This method is identical to calling
      * {@link G#stop(String, boolean) G.stop(gridName, true)}.
      * <p>

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/IgniteCache.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/IgniteCache.java b/modules/core/src/main/java/org/apache/ignite/IgniteCache.java
index fd0112c..c9ff955 100644
--- a/modules/core/src/main/java/org/apache/ignite/IgniteCache.java
+++ b/modules/core/src/main/java/org/apache/ignite/IgniteCache.java
@@ -25,6 +25,7 @@ import org.apache.ignite.cache.store.*;
 import org.apache.ignite.cluster.*;
 import org.apache.ignite.configuration.*;
 import org.apache.ignite.lang.*;
+import org.apache.ignite.marshaller.portable.*;
 import org.apache.ignite.mxbean.*;
 import org.jetbrains.annotations.*;
 
@@ -35,7 +36,9 @@ import javax.cache.expiry.*;
 import javax.cache.integration.*;
 import javax.cache.processor.*;
 import java.io.*;
+import java.sql.*;
 import java.util.*;
+import java.util.Date;
 import java.util.concurrent.*;
 import java.util.concurrent.locks.*;
 
@@ -112,6 +115,44 @@ public interface IgniteCache<K, V> extends javax.cache.Cache<K, V>, IgniteAsyncS
     public IgniteCache<K, V> withNoRetries();
 
     /**
+     * Returns cache that will operate with portable objects.
+     * <p>
+     * Cache returned by this method will not be forced to deserialize portable objects,
+     * so keys and values will be returned from cache API methods without changes. Therefore,
+     * signature of the cache can contain only following types:
+     * <ul>
+     *     <li><code>org.apache.ignite.portable.PortableObject</code> for portable classes</li>
+     *     <li>All primitives (byte, int, ...) and there boxed versions (Byte, Integer, ...)</li>
+     *     <li>Arrays of primitives (byte[], int[], ...)</li>
+     *     <li>{@link String} and array of {@link String}s</li>
+     *     <li>{@link UUID} and array of {@link UUID}s</li>
+     *     <li>{@link Date} and array of {@link Date}s</li>
+     *     <li>{@link Timestamp} and array of {@link Timestamp}s</li>
+     *     <li>Enums and array of enums</li>
+     *     <li>
+     *         Maps, collections and array of objects (but objects inside
+     *         them will still be converted if they are portable)
+     *     </li>
+     * </ul>
+     * <p>
+     * For example, if you use {@link Integer} as a key and {@code Value} class as a value
+     * (which will be stored in portable format), you should acquire following projection
+     * to avoid deserialization:
+     * <pre>
+     * IgniteCache<Integer, PortableObject> prj = cache.withKeepPortable();
+     *
+     * // Value is not deserialized and returned in portable format.
+     * PortableObject po = prj.get(1);
+     * </pre>
+     * <p>
+     * Note that this method makes sense only if cache is working in portable mode ({@link PortableMarshaller} is used).
+     * If not, this method is no-op and will return current cache.
+     *
+     * @return New cache instance for portable objects.
+     */
+    public <K1, V1> IgniteCache<K1, V1> withKeepPortable();
+
+    /**
      * Executes {@link #localLoadCache(IgniteBiPredicate, Object...)} on all cache nodes.
      *
      * @param p Optional predicate (may be {@code null}). If provided, will be used to

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/IgnitePortables.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/IgnitePortables.java b/modules/core/src/main/java/org/apache/ignite/IgnitePortables.java
new file mode 100644
index 0000000..6800edc
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/IgnitePortables.java
@@ -0,0 +1,362 @@
+/*
+ * 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;
+
+import org.apache.ignite.internal.processors.cache.*;
+import org.apache.ignite.portable.*;
+import org.apache.ignite.marshaller.portable.*;
+
+import org.jetbrains.annotations.*;
+
+import java.sql.*;
+import java.util.*;
+import java.util.Date;
+
+/**
+ * Defines portable objects functionality. With portable objects you are able to:
+ * <ul>
+ * <li>Seamlessly interoperate between Java, .NET, and C++.</li>
+ * <li>Make any object portable with zero code change to your existing code.</li>
+ * <li>Nest portable objects within each other.</li>
+ * <li>Automatically handle {@code circular} or {@code null} references.</li>
+ * <li>Automatically convert collections and maps between Java, .NET, and C++.</li>
+ * <li>
+ *      Optionally avoid deserialization of objects on the server side
+ *      (objects are stored in {@link PortableObject} format).
+ * </li>
+ * <li>Avoid need to have concrete class definitions on the server side.</li>
+ * <li>Dynamically change structure of the classes without having to restart the cluster.</li>
+ * <li>Index into portable objects for querying purposes.</li>
+ * </ul>
+ * <h1 class="header">Working With Portables Directly</h1>
+ * Once an object is defined as portable,
+ * Ignite will always store it in memory in the portable (i.e. binary) format.
+ * User can choose to work either with the portable format or with the deserialized form
+ * (assuming that class definitions are present in the classpath).
+ * <p>
+ * To work with the portable format directly, user should create a special cache projection
+ * using {@link IgniteCache#withKeepPortable()} method and then retrieve individual fields as needed:
+ * <pre name=code class=java>
+ * IgniteCache&lt;PortableObject, PortableObject&gt; prj = cache.withKeepPortable();
+ *
+ * // Convert instance of MyKey to portable format.
+ * // We could also use PortableBuilder to create the key in portable format directly.
+ * PortableObject key = grid.portables().toPortable(new MyKey());
+ *
+ * PortableObject val = prj.get(key);
+ *
+ * String field = val.field("myFieldName");
+ * </pre>
+ * Alternatively, if we have class definitions in the classpath, we may choose to work with deserialized
+ * typed objects at all times. In this case we do incur the deserialization cost. However, if
+ * {@link PortableMarshaller#isKeepDeserialized()} is {@code true} then Ignite will only deserialize on the first access
+ * and will cache the deserialized object, so it does not have to be deserialized again:
+ * <pre name=code class=java>
+ * IgniteCache&lt;MyKey.class, MyValue.class&gt; cache = grid.cache(null);
+ *
+ * MyValue val = cache.get(new MyKey());
+ *
+ * // Normal java getter.
+ * String fieldVal = val.getMyFieldName();
+ * </pre>
+ * If we used, for example, one of the automatically handled portable types for a key, like integer,
+ * and still wanted to work with binary portable format for values, then we would declare cache projection
+ * as follows:
+ * <pre name=code class=java>
+ * IgniteCache&lt;Integer.class, PortableObject&gt; prj = cache.withKeepPortable();
+ * </pre>
+ * <h1 class="header">Automatic Portable Types</h1>
+ * Note that only portable classes are converted to {@link PortableObject} format. Following
+ * classes are never converted (e.g., {@link #toPortable(Object)} method will return original
+ * object, and instances of these classes will be stored in cache without changes):
+ * <ul>
+ *     <li>All primitives (byte, int, ...) and there boxed versions (Byte, Integer, ...)</li>
+ *     <li>Arrays of primitives (byte[], int[], ...)</li>
+ *     <li>{@link String} and array of {@link String}s</li>
+ *     <li>{@link UUID} and array of {@link UUID}s</li>
+ *     <li>{@link Date} and array of {@link Date}s</li>
+ *     <li>{@link Timestamp} and array of {@link Timestamp}s</li>
+ *     <li>Enums and array of enums</li>
+ *     <li>
+ *         Maps, collections and array of objects (but objects inside
+ *         them will still be converted if they are portable)
+ *     </li>
+ * </ul>
+ * <h1 class="header">Working With Maps and Collections</h1>
+ * All maps and collections in the portable objects are serialized automatically. When working
+ * with different platforms, e.g. C++ or .NET, Ignite will automatically pick the most
+ * adequate collection or map in either language. For example, {@link ArrayList} in Java will become
+ * {@code List} in C#, {@link LinkedList} in Java is {@link LinkedList} in C#, {@link HashMap}
+ * in Java is {@code Dictionary} in C#, and {@link TreeMap} in Java becomes {@code SortedDictionary}
+ * in C#, etc.
+ * <h1 class="header">Building Portable Objects</h1>
+ * Ignite comes with {@link PortableBuilder} which allows to build portable objects dynamically:
+ * <pre name=code class=java>
+ * PortableBuilder builder = Ignition.ignite().portables().builder();
+ *
+ * builder.typeId("MyObject");
+ *
+ * builder.stringField("fieldA", "A");
+ * build.intField("fieldB", "B");
+ *
+ * PortableObject portableObj = builder.build();
+ * </pre>
+ * For the cases when class definition is present
+ * in the class path, it is also possible to populate a standard POJO and then
+ * convert it to portable format, like so:
+ * <pre name=code class=java>
+ * MyObject obj = new MyObject();
+ *
+ * obj.setFieldA("A");
+ * obj.setFieldB(123);
+ *
+ * PortableObject portableObj = Ignition.ignite().portables().toPortable(obj);
+ * </pre>
+ * NOTE: you don't need to convert typed objects to portable format before storing
+ * them in cache, Ignite will do that automatically.
+ * <h1 class="header">Portable Metadata</h1>
+ * Even though Ignite portable protocol only works with hash codes for type and field names
+ * to achieve better performance, Ignite provides metadata for all portable types which
+ * can be queried ar runtime via any of the {@link IgnitePortables#metadata(Class)}
+ * methods. Having metadata also allows for proper formatting of {@code PortableObject#toString()} method,
+ * even when portable objects are kept in binary format only, which may be necessary for audit reasons.
+ * <h1 class="header">Dynamic Structure Changes</h1>
+ * Since objects are always cached in the portable binary format, server does not need to
+ * be aware of the class definitions. Moreover, if class definitions are not present or not
+ * used on the server, then clients can continuously change the structure of the portable
+ * objects without having to restart the cluster. For example, if one client stores a
+ * certain class with fields A and B, and another client stores the same class with
+ * fields B and C, then the server-side portable object will have the fields A, B, and C.
+ * As the structure of a portable object changes, the new fields become available for SQL queries
+ * automatically.
+ * <h1 class="header">Configuration</h1>
+ * By default all your objects are considered as portables and no specific configuration is needed.
+ * However, in some cases, like when an object is used by both Java and .Net, you may need to specify portable objects
+ * explicitly by calling {@link PortableMarshaller#setClassNames(Collection)}.
+ * The only requirement Ignite imposes is that your object has an empty
+ * constructor. Note, that since server side does not have to know the class definition,
+ * you only need to list portable objects in configuration on the client side. However, if you
+ * list them on the server side as well, then you get the ability to deserialize portable objects
+ * into concrete types on the server as well as on the client.
+ * <p>
+ * Here is an example of portable configuration (note that star (*) notation is supported):
+ * <pre name=code class=xml>
+ * ...
+ * &lt;!-- Explicit portable objects configuration. --&gt;
+ * &lt;property name="marshaller"&gt;
+ *     &lt;bean class="org.apache.ignite.marshaller.portable.PortableMarshaller"&gt;
+ *         &lt;property name="classNames"&gt;
+ *             &lt;list&gt;
+ *                 &lt;value&gt;my.package.for.portable.objects.*&lt;/value&gt;
+ *                 &lt;value&gt;org.apache.ignite.examples.client.portable.Employee&lt;/value&gt;
+ *             &lt;/list&gt;
+ *         &lt;/property&gt;
+ *     &lt;/bean&gt;
+ * &lt;/property&gt;
+ * ...
+ * </pre>
+ * or from code:
+ * <pre name=code class=java>
+ * IgniteConfiguration cfg = new IgniteConfiguration();
+ *
+ * PortableMarshaller marsh = new PortableMarshaller();
+ *
+ * marsh.setClassNames(Arrays.asList(
+ *     Employee.class.getName(),
+ *     Address.class.getName())
+ * );
+ *
+ * cfg.setMarshaller(marsh);
+ * </pre>
+ * You can also specify class name for a portable object via {@link PortableTypeConfiguration}.
+ * Do it in case if you need to override other configuration properties on per-type level, like
+ * ID-mapper, or serializer.
+ * <h1 class="header">Custom Affinity Keys</h1>
+ * Often you need to specify an alternate key (not the cache key) for affinity routing whenever
+ * storing objects in cache. For example, if you are caching {@code Employee} object with
+ * {@code Organization}, and want to colocate employees with organization they work for,
+ * so you can process them together, you need to specify an alternate affinity key.
+ * With portable objects you would have to do it as following:
+ * <pre name=code class=xml>
+ * &lt;property name="marshaller"&gt;
+ *     &lt;bean class="org.gridgain.grid.marshaller.portable.PortableMarshaller"&gt;
+ *         ...
+ *         &lt;property name="typeConfigurations"&gt;
+ *             &lt;list&gt;
+ *                 &lt;bean class="org.apache.ignite.portable.PortableTypeConfiguration"&gt;
+ *                     &lt;property name="className" value="org.apache.ignite.examples.client.portable.EmployeeKey"/&gt;
+ *                     &lt;property name="affinityKeyFieldName" value="organizationId"/&gt;
+ *                 &lt;/bean&gt;
+ *             &lt;/list&gt;
+ *         &lt;/property&gt;
+ *         ...
+ *     &lt;/bean&gt;
+ * &lt;/property&gt;
+ * </pre>
+ * <h1 class="header">Serialization</h1>
+ * Serialization and deserialization works out-of-the-box in Ignite. However, you can provide your own custom
+ * serialization logic by optionally implementing {@link PortableMarshalAware} interface, like so:
+ * <pre name=code class=java>
+ * public class Address implements PortableMarshalAware {
+ *     private String street;
+ *     private int zip;
+ *
+ *     // Empty constructor required for portable deserialization.
+ *     public Address() {}
+ *
+ *     &#64;Override public void writePortable(PortableWriter writer) throws PortableException {
+ *         writer.writeString("street", street);
+ *         writer.writeInt("zip", zip);
+ *     }
+ *
+ *     &#64;Override public void readPortable(PortableReader reader) throws PortableException {
+ *         street = reader.readString("street");
+ *         zip = reader.readInt("zip");
+ *     }
+ * }
+ * </pre>
+ * Alternatively, if you cannot change class definitions, you can provide custom serialization
+ * logic in {@link PortableSerializer} either globally in {@link PortableMarshaller} or
+ * for a specific type via {@link PortableTypeConfiguration} instance.
+ * <p>
+ * Similar to java serialization you can use {@code writeReplace()} and {@code readResolve()} methods.
+ * <ul>
+ *     <li>
+ *         {@code readResolve} is defined as follows: {@code ANY-ACCESS-MODIFIER Object readResolve()}.
+ *         It may be used to replace the de-serialized object by another one of your choice.
+ *     </li>
+ *     <li>
+ *          {@code writeReplace} is defined as follows: {@code ANY-ACCESS-MODIFIER Object writeReplace()}. This method
+ *          allows the developer to provide a replacement object that will be serialized instead of the original one.
+ *     </li>
+ * </ul>
+ *
+ * <h1 class="header">Custom ID Mappers</h1>
+ * Ignite implementation uses name hash codes to generate IDs for class names or field names
+ * internally. However, in cases when you want to provide your own ID mapping schema,
+ * you can provide your own {@link PortableIdMapper} implementation.
+ * <p>
+ * ID-mapper may be provided either globally in {@link PortableMarshaller},
+ * or for a specific type via {@link PortableTypeConfiguration} instance.
+ * <h1 class="header">Query Indexing</h1>
+ * Portable objects can be indexed for querying by specifying index fields in
+ * {@link org.apache.ignite.cache.CacheTypeMetadata} inside of specific
+ * {@link org.apache.ignite.configuration.CacheConfiguration} instance,
+ * like so:
+ * <pre name=code class=xml>
+ * ...
+ * &lt;bean class="org.apache.ignite.cache.CacheConfiguration"&gt;
+ *     ...
+ *     &lt;property name="typeMetadata"&gt;
+ *         &lt;list&gt;
+ *             &lt;bean class="CacheTypeMetadata"&gt;
+ *                 &lt;property name="type" value="Employee"/&gt;
+ *
+ *                 &lt;!-- Fields to index in ascending order. --&gt;
+ *                 &lt;property name="ascendingFields"&gt;
+ *                     &lt;map&gt;
+ *                     &lt;entry key="name" value="java.lang.String"/&gt;
+ *
+ *                         &lt;!-- Nested portable objects can also be indexed. --&gt;
+ *                         &lt;entry key="address.zip" value="java.lang.Integer"/&gt;
+ *                     &lt;/map&gt;
+ *                 &lt;/property&gt;
+ *             &lt;/bean&gt;
+ *         &lt;/list&gt;
+ *     &lt;/property&gt;
+ * &lt;/bean&gt;
+ * </pre>
+ */
+public interface IgnitePortables {
+    /**
+     * Gets type ID for given type name.
+     *
+     * @param typeName Type name.
+     * @return Type ID.
+     */
+    public int typeId(String typeName);
+
+    /**
+     * Converts provided object to instance of {@link PortableObject}.
+     *
+     * @param obj Object to convert.
+     * @return Converted object.
+     * @throws PortableException In case of error.
+     */
+    public <T> T toPortable(@Nullable Object obj) throws PortableException;
+
+    /**
+     * Creates new portable builder.
+     *
+     * @param typeId ID of the type.
+     * @return Newly portable builder.
+     */
+    public PortableBuilder builder(int typeId);
+
+    /**
+     * Creates new portable builder.
+     *
+     * @param typeName Type name.
+     * @return Newly portable builder.
+     */
+    public PortableBuilder builder(String typeName);
+
+    /**
+     * Creates portable builder initialized by existing portable object.
+     *
+     * @param portableObj Portable object to initialize builder.
+     * @return Portable builder.
+     */
+    public PortableBuilder builder(PortableObject portableObj);
+
+    /**
+     * Gets metadata for provided class.
+     *
+     * @param cls Class.
+     * @return Metadata.
+     * @throws PortableException In case of error.
+     */
+    @Nullable public PortableMetadata metadata(Class<?> cls) throws PortableException;
+
+    /**
+     * Gets metadata for provided class name.
+     *
+     * @param typeName Type name.
+     * @return Metadata.
+     * @throws PortableException In case of error.
+     */
+    @Nullable public PortableMetadata metadata(String typeName) throws PortableException;
+
+    /**
+     * Gets metadata for provided type ID.
+     *
+     * @param typeId Type ID.
+     * @return Metadata.
+     * @throws PortableException In case of error.
+     */
+    @Nullable public PortableMetadata metadata(int typeId) throws PortableException;
+
+    /**
+     * Gets metadata for all known types.
+     *
+     * @return Metadata.
+     * @throws PortableException In case of error.
+     */
+    public Collection<PortableMetadata> metadata() throws PortableException;
+}
+

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/configuration/CacheConfiguration.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/configuration/CacheConfiguration.java b/modules/core/src/main/java/org/apache/ignite/configuration/CacheConfiguration.java
index 3ad0f01..af2bbe8 100644
--- a/modules/core/src/main/java/org/apache/ignite/configuration/CacheConfiguration.java
+++ b/modules/core/src/main/java/org/apache/ignite/configuration/CacheConfiguration.java
@@ -153,6 +153,10 @@ public class CacheConfiguration<K, V> extends MutableConfiguration<K, V> {
     /** Default size for onheap SQL row cache size. */
     public static final int DFLT_SQL_ONHEAP_ROW_CACHE_SIZE = 10 * 1024;
 
+    /** Default value for keep portable in store behavior .*/
+    @SuppressWarnings({"UnnecessaryBoxing", "BooleanConstructorCall"})
+    public static final Boolean DFLT_KEEP_PORTABLE_IN_STORE  = new Boolean(true);
+
     /** Cache name. */
     private String name;
 
@@ -205,6 +209,9 @@ public class CacheConfiguration<K, V> extends MutableConfiguration<K, V> {
     private Factory storeFactory;
 
     /** */
+    private Boolean keepPortableInStore = DFLT_KEEP_PORTABLE_IN_STORE;
+
+    /** */
     private boolean loadPrevVal = DFLT_LOAD_PREV_VAL;
 
     /** Node group resolver. */
@@ -366,6 +373,7 @@ public class CacheConfiguration<K, V> extends MutableConfiguration<K, V> {
         invalidate = cc.isInvalidate();
         isReadThrough = cc.isReadThrough();
         isWriteThrough = cc.isWriteThrough();
+        keepPortableInStore = cc.isKeepPortableInStore();
         listenerConfigurations = cc.listenerConfigurations;
         loadPrevVal = cc.isLoadPreviousValue();
         longQryWarnTimeout = cc.getLongQueryWarningTimeout();
@@ -806,6 +814,38 @@ public class CacheConfiguration<K, V> extends MutableConfiguration<K, V> {
     }
 
     /**
+     * Flag indicating that {@link CacheStore} implementation
+     * is working with portable objects instead of Java objects.
+     * Default value of this flag is {@link #DFLT_KEEP_PORTABLE_IN_STORE},
+     * because this is recommended behavior from performance standpoint.
+     * <p>
+     * If set to {@code false}, Ignite will deserialize keys and
+     * values stored in portable format before they are passed
+     * to cache store.
+     * <p>
+     * Note that setting this flag to {@code false} can simplify
+     * store implementation in some cases, but it can cause performance
+     * degradation due to additional serializations and deserializations
+     * of portable objects. You will also need to have key and value
+     * classes on all nodes since portables will be deserialized when
+     * store is called.
+     *
+     * @return Keep portables in store flag.
+     */
+    public Boolean isKeepPortableInStore() {
+        return keepPortableInStore;
+    }
+
+    /**
+     * Sets keep portables in store flag.
+     *
+     * @param keepPortableInStore Keep portables in store flag.
+     */
+    public void setKeepPortableInStore(boolean keepPortableInStore) {
+        this.keepPortableInStore = keepPortableInStore;
+    }
+
+    /**
      * Gets key topology resolver to provide mapping from keys to nodes.
      *
      * @return Key topology resolver to provide mapping from keys to nodes.

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/internal/GridKernalContextImpl.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/GridKernalContextImpl.java b/modules/core/src/main/java/org/apache/ignite/internal/GridKernalContextImpl.java
index fd8b50c..01dadfd 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/GridKernalContextImpl.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/GridKernalContextImpl.java
@@ -32,6 +32,7 @@ import org.apache.ignite.internal.managers.loadbalancer.*;
 import org.apache.ignite.internal.managers.swapspace.*;
 import org.apache.ignite.internal.processors.affinity.*;
 import org.apache.ignite.internal.processors.cache.*;
+import org.apache.ignite.internal.processors.cache.portable.*;
 import org.apache.ignite.internal.processors.cacheobject.*;
 import org.apache.ignite.internal.processors.clock.*;
 import org.apache.ignite.internal.processors.closure.*;
@@ -803,7 +804,7 @@ public class GridKernalContextImpl implements GridKernalContext, Externalizable
             return res;
 
         if (cls.equals(IgniteCacheObjectProcessor.class))
-            return (T)new IgniteCacheObjectProcessorImpl(this);
+            return (T)new CacheObjectPortableProcessorImpl(this);
 
         if (cls.equals(CacheConflictResolutionManager.class))
             return null;

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/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 bf47f63..391d3dc 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
@@ -36,6 +36,7 @@ import org.apache.ignite.internal.managers.swapspace.*;
 import org.apache.ignite.internal.processors.*;
 import org.apache.ignite.internal.processors.affinity.*;
 import org.apache.ignite.internal.processors.cache.*;
+import org.apache.ignite.internal.processors.cache.portable.*;
 import org.apache.ignite.internal.processors.cacheobject.*;
 import org.apache.ignite.internal.processors.clock.*;
 import org.apache.ignite.internal.processors.closure.*;
@@ -2666,6 +2667,11 @@ public class IgniteKernal implements IgniteEx, IgniteMXBean, Externalizable {
     }
 
     /** {@inheritDoc} */
+    @Override public IgnitePortables portables() {
+        return ((CacheObjectPortableProcessor)ctx.cacheObjects()).portables();
+    }
+
+    /** {@inheritDoc} */
     @Override public IgniteProductVersion version() {
         return VER;
     }
@@ -2960,7 +2966,7 @@ public class IgniteKernal implements IgniteEx, IgniteMXBean, Externalizable {
             return comp;
 
         if (cls.equals(IgniteCacheObjectProcessor.class))
-            return (T)new IgniteCacheObjectProcessorImpl(ctx);
+            return (T)new CacheObjectPortableProcessorImpl(ctx);
 
         if (cls.equals(DiscoveryNodeValidationProcessor.class))
             return (T)new OsDiscoveryNodeValidationProcessor(ctx);

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/internal/managers/communication/GridIoMessageFactory.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/managers/communication/GridIoMessageFactory.java b/modules/core/src/main/java/org/apache/ignite/internal/managers/communication/GridIoMessageFactory.java
index 7fe8da8..2acfd2b 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/managers/communication/GridIoMessageFactory.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/managers/communication/GridIoMessageFactory.java
@@ -22,6 +22,7 @@ import org.apache.ignite.internal.*;
 import org.apache.ignite.internal.managers.checkpoint.*;
 import org.apache.ignite.internal.managers.deployment.*;
 import org.apache.ignite.internal.managers.eventstorage.*;
+import org.apache.ignite.internal.portable.*;
 import org.apache.ignite.internal.processors.affinity.*;
 import org.apache.ignite.internal.processors.cache.*;
 import org.apache.ignite.internal.processors.cache.distributed.*;
@@ -600,6 +601,11 @@ public class GridIoMessageFactory implements MessageFactory {
 
                 break;
 
+            case 113:
+                msg = new PortableObjectImpl();
+
+                break;
+
             // [-3..112] - this
             // [120..123] - DR
             // [-4..-22] - SQL

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/internal/portable/GridPortableMarshaller.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/portable/GridPortableMarshaller.java b/modules/core/src/main/java/org/apache/ignite/internal/portable/GridPortableMarshaller.java
new file mode 100644
index 0000000..2969261
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/GridPortableMarshaller.java
@@ -0,0 +1,304 @@
+/*
+ * 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.portable;
+
+import org.apache.ignite.internal.portable.streams.*;
+import org.apache.ignite.portable.*;
+
+import org.jetbrains.annotations.*;
+
+/**
+ * Portable objects marshaller.
+ */
+public class GridPortableMarshaller {
+    /** */
+    public static final ThreadLocal<Boolean> KEEP_PORTABLES = new ThreadLocal<Boolean>() {
+        @Override protected Boolean initialValue() {
+            return true;
+        }
+    };
+
+    /** */
+    static final byte OPTM_MARSH = -2;
+
+    /** */
+    public static final byte BYTE = 1;
+
+    /** */
+    public static final byte SHORT = 2;
+
+    /** */
+    public static final byte INT = 3;
+
+    /** */
+    public static final byte LONG = 4;
+
+    /** */
+    public static final byte FLOAT = 5;
+
+    /** */
+    public static final byte DOUBLE = 6;
+
+    /** */
+    public static final byte CHAR = 7;
+
+    /** */
+    public static final byte BOOLEAN = 8;
+
+    /** */
+    public static final byte DECIMAL = 30;
+
+    /** */
+    public static final byte STRING = 9;
+
+    /** */
+    public static final byte UUID = 10;
+
+    /** */
+    public static final byte DATE = 11;
+
+    /** */
+    public static final byte BYTE_ARR = 12;
+
+    /** */
+    public static final byte SHORT_ARR = 13;
+
+    /** */
+    public static final byte INT_ARR = 14;
+
+    /** */
+    public static final byte LONG_ARR = 15;
+
+    /** */
+    public static final byte FLOAT_ARR = 16;
+
+    /** */
+    public static final byte DOUBLE_ARR = 17;
+
+    /** */
+    public static final byte CHAR_ARR = 18;
+
+    /** */
+    public static final byte BOOLEAN_ARR = 19;
+
+    /** */
+    public static final byte DECIMAL_ARR = 31;
+
+    /** */
+    public static final byte STRING_ARR = 20;
+
+    /** */
+    public static final byte UUID_ARR = 21;
+
+    /** */
+    public static final byte DATE_ARR = 22;
+
+    /** */
+    public static final byte OBJ_ARR = 23;
+
+    /** */
+    public static final byte COL = 24;
+
+    /** */
+    public static final byte MAP = 25;
+
+    /** */
+    public static final byte MAP_ENTRY = 26;
+
+    /** */
+    public static final byte PORTABLE_OBJ = 27;
+
+    /** */
+    public static final byte ENUM = 28;
+
+    /** */
+    public static final byte ENUM_ARR = 29;
+
+    /** */
+    public static final byte CLASS = 32;
+
+    /** */
+    public static final byte NULL = (byte)101;
+
+    /** */
+    public static final byte HANDLE = (byte)102;
+
+    /** */
+    public static final byte OBJ = (byte)103;
+
+    /** */
+    static final byte USER_SET = -1;
+
+    /** */
+    static final byte USER_COL = 0;
+
+    /** */
+    static final byte ARR_LIST = 1;
+
+    /** */
+    static final byte LINKED_LIST = 2;
+
+    /** */
+    static final byte HASH_SET = 3;
+
+    /** */
+    static final byte LINKED_HASH_SET = 4;
+
+    /** */
+    static final byte TREE_SET = 5;
+
+    /** */
+    static final byte CONC_SKIP_LIST_SET = 6;
+
+    /** */
+    static final byte HASH_MAP = 1;
+
+    /** */
+    static final byte LINKED_HASH_MAP = 2;
+
+    /** */
+    static final byte TREE_MAP = 3;
+
+    /** */
+    static final byte CONC_HASH_MAP = 4;
+
+    /** */
+    static final byte PROPERTIES_MAP = 5;
+
+    /** */
+    static final int OBJECT_TYPE_ID = -1;
+
+    /** */
+    static final int UNREGISTERED_TYPE_ID = 0;
+
+    /** */
+    static final int TYPE_ID_POS = 2;
+
+    /** */
+    static final int HASH_CODE_POS = 6;
+
+    /** */
+    static final int TOTAL_LEN_POS = 10;
+
+    /** */
+    static final byte RAW_DATA_OFF_POS = 14;
+
+    /** */
+    static final int CLS_NAME_POS = 18;
+
+    /** */
+    static final byte DFLT_HDR_LEN = 18;
+
+    /** */
+    private final PortableContext ctx;
+
+    /**
+     * @param ctx Context.
+     */
+    public GridPortableMarshaller(PortableContext ctx) {
+        this.ctx = ctx;
+    }
+
+    /**
+     * @param obj Object to marshal.
+     * @param off Offset.
+     * @return Byte array.
+     * @throws PortableException In case of error.
+     */
+    public byte[] marshal(@Nullable Object obj, int off) throws PortableException {
+        if (obj == null)
+            return new byte[] { NULL };
+
+        try (PortableWriterExImpl writer = new PortableWriterExImpl(ctx, off)) {
+            writer.marshal(obj, false);
+
+            return writer.array();
+        }
+    }
+
+    /**
+     * @param bytes Bytes array.
+     * @return Portable object.
+     * @throws PortableException In case of error.
+     */
+    @SuppressWarnings("unchecked")
+    @Nullable public <T> T unmarshal(byte[] bytes, @Nullable ClassLoader clsLdr) throws PortableException {
+        assert bytes != null;
+
+        PortableReaderExImpl reader = new PortableReaderExImpl(ctx, bytes, 0, clsLdr);
+
+        return (T)reader.unmarshal();
+    }
+
+    /**
+     * @param in Input stream.
+     * @return Portable object.
+     * @throws PortableException In case of error.
+     */
+    @SuppressWarnings("unchecked")
+    @Nullable public <T> T unmarshal(PortableInputStream in) throws PortableException {
+        return (T)reader(in).unmarshal();
+    }
+
+    /**
+     * @param arr Byte array.
+     * @param ldr Class loader.
+     * @return Deserialized object.
+     * @throws PortableException In case of error.
+     */
+    @SuppressWarnings("unchecked")
+    @Nullable public <T> T deserialize(byte[] arr, @Nullable ClassLoader ldr) throws PortableException {
+        assert arr != null;
+        assert arr.length > 0;
+
+        if (arr[0] == NULL)
+            return null;
+
+        PortableReaderExImpl reader = new PortableReaderExImpl(ctx, arr, 0, ldr);
+
+        return (T)reader.deserialize();
+    }
+
+    /**
+     * Gets writer for the given output stream.
+     *
+     * @param out Output stream.
+     * @return Writer.
+     */
+    public PortableWriterExImpl writer(PortableOutputStream out) {
+        return new PortableWriterExImpl(ctx, out, 0);
+    }
+
+    /**
+     * Gets reader for the given input stream.
+     *
+     * @param in Input stream.
+     * @return Reader.
+     */
+    public PortableReaderExImpl reader(PortableInputStream in) {
+        // TODO: IGNITE-1272 - Is class loader needed here?
+        return new PortableReaderExImpl(ctx, in, in.position(), null);
+    }
+
+    /**
+     * @return Context.
+     */
+    public PortableContext context() {
+        return ctx;
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableAbstractLazyValue.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableAbstractLazyValue.java b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableAbstractLazyValue.java
new file mode 100644
index 0000000..83b3050
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableAbstractLazyValue.java
@@ -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.internal.portable;
+
+/**
+ *
+ */
+abstract class PortableAbstractLazyValue implements PortableLazyValue {
+    /** */
+    protected Object val;
+
+    /** */
+    protected final PortableBuilderReader reader;
+
+    /** */
+    protected final int valOff;
+
+    /**
+     * @param reader Reader.
+     * @param valOff Value.
+     */
+    protected PortableAbstractLazyValue(PortableBuilderReader reader, int valOff) {
+        this.reader = reader;
+        this.valOff = valOff;
+    }
+
+    /**
+     * @return Value.
+     */
+    protected abstract Object init();
+
+    /** {@inheritDoc} */
+    @Override public Object value() {
+        if (val == null) {
+            val = init();
+
+            assert val != null;
+        }
+
+        return val;
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableBuilderEnum.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableBuilderEnum.java b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableBuilderEnum.java
new file mode 100644
index 0000000..9d29669
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableBuilderEnum.java
@@ -0,0 +1,114 @@
+/*
+ * 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.portable;
+
+import org.apache.ignite.internal.util.typedef.internal.*;
+import org.apache.ignite.portable.*;
+
+/**
+ *
+ */
+public class PortableBuilderEnum implements PortableBuilderSerializationAware {
+    /** */
+    private final int ordinal;
+
+    /** */
+    private final int typeId;
+
+    /** */
+    private final String clsName;
+
+    /**
+     * @param typeId Type ID.
+     * @param anEnum Enum instance.
+     */
+    public PortableBuilderEnum(int typeId, Enum anEnum) {
+        ordinal = anEnum.ordinal();
+        this.typeId = typeId;
+        clsName = null;
+    }
+
+    /**
+     * @param reader PortableBuilderReader.
+     */
+    public PortableBuilderEnum(PortableBuilderReader reader) {
+        int typeId = reader.readInt();
+
+        if (typeId == GridPortableMarshaller.UNREGISTERED_TYPE_ID) {
+            clsName = reader.readString();
+
+            Class cls;
+
+            try {
+                // TODO: IGNITE-1272 - Is class loader needed here?
+                cls = U.forName(reader.readString(), null);
+            }
+            catch (ClassNotFoundException e) {
+                throw new PortableInvalidClassException("Failed to load the class: " + clsName, e);
+            }
+
+            this.typeId = reader.portableContext().descriptorForClass(cls).typeId();
+        }
+        else {
+            this.typeId = typeId;
+            this.clsName = null;
+        }
+
+        ordinal = reader.readInt();
+    }
+
+    /**
+     * @return Ordinal.
+     */
+    public int getOrdinal() {
+        return ordinal;
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeTo(PortableWriterExImpl writer, PortableBuilderSerializer ctx) {
+        writer.writeByte(GridPortableMarshaller.ENUM);
+
+        if (typeId == GridPortableMarshaller.UNREGISTERED_TYPE_ID) {
+            writer.writeInt(GridPortableMarshaller.UNREGISTERED_TYPE_ID);
+            writer.writeString(clsName);
+        }
+        else
+            writer.writeInt(typeId);
+
+        writer.writeInt(ordinal);
+    }
+
+    /** {@inheritDoc} */
+    @Override public boolean equals(Object o) {
+        if (o == null || getClass() != o.getClass())
+            return false;
+
+        PortableBuilderEnum that = (PortableBuilderEnum)o;
+
+        return ordinal == that.ordinal && typeId == that.typeId;
+    }
+
+    /** {@inheritDoc} */
+    @Override public int hashCode() {
+        int result = ordinal;
+
+        result = 31 * result + typeId;
+
+        return result;
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableBuilderImpl.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableBuilderImpl.java b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableBuilderImpl.java
new file mode 100644
index 0000000..26f1d25
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableBuilderImpl.java
@@ -0,0 +1,519 @@
+/*
+ * 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.portable;
+
+import org.apache.ignite.internal.processors.cache.portable.*;
+import org.apache.ignite.internal.util.*;
+import org.apache.ignite.internal.util.typedef.internal.*;
+import org.apache.ignite.portable.*;
+
+import org.jetbrains.annotations.*;
+
+import java.util.*;
+
+import static org.apache.ignite.internal.portable.GridPortableMarshaller.*;
+
+/**
+ *
+ */
+public class PortableBuilderImpl implements PortableBuilder {
+    /** */
+    private static final Object REMOVED_FIELD_MARKER = new Object();
+
+    /** */
+    private final PortableContext ctx;
+
+    /** */
+    private final int typeId;
+
+    /** May be null. */
+    private String typeName;
+
+    /** May be null. */
+    private String clsNameToWrite;
+
+    /** */
+    private boolean registeredType = true;
+
+    /** */
+    private Map<String, Object> assignedVals;
+
+    /** */
+    private Map<Integer, Object> readCache;
+
+    /** Position of object in source array, or -1 if object is not created from PortableObject. */
+    private final int start;
+
+    /** Total header length */
+    private final int hdrLen;
+
+    /**
+     * Context of PortableObject reading process. Or {@code null} if object is not created from PortableObject.
+     */
+    private final PortableBuilderReader reader;
+
+    /** */
+    private int hashCode;
+
+    /**
+     * @param clsName Class name.
+     * @param ctx Portable context.
+     */
+    public PortableBuilderImpl(PortableContext ctx, String clsName) {
+        this(ctx, ctx.typeId(clsName), PortableContext.typeName(clsName));
+    }
+
+    /**
+     * @param typeId Type ID.
+     * @param ctx Portable context.
+     */
+    public PortableBuilderImpl(PortableContext ctx, int typeId) {
+        this(ctx, typeId, null);
+    }
+
+    /**
+     * @param typeName Type name.
+     * @param ctx Context.
+     * @param typeId Type id.
+     */
+    public PortableBuilderImpl(PortableContext ctx, int typeId, String typeName) {
+        this.typeId = typeId;
+        this.typeName = typeName;
+        this.ctx = ctx;
+
+        start = -1;
+        reader = null;
+        hdrLen = DFLT_HDR_LEN;
+
+        readCache = Collections.emptyMap();
+    }
+
+    /**
+     * @param obj Object to wrap.
+     */
+    public PortableBuilderImpl(PortableObjectImpl obj) {
+        this(new PortableBuilderReader(obj), obj.start());
+
+        reader.registerObject(this);
+    }
+
+    /**
+     * @param reader ctx
+     * @param start Start.
+     */
+    PortableBuilderImpl(PortableBuilderReader reader, int start) {
+        this.reader = reader;
+        this.start = start;
+
+        int typeId = reader.readIntAbsolute(start + TYPE_ID_POS);
+        ctx = reader.portableContext();
+        hashCode = reader.readIntAbsolute(start + HASH_CODE_POS);
+
+        if (typeId == UNREGISTERED_TYPE_ID) {
+            int mark = reader.position();
+
+            reader.position(start + CLS_NAME_POS);
+
+            clsNameToWrite = reader.readString();
+
+            Class cls;
+
+            try {
+                // TODO: IGNITE-1272 - Is class loader needed here?
+                cls = U.forName(clsNameToWrite, null);
+            }
+            catch (ClassNotFoundException e) {
+                throw new PortableInvalidClassException("Failed to load the class: " + clsNameToWrite, e);
+            }
+
+            this.typeId = ctx.descriptorForClass(cls).typeId();
+
+            registeredType = false;
+
+            hdrLen = reader.position() - mark;
+
+            reader.position(mark);
+        }
+        else {
+            this.typeId = typeId;
+            hdrLen = DFLT_HDR_LEN;
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override public PortableObject build() {
+        try (PortableWriterExImpl writer = new PortableWriterExImpl(ctx, 0, typeId, false)) {
+
+            PortableBuilderSerializer serializationCtx = new PortableBuilderSerializer();
+
+            serializationCtx.registerObjectWriting(this, 0);
+
+            serializeTo(writer, serializationCtx);
+
+            byte[] arr = writer.array();
+
+            return new PortableObjectImpl(ctx, arr, 0);
+        }
+    }
+
+    /**
+     * @param writer Writer.
+     * @param serializer Serializer.
+     */
+    void serializeTo(PortableWriterExImpl writer, PortableBuilderSerializer serializer) {
+        writer.doWriteByte(GridPortableMarshaller.OBJ);
+        writer.doWriteBoolean(true);
+        writer.doWriteInt(registeredType ? typeId : UNREGISTERED_TYPE_ID);
+        writer.doWriteInt(hashCode);
+
+        // Length and raw offset.
+        writer.reserve(8);
+
+        if (!registeredType)
+            writer.writeString(clsNameToWrite);
+
+
+        Set<Integer> remainsFlds = null;
+
+        if (reader != null) {
+            Map<Integer, Object> assignedFldsById;
+
+            if (assignedVals != null) {
+                assignedFldsById = U.newHashMap(assignedVals.size());
+
+                for (Map.Entry<String, Object> entry : assignedVals.entrySet()) {
+                    int fldId = ctx.fieldId(typeId, entry.getKey());
+
+                    assignedFldsById.put(fldId, entry.getValue());
+                }
+
+                remainsFlds = assignedFldsById.keySet();
+            }
+            else
+                assignedFldsById = Collections.emptyMap();
+
+            int rawOff = start + reader.readIntAbsolute(start + RAW_DATA_OFF_POS);
+
+            reader.position(start + hdrLen);
+
+            int cpStart = -1;
+
+            while (reader.position() < rawOff) {
+                int fldId = reader.readInt();
+
+                int len = reader.readInt();
+
+                if (assignedFldsById.containsKey(fldId)) {
+                    if (cpStart >= 0) {
+                        writer.write(reader.array(), cpStart, reader.position() - 4 - 4 - cpStart);
+
+                        cpStart = -1;
+                    }
+
+                    Object assignedVal = assignedFldsById.remove(fldId);
+
+                    reader.skip(len);
+
+                    if (assignedVal != REMOVED_FIELD_MARKER) {
+                        writer.writeInt(fldId);
+
+                        int lenPos = writer.reserveAndMark(4);
+
+                        serializer.writeValue(writer, assignedVal);
+
+                        writer.writeDelta(lenPos);
+                    }
+                }
+                else {
+                    if (len != 0 && PortableUtils.isPlainType(reader.readByte(0))) {
+                        if (cpStart < 0)
+                            cpStart = reader.position() - 4 - 4;
+
+                        reader.skip(len);
+                    }
+                    else {
+                        if (cpStart >= 0) {
+                            writer.write(reader.array(), cpStart, reader.position() - 4 - cpStart);
+
+                            cpStart = -1;
+                        }
+                        else
+                            writer.writeInt(fldId);
+
+                        Object val;
+
+                        if (len == 0)
+                            val = null;
+                        else if (readCache == null) {
+                            int savedPos = reader.position();
+
+                            val = reader.parseValue();
+
+                            assert reader.position() == savedPos + len;
+                        }
+                        else {
+                            val = readCache.get(fldId);
+
+                            reader.skip(len);
+                        }
+
+                        int lenPos = writer.reserveAndMark(4);
+
+                        serializer.writeValue(writer, val);
+
+                        writer.writeDelta(lenPos);
+                    }
+                }
+            }
+
+            if (cpStart >= 0)
+                writer.write(reader.array(), cpStart, reader.position() - cpStart);
+        }
+
+        if (assignedVals != null && (remainsFlds == null || !remainsFlds.isEmpty())) {
+            boolean metadataEnabled = ctx.isMetaDataEnabled(typeId);
+
+            PortableMetadata metadata = null;
+
+            if (metadataEnabled)
+                metadata = ctx.metaData(typeId);
+
+            Map<String, String> newFldsMetadata = null;
+
+            for (Map.Entry<String, Object> entry : assignedVals.entrySet()) {
+                Object val = entry.getValue();
+
+                if (val == REMOVED_FIELD_MARKER)
+                    continue;
+
+                String name = entry.getKey();
+
+                int fldId = ctx.fieldId(typeId, name);
+
+                if (remainsFlds != null && !remainsFlds.contains(fldId))
+                    continue;
+
+                writer.writeInt(fldId);
+
+                int lenPos = writer.reserveAndMark(4);
+
+                serializer.writeValue(writer, val);
+
+                writer.writeDelta(lenPos);
+
+                if (metadataEnabled) {
+                    String oldFldTypeName = metadata == null ? null : metadata.fieldTypeName(name);
+
+                    String newFldTypeName;
+
+                    if (val instanceof PortableValueWithType)
+                        newFldTypeName = ((PortableValueWithType)val).typeName();
+                    else {
+                        byte type = PortableUtils.typeByClass(val.getClass());
+
+                        newFldTypeName = CacheObjectPortableProcessorImpl.fieldTypeName(type);
+                    }
+
+                    if (oldFldTypeName == null) {
+                        // It's a new field, we have to add it to metadata.
+
+                        if (newFldsMetadata == null)
+                            newFldsMetadata = new HashMap<>();
+
+                        newFldsMetadata.put(name, newFldTypeName);
+                    }
+                    else {
+                        if (!"Object".equals(oldFldTypeName) && !oldFldTypeName.equals(newFldTypeName)) {
+                            throw new PortableException(
+                                "Wrong value has been set [" +
+                                    "typeName=" + (typeName == null ? metadata.typeName() : typeName) +
+                                    ", fieldName=" + name +
+                                    ", fieldType=" + oldFldTypeName +
+                                    ", assignedValueType=" + newFldTypeName +
+                                    ", assignedValue=" + (((PortableValueWithType)val).value()) + ']'
+                            );
+                        }
+                    }
+                }
+            }
+
+            if (newFldsMetadata != null) {
+                String typeName = this.typeName;
+
+                if (typeName == null)
+                    typeName = metadata.typeName();
+
+                ctx.updateMetaData(typeId, typeName, newFldsMetadata);
+            }
+        }
+
+        writer.writeRawOffsetIfNeeded();
+
+        if (reader != null) {
+            int rawOff = reader.readIntAbsolute(start + RAW_DATA_OFF_POS);
+            int len = reader.readIntAbsolute(start + TOTAL_LEN_POS);
+
+            if (rawOff < len)
+                writer.write(reader.array(), rawOff, len - rawOff);
+        }
+
+        writer.writeLength();
+    }
+
+    /** {@inheritDoc} */
+    @Override public PortableBuilderImpl hashCode(int hashCode) {
+        this.hashCode = hashCode;
+
+        return this;
+    }
+
+    /**
+     *
+     */
+    private void ensureReadCacheInit() {
+        if (readCache == null) {
+            Map<Integer, Object> readCache = new HashMap<>();
+
+            int pos = start + hdrLen;
+            int end = start + reader.readIntAbsolute(start + RAW_DATA_OFF_POS);
+
+            while (pos < end) {
+                int fieldId = reader.readIntAbsolute(pos);
+
+                pos += 4;
+
+                int len = reader.readIntAbsolute(pos);
+
+                pos += 4;
+
+                Object val = reader.getValueQuickly(pos, len);
+
+                readCache.put(fieldId, val);
+
+                pos += len;
+            }
+
+            this.readCache = readCache;
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override public <F> F getField(String name) {
+        Object val;
+
+        if (assignedVals != null && assignedVals.containsKey(name)) {
+            val = assignedVals.get(name);
+
+            if (val == REMOVED_FIELD_MARKER)
+                return null;
+        }
+        else {
+            ensureReadCacheInit();
+
+            int fldId = ctx.fieldId(typeId, name);
+
+            val = readCache.get(fldId);
+        }
+
+        return (F)PortableUtils.unwrapLazy(val);
+    }
+
+    /** {@inheritDoc} */
+    @Override public PortableBuilder setField(String name, Object val) {
+        GridArgumentCheck.notNull(val, "val");
+
+        if (assignedVals == null)
+            assignedVals = new LinkedHashMap<>();
+
+        Object oldVal = assignedVals.put(name, val);
+
+        if (oldVal instanceof PortableValueWithType) {
+            ((PortableValueWithType)oldVal).value(val);
+
+            assignedVals.put(name, oldVal);
+        }
+
+        return this;
+    }
+
+    /** {@inheritDoc} */
+    @Override public <T> PortableBuilder setField(String name, @Nullable T val, Class<? super T> type) {
+        if (assignedVals == null)
+            assignedVals = new LinkedHashMap<>();
+
+        //int fldId = ctx.fieldId(typeId, fldName);
+
+        assignedVals.put(name, new PortableValueWithType(PortableUtils.typeByClass(type), val));
+
+        return this;
+    }
+
+    /** {@inheritDoc} */
+    @Override public PortableBuilder setField(String name, @Nullable PortableBuilder builder) {
+        if (builder == null)
+            return setField(name, null, Object.class);
+        else
+            return setField(name, (Object)builder);
+    }
+
+    /**
+     * Removes field from portable object.
+     *
+     * @param name Field name.
+     * @return {@code this} instance for chaining.
+     */
+    @Override public PortableBuilderImpl removeField(String name) {
+        if (assignedVals == null)
+            assignedVals = new LinkedHashMap<>();
+
+        assignedVals.put(name, REMOVED_FIELD_MARKER);
+
+        return this;
+    }
+
+    /**
+     * Creates builder initialized by specified portable object.
+     *
+     * @param obj Portable object to initialize builder.
+     * @return New builder.
+     */
+    public static PortableBuilderImpl wrap(PortableObject obj) {
+        PortableObjectImpl heapObj;
+
+        if (obj instanceof PortableObjectOffheapImpl)
+            heapObj = (PortableObjectImpl)((PortableObjectOffheapImpl)obj).heapCopy();
+        else
+            heapObj = (PortableObjectImpl)obj;
+
+        return new PortableBuilderImpl(heapObj);
+    }
+
+    /**
+     * @return Object start position in source array.
+     */
+    int start() {
+        return start;
+    }
+
+    /**
+     * @return Object type id.
+     */
+    int typeId() {
+        return typeId;
+    }
+}


[13/59] [abbrv] ignite git commit: ignite-1258: portable objects API support in Ignite

Posted by vk...@apache.org.
http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableBuilderReader.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableBuilderReader.java b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableBuilderReader.java
new file mode 100644
index 0000000..3e0286f
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableBuilderReader.java
@@ -0,0 +1,775 @@
+/*
+ * 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.portable;
+
+import org.apache.ignite.portable.*;
+
+import java.sql.*;
+import java.util.Date;
+import java.util.*;
+
+import static java.nio.charset.StandardCharsets.*;
+import static org.apache.ignite.internal.portable.GridPortableMarshaller.*;
+
+/**
+ *
+ */
+class PortableBuilderReader {
+    /** */
+    private static final PortablePrimitives PRIM = PortablePrimitives.get();
+
+    /** */
+    private final Map<Integer, PortableBuilderImpl> objMap = new HashMap<>();
+
+    /** */
+    private final PortableContext ctx;
+
+    /** */
+    private final PortableReaderExImpl reader;
+
+    /** */
+    private byte[] arr;
+
+    /** */
+    private int pos;
+
+    /**
+     * @param objImpl Portable object
+     */
+    PortableBuilderReader(PortableObjectImpl objImpl) {
+        ctx = objImpl.context();
+        arr = objImpl.array();
+        pos = objImpl.start();
+
+        // TODO: IGNITE-1272 - Is class loader needed here?
+        reader = new PortableReaderExImpl(portableContext(), arr, pos, null);
+    }
+
+    /**
+     * @return Portable context.
+     */
+    public PortableContext portableContext() {
+        return ctx;
+    }
+
+    /**
+     * @param obj Mutable portable object.
+     */
+    public void registerObject(PortableBuilderImpl obj) {
+        objMap.put(obj.start(), obj);
+    }
+
+    /**
+     * @return Read int value.
+     */
+    public int readInt() {
+        int res = readInt(0);
+
+        pos += 4;
+
+        return res;
+    }
+
+    /**
+     * @return Read int value.
+     */
+    public byte readByte() {
+        return arr[pos++];
+    }
+
+    /**
+     * @return Read boolean value.
+     */
+    public boolean readBoolean() {
+        return readByte() == 1;
+    }
+
+    /**
+     * @return Read int value.
+     */
+    public byte readByte(int off) {
+        return arr[pos + off];
+    }
+
+    /**
+     * @param off Offset related to {@link #pos}
+     * @return Read int value.
+     */
+    public int readInt(int off) {
+        return PRIM.readInt(arr, pos + off);
+    }
+
+    /**
+     * @param pos Position in the source array.
+     * @return Read int value.
+     */
+    public int readIntAbsolute(int pos) {
+        return PRIM.readInt(arr, pos);
+    }
+
+    /**
+     * @return Read length of array.
+     */
+    public int readLength() {
+        return PRIM.readInt(arr, pos);
+    }
+
+    /**
+     * Read string length.
+     *
+     * @return String length.
+     */
+    public int readStringLength() {
+        boolean utf = PRIM.readBoolean(arr, pos);
+
+        int arrLen = PRIM.readInt(arr, pos + 1);
+
+        return 1 + (utf ? arrLen : arrLen << 1);
+    }
+
+    /**
+     * Reads string.
+     *
+     * @return String.
+     */
+    public String readString() {
+        byte flag = readByte();
+
+        if (flag == NULL)
+            return null;
+
+        if (flag != STRING)
+            throw new PortableException("Failed to deserialize String.");
+
+        boolean convert = readBoolean();
+        int len = readInt();
+
+        String str;
+
+        if (convert) {
+            str = new String(arr, pos, len, UTF_8);
+
+            pos += len;
+        }
+        else {
+            str = String.valueOf(PRIM.readCharArray(arr, pos, len));
+
+            pos += len << 1;
+        }
+
+        return str;
+    }
+
+    /**
+     *
+     */
+    public void skipValue() {
+        byte type = arr[pos++];
+
+        int len;
+
+        switch (type) {
+            case GridPortableMarshaller.NULL:
+                return;
+
+            case GridPortableMarshaller.OBJ:
+                pos += readInt(GridPortableMarshaller.TOTAL_LEN_POS - 1) - 1;
+
+                return;
+
+            case GridPortableMarshaller.BOOLEAN:
+            case GridPortableMarshaller.BYTE:
+                len = 1;
+                break;
+
+            case GridPortableMarshaller.CHAR:
+            case GridPortableMarshaller.SHORT:
+                len = 2;
+
+                break;
+
+            case GridPortableMarshaller.HANDLE:
+            case GridPortableMarshaller.FLOAT:
+            case GridPortableMarshaller.INT:
+                len = 4;
+
+                break;
+
+            case GridPortableMarshaller.ENUM:
+                //skipping type id and ordinal value
+                len = 8;
+
+                break;
+
+            case GridPortableMarshaller.LONG:
+            case GridPortableMarshaller.DOUBLE:
+                len = 8;
+
+                break;
+
+            case GridPortableMarshaller.BYTE_ARR:
+            case GridPortableMarshaller.BOOLEAN_ARR:
+                len = 4 + readLength();
+
+                break;
+
+            case GridPortableMarshaller.STRING:
+                len = 4 + readStringLength();
+
+                break;
+
+            case GridPortableMarshaller.DECIMAL:
+                len = /** scale */ 4  + /** mag len */ 4  + /** mag bytes count */ readInt(4);
+
+                break;
+
+            case GridPortableMarshaller.UUID:
+                len = 8 + 8;
+
+                break;
+
+            case GridPortableMarshaller.DATE:
+                len = 8 + 4;
+
+                break;
+
+            case GridPortableMarshaller.CHAR_ARR:
+            case GridPortableMarshaller.SHORT_ARR:
+                len = 4 + readLength() * 2;
+
+                break;
+
+            case GridPortableMarshaller.INT_ARR:
+            case GridPortableMarshaller.FLOAT_ARR:
+                len = 4 + readLength() * 4;
+
+                break;
+
+            case GridPortableMarshaller.LONG_ARR:
+            case GridPortableMarshaller.DOUBLE_ARR:
+                len = 4 + readLength() * 8;
+
+                break;
+
+            case GridPortableMarshaller.DECIMAL_ARR:
+            case GridPortableMarshaller.DATE_ARR:
+            case GridPortableMarshaller.OBJ_ARR:
+            case GridPortableMarshaller.ENUM_ARR:
+            case GridPortableMarshaller.UUID_ARR:
+            case GridPortableMarshaller.STRING_ARR: {
+                int size = readInt();
+
+                for (int i = 0; i < size; i++)
+                    skipValue();
+
+                return;
+            }
+
+            case GridPortableMarshaller.COL: {
+                int size = readInt();
+
+                pos++; // skip collection type
+
+                for (int i = 0; i < size; i++)
+                    skipValue();
+
+                return;
+            }
+
+            case GridPortableMarshaller.MAP: {
+                int size = readInt();
+
+                pos++; // skip collection type
+
+                for (int i = 0; i < size; i++) {
+                    skipValue(); // skip key.
+                    skipValue(); // skip value.
+                }
+
+                return;
+            }
+
+            case GridPortableMarshaller.MAP_ENTRY:
+                skipValue();
+                skipValue();
+
+                return;
+
+            case GridPortableMarshaller.PORTABLE_OBJ:
+                len = readInt() + 4;
+
+                break;
+
+            default:
+                throw new PortableException("Invalid flag value: " + type);
+        }
+
+        pos += len;
+    }
+
+    /**
+     * @param pos Position.
+     * @param len Length.
+     * @return Object.
+     */
+    public Object getValueQuickly(int pos, int len) {
+        byte type = arr[pos];
+
+        switch (type) {
+            case GridPortableMarshaller.NULL:
+                return null;
+
+            case GridPortableMarshaller.HANDLE: {
+                int objStart = pos - readIntAbsolute(pos + 1);
+
+                PortableBuilderImpl res = objMap.get(objStart);
+
+                if (res == null) {
+                    res = new PortableBuilderImpl(this, objStart);
+
+                    objMap.put(objStart, res);
+                }
+
+                return res;
+            }
+
+            case GridPortableMarshaller.OBJ: {
+                PortableBuilderImpl res = objMap.get(pos);
+
+                if (res == null) {
+                    res = new PortableBuilderImpl(this, pos);
+
+                    objMap.put(pos, res);
+                }
+
+                return res;
+            }
+
+            case GridPortableMarshaller.BYTE:
+                return arr[pos + 1];
+
+            case GridPortableMarshaller.SHORT:
+                return PRIM.readShort(arr, pos + 1);
+
+            case GridPortableMarshaller.INT:
+                return PRIM.readInt(arr, pos + 1);
+
+            case GridPortableMarshaller.LONG:
+                return PRIM.readLong(arr, pos + 1);
+
+            case GridPortableMarshaller.FLOAT:
+                return PRIM.readFloat(arr, pos + 1);
+
+            case GridPortableMarshaller.DOUBLE:
+                return PRIM.readDouble(arr, pos + 1);
+
+            case GridPortableMarshaller.CHAR:
+                return PRIM.readChar(arr, pos + 1);
+
+            case GridPortableMarshaller.BOOLEAN:
+                return arr[pos + 1] != 0;
+
+            case GridPortableMarshaller.DECIMAL:
+            case GridPortableMarshaller.STRING:
+            case GridPortableMarshaller.UUID:
+            case GridPortableMarshaller.DATE:
+            case GridPortableMarshaller.BYTE_ARR:
+            case GridPortableMarshaller.SHORT_ARR:
+            case GridPortableMarshaller.INT_ARR:
+            case GridPortableMarshaller.LONG_ARR:
+            case GridPortableMarshaller.FLOAT_ARR:
+            case GridPortableMarshaller.DOUBLE_ARR:
+            case GridPortableMarshaller.CHAR_ARR:
+            case GridPortableMarshaller.BOOLEAN_ARR:
+            case GridPortableMarshaller.DECIMAL_ARR:
+            case GridPortableMarshaller.DATE_ARR:
+            case GridPortableMarshaller.UUID_ARR:
+            case GridPortableMarshaller.STRING_ARR:
+                return new PortablePlainLazyValue(this, pos, len);
+
+            case GridPortableMarshaller.COL:
+            case GridPortableMarshaller.OBJ_ARR:
+            case GridPortableMarshaller.MAP:
+            case GridPortableMarshaller.ENUM_ARR:
+            case GridPortableMarshaller.MAP_ENTRY:
+                return new LazyCollection(pos);
+
+            case GridPortableMarshaller.ENUM: {
+                if (len == 1) {
+                    assert readByte(pos) == GridPortableMarshaller.NULL;
+
+                    return null;
+                }
+
+                int mark = position();
+                position(pos + 1);
+
+                PortableBuilderEnum builderEnum = new PortableBuilderEnum(this);
+
+                position(mark);
+
+                return builderEnum;
+            }
+
+            case GridPortableMarshaller.PORTABLE_OBJ: {
+                int size = readIntAbsolute(pos + 1);
+
+                int start = readIntAbsolute(pos + 4 + size);
+
+                PortableObjectImpl portableObj = new PortableObjectImpl(ctx, arr, pos + 4 + start);
+
+                return new PortablePlainPortableObject(portableObj);
+            }
+
+            default:
+                throw new PortableException("Invalid flag value: " + type);
+        }
+    }
+
+    /**
+     * @return Parsed value.
+     */
+    public Object parseValue() {
+        int valPos = pos;
+
+        byte type = arr[pos++];
+
+        int plainLazyValLen;
+
+        switch (type) {
+            case GridPortableMarshaller.NULL:
+                return null;
+
+            case GridPortableMarshaller.HANDLE: {
+                int objStart = pos - 1 - readInt();
+
+                PortableBuilderImpl res = objMap.get(objStart);
+
+                if (res == null) {
+                    res = new PortableBuilderImpl(this, objStart);
+
+                    objMap.put(objStart, res);
+                }
+
+                return res;
+            }
+
+            case GridPortableMarshaller.OBJ: {
+                pos--;
+
+                PortableBuilderImpl res = objMap.get(pos);
+
+                if (res == null) {
+                    res = new PortableBuilderImpl(this, pos);
+
+                    objMap.put(pos, res);
+                }
+
+                pos += readInt(GridPortableMarshaller.TOTAL_LEN_POS);
+
+                return res;
+            }
+
+            case GridPortableMarshaller.BYTE:
+                return arr[pos++];
+
+            case GridPortableMarshaller.SHORT: {
+                Object res = PRIM.readShort(arr, pos);
+                pos += 2;
+                return res;
+            }
+
+            case GridPortableMarshaller.INT:
+                return readInt();
+
+            case GridPortableMarshaller.LONG:
+                plainLazyValLen = 8;
+
+                break;
+
+            case GridPortableMarshaller.FLOAT:
+                plainLazyValLen = 4;
+
+                break;
+
+            case GridPortableMarshaller.DOUBLE:
+                plainLazyValLen = 8;
+
+                break;
+
+            case GridPortableMarshaller.CHAR:
+                plainLazyValLen = 2;
+
+                break;
+
+            case GridPortableMarshaller.BOOLEAN:
+                return arr[pos++] != 0;
+
+            case GridPortableMarshaller.DECIMAL:
+                plainLazyValLen = /** scale */ 4  + /** mag len */ 4  + /** mag bytes count */ readInt(4);
+
+                break;
+
+            case GridPortableMarshaller.STRING:
+                plainLazyValLen = 4 + readStringLength();
+
+                break;
+
+            case GridPortableMarshaller.UUID:
+                plainLazyValLen = 8 + 8;
+
+                break;
+
+            case GridPortableMarshaller.DATE:
+                plainLazyValLen = 8 + 4;
+
+                break;
+
+            case GridPortableMarshaller.BYTE_ARR:
+                plainLazyValLen = 4 + readLength();
+
+                break;
+
+            case GridPortableMarshaller.SHORT_ARR:
+                plainLazyValLen = 4 + readLength() * 2;
+
+                break;
+
+            case GridPortableMarshaller.INT_ARR:
+                plainLazyValLen = 4 + readLength() * 4;
+
+                break;
+
+            case GridPortableMarshaller.LONG_ARR:
+                plainLazyValLen = 4 + readLength() * 8;
+
+                break;
+
+            case GridPortableMarshaller.FLOAT_ARR:
+                plainLazyValLen = 4 + readLength() * 4;
+
+                break;
+
+            case GridPortableMarshaller.DOUBLE_ARR:
+                plainLazyValLen = 4 + readLength() * 8;
+
+                break;
+
+            case GridPortableMarshaller.CHAR_ARR:
+                plainLazyValLen = 4 + readLength() * 2;
+
+                break;
+
+            case GridPortableMarshaller.BOOLEAN_ARR:
+                plainLazyValLen = 4 + readLength();
+
+                break;
+
+            case GridPortableMarshaller.OBJ_ARR:
+                return new PortableObjectArrayLazyValue(this);
+
+            case GridPortableMarshaller.DATE_ARR: {
+                int size = readInt();
+
+                Date[] res = new Date[size];
+
+                for (int i = 0; i < res.length; i++) {
+                    byte flag = arr[pos++];
+
+                    if (flag == GridPortableMarshaller.NULL) continue;
+
+                    if (flag != GridPortableMarshaller.DATE)
+                        throw new PortableException("Invalid flag value: " + flag);
+
+                    long time = PRIM.readLong(arr, pos);
+
+                    pos += 8;
+
+                    if (ctx.isUseTimestamp()) {
+                        Timestamp ts = new Timestamp(time);
+
+                        ts.setNanos(ts.getNanos() + readInt());
+
+                        res[i] = ts;
+                    }
+                    else {
+                        res[i] = new Date(time);
+
+                        pos += 4;
+                    }
+                }
+
+                return res;
+            }
+
+            case GridPortableMarshaller.UUID_ARR:
+            case GridPortableMarshaller.STRING_ARR:
+            case GridPortableMarshaller.DECIMAL_ARR: {
+                int size = readInt();
+
+                for (int i = 0; i < size; i++) {
+                    byte flag = arr[pos++];
+
+                    if (flag == GridPortableMarshaller.UUID)
+                        pos += 8 + 8;
+                    else if (flag == GridPortableMarshaller.STRING)
+                        pos += 4 + readStringLength();
+                    else if (flag == GridPortableMarshaller.DECIMAL)
+                        pos += 4 + readLength();
+                    else
+                        assert flag == GridPortableMarshaller.NULL;
+                }
+
+                return new PortablePlainLazyValue(this, valPos, pos - valPos);
+            }
+
+            case GridPortableMarshaller.COL: {
+                int size = readInt();
+                byte colType = arr[pos++];
+
+                switch (colType) {
+                    case GridPortableMarshaller.USER_COL:
+                    case GridPortableMarshaller.ARR_LIST:
+                        return new PortableLazyArrayList(this, size);
+
+                    case GridPortableMarshaller.LINKED_LIST:
+                        return new PortableLazyLinkedList(this, size);
+
+                    case GridPortableMarshaller.HASH_SET:
+                    case GridPortableMarshaller.LINKED_HASH_SET:
+                    case GridPortableMarshaller.TREE_SET:
+                    case GridPortableMarshaller.CONC_SKIP_LIST_SET:
+                        return new PortableLazySet(this, size);
+                }
+
+                throw new PortableException("Unknown collection type: " + colType);
+            }
+
+            case GridPortableMarshaller.MAP:
+                return PortableLazyMap.parseMap(this);
+
+            case GridPortableMarshaller.ENUM:
+                return new PortableBuilderEnum(this);
+
+            case GridPortableMarshaller.ENUM_ARR:
+                return new PortableEnumArrayLazyValue(this);
+
+            case GridPortableMarshaller.MAP_ENTRY:
+                return new PortableLazyMapEntry(this);
+
+            case GridPortableMarshaller.PORTABLE_OBJ: {
+                int size = readInt();
+
+                pos += size;
+
+                int start = readInt();
+
+                PortableObjectImpl portableObj = new PortableObjectImpl(ctx, arr,
+                    pos - 4 - size + start);
+
+                return new PortablePlainPortableObject(portableObj);
+            }
+
+
+            default:
+                throw new PortableException("Invalid flag value: " + type);
+        }
+
+        PortablePlainLazyValue res = new PortablePlainLazyValue(this, valPos, 1 + plainLazyValLen);
+
+        pos += plainLazyValLen;
+
+        return res;
+    }
+
+    /**
+     * @return Array.
+     */
+    public byte[] array() {
+        return arr;
+    }
+
+    /**
+     * @return Position of reader.
+     */
+    public int position() {
+        return pos;
+    }
+
+    /**
+     * @param pos New pos.
+     */
+    public void position(int pos) {
+        this.pos = pos;
+    }
+
+    /**
+     * @param n Number of bytes to skip.
+     */
+    public void skip(int n) {
+        pos += n;
+    }
+
+    /**
+     * @return Reader.
+     */
+    PortableReaderExImpl reader() {
+        return reader;
+    }
+
+    /**
+     *
+     */
+    private class LazyCollection implements PortableLazyValue {
+        /** */
+        private final int valOff;
+
+        /** */
+        private Object col;
+
+        /**
+         * @param valOff Value.
+         */
+        protected LazyCollection(int valOff) {
+            this.valOff = valOff;
+        }
+
+        /**
+         * @return Object.
+         */
+        private Object wrappedCollection() {
+            if (col == null) {
+                position(valOff);
+
+                col = parseValue();
+            }
+
+            return col;
+        }
+
+        /** {@inheritDoc} */
+        @Override public void writeTo(PortableWriterExImpl writer, PortableBuilderSerializer ctx) {
+            ctx.writeValue(writer, wrappedCollection());
+        }
+
+        /** {@inheritDoc} */
+        @Override public Object value() {
+            return PortableUtils.unwrapLazy(wrappedCollection());
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableBuilderSerializationAware.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableBuilderSerializationAware.java b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableBuilderSerializationAware.java
new file mode 100644
index 0000000..dadbcf2
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableBuilderSerializationAware.java
@@ -0,0 +1,29 @@
+/*
+ * 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.portable;
+
+/**
+ *
+ */
+interface PortableBuilderSerializationAware {
+    /**
+     * @param writer Writer.
+     * @param ctx Context.
+     */
+    public void writeTo(PortableWriterExImpl writer, PortableBuilderSerializer ctx);
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableBuilderSerializer.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableBuilderSerializer.java b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableBuilderSerializer.java
new file mode 100644
index 0000000..01edc5e
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableBuilderSerializer.java
@@ -0,0 +1,210 @@
+/*
+ * 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.portable;
+
+import org.apache.ignite.internal.util.*;
+import org.apache.ignite.portable.*;
+
+import java.util.*;
+
+/**
+ *
+ */
+class PortableBuilderSerializer {
+    /** */
+    private final Map<PortableBuilderImpl, Integer> objToPos = new IdentityHashMap<>();
+
+    /** */
+    private Map<PortableObject, PortableBuilderImpl> portableObjToWrapper;
+
+    /**
+     * @param obj Mutable object.
+     * @param posInResArr Object position in the array.
+     */
+    public void registerObjectWriting(PortableBuilderImpl obj, int posInResArr) {
+        objToPos.put(obj, posInResArr);
+    }
+
+    /**
+     * @param writer Writer.
+     * @param val Value.
+     */
+    public void writeValue(PortableWriterExImpl writer, Object val) {
+        if (val == null) {
+            writer.writeByte(GridPortableMarshaller.NULL);
+
+            return;
+        }
+
+        if (val instanceof PortableBuilderSerializationAware) {
+            ((PortableBuilderSerializationAware)val).writeTo(writer, this);
+
+            return;
+        }
+
+        if (val instanceof PortableObjectEx) {
+            if (portableObjToWrapper == null)
+                portableObjToWrapper = new IdentityHashMap<>();
+
+            PortableBuilderImpl wrapper = portableObjToWrapper.get(val);
+
+            if (wrapper == null) {
+                wrapper = PortableBuilderImpl.wrap((PortableObject)val);
+
+                portableObjToWrapper.put((PortableObject)val, wrapper);
+            }
+
+            val = wrapper;
+        }
+
+        if (val instanceof PortableBuilderImpl) {
+            PortableBuilderImpl obj = (PortableBuilderImpl)val;
+
+            Integer posInResArr = objToPos.get(obj);
+
+            if (posInResArr == null) {
+                objToPos.put(obj, writer.outputStream().position());
+
+                obj.serializeTo(writer.newWriter(obj.typeId()), this);
+            }
+            else {
+                int handle = writer.outputStream().position() - posInResArr;
+
+                writer.writeByte(GridPortableMarshaller.HANDLE);
+                writer.writeInt(handle);
+            }
+
+            return;
+        }
+
+        if (val.getClass().isEnum()) {
+            writer.writeByte(GridPortableMarshaller.ENUM);
+            writer.writeInt(writer.context().typeId(val.getClass().getName()));
+            writer.writeInt(((Enum)val).ordinal());
+
+            return;
+        }
+
+        if (val instanceof Collection) {
+            Collection<?> c = (Collection<?>)val;
+
+            writer.writeByte(GridPortableMarshaller.COL);
+            writer.writeInt(c.size());
+
+            byte colType;
+
+            if (c instanceof GridConcurrentSkipListSet)
+                colType = GridPortableMarshaller.CONC_SKIP_LIST_SET;
+            else
+                colType = writer.context().collectionType(c.getClass());
+
+
+            writer.writeByte(colType);
+
+            for (Object obj : c)
+                writeValue(writer, obj);
+
+            return;
+        }
+
+        if (val instanceof Map) {
+            Map<?, ?> map = (Map<?, ?>)val;
+
+            writer.writeByte(GridPortableMarshaller.MAP);
+            writer.writeInt(map.size());
+
+            writer.writeByte(writer.context().mapType(map.getClass()));
+
+            for (Map.Entry<?, ?> entry : map.entrySet()) {
+                writeValue(writer, entry.getKey());
+                writeValue(writer, entry.getValue());
+            }
+
+            return;
+        }
+
+        Byte flag = PortableUtils.PLAIN_CLASS_TO_FLAG.get(val.getClass());
+
+        if (flag != null) {
+            PortableUtils.writePlainObject(writer, val);
+
+            return;
+        }
+
+        if (val instanceof Object[]) {
+            int compTypeId = writer.context().typeId(((Object[])val).getClass().getComponentType().getName());
+
+            if (val instanceof PortableBuilderEnum[]) {
+                writeArray(writer, GridPortableMarshaller.ENUM_ARR, (Object[])val, compTypeId);
+
+                return;
+            }
+
+            if (((Object[])val).getClass().getComponentType().isEnum()) {
+                Enum[] enumArr = (Enum[])val;
+
+                writer.writeByte(GridPortableMarshaller.ENUM_ARR);
+                writer.writeInt(compTypeId);
+                writer.writeInt(enumArr.length);
+
+                for (Enum anEnum : enumArr)
+                    writeValue(writer, anEnum);
+
+                return;
+            }
+
+            writeArray(writer, GridPortableMarshaller.OBJ_ARR, (Object[])val, compTypeId);
+
+            return;
+        }
+
+        writer.doWriteObject(val, false);
+    }
+
+    /**
+     * @param writer Writer.
+     * @param elementType Element type.
+     * @param arr The array.
+     * @param compTypeId Component type ID.
+     */
+    public void writeArray(PortableWriterExImpl writer, byte elementType, Object[] arr, int compTypeId) {
+        writer.writeByte(elementType);
+        writer.writeInt(compTypeId);
+        writer.writeInt(arr.length);
+
+        for (Object obj : arr)
+            writeValue(writer, obj);
+    }
+
+    /**
+     * @param writer Writer.
+     * @param elementType Element type.
+     * @param arr The array.
+     * @param clsName Component class name.
+     */
+    public void writeArray(PortableWriterExImpl writer, byte elementType, Object[] arr, String clsName) {
+        writer.writeByte(elementType);
+        writer.writeInt(GridPortableMarshaller.UNREGISTERED_TYPE_ID);
+        writer.writeString(clsName);
+        writer.writeInt(arr.length);
+
+        for (Object obj : arr)
+            writeValue(writer, obj);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableClassDescriptor.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableClassDescriptor.java b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableClassDescriptor.java
new file mode 100644
index 0000000..fb2bdc2
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableClassDescriptor.java
@@ -0,0 +1,1344 @@
+/*
+ * 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.portable;
+
+import org.apache.ignite.*;
+import org.apache.ignite.internal.processors.cache.*;
+import org.apache.ignite.internal.util.typedef.internal.*;
+import org.apache.ignite.marshaller.*;
+import org.apache.ignite.portable.*;
+
+import org.jetbrains.annotations.*;
+
+import java.io.*;
+import java.lang.reflect.*;
+import java.math.*;
+import java.sql.*;
+import java.util.*;
+import java.util.Date;
+
+import static java.lang.reflect.Modifier.*;
+
+/**
+ * Portable class descriptor.
+ */
+class PortableClassDescriptor {
+    /** */
+    private final PortableContext ctx;
+
+    /** */
+    private final Class<?> cls;
+
+    /** */
+    private final PortableSerializer serializer;
+
+    /** */
+    private final Mode mode;
+
+    /** */
+    private final boolean userType;
+
+    /** */
+    private final int typeId;
+
+    /** */
+    private final String typeName;
+
+    /** */
+    private final Constructor<?> ctor;
+
+    /** */
+    private final Collection<FieldInfo> fields;
+
+    /** */
+    private final Method writeReplaceMtd;
+
+    /** */
+    private final Method readResolveMtd;
+
+    /** */
+    private final boolean useTs;
+
+    /** */
+    private final Map<String, String> fieldsMeta;
+
+    /** */
+    private final boolean keepDeserialized;
+
+    /** */
+    private final boolean registered;
+
+    /** */
+    private final boolean excluded;
+
+    /**
+     * @param ctx Context.
+     * @param cls Class.
+     * @param userType User type flag.
+     * @param typeId Type ID.
+     * @param typeName Type name.
+     * @param idMapper ID mapper.
+     * @param serializer Serializer.
+     * @param useTs Use timestamp flag.
+     * @param metaDataEnabled Metadata enabled flag.
+     * @param keepDeserialized Keep deserialized flag.
+     * @throws PortableException In case of error.
+     */
+    PortableClassDescriptor(
+        PortableContext ctx,
+        Class<?> cls,
+        boolean userType,
+        int typeId,
+        String typeName,
+        @Nullable PortableIdMapper idMapper,
+        @Nullable PortableSerializer serializer,
+        boolean useTs,
+        boolean metaDataEnabled,
+        boolean keepDeserialized
+    ) throws PortableException {
+        this(ctx, cls, userType, typeId, typeName, idMapper, serializer, useTs, metaDataEnabled, keepDeserialized,
+             true);
+    }
+
+    /**
+     * @param ctx Context.
+     * @param cls Class.
+     * @param userType User type flag.
+     * @param typeId Type ID.
+     * @param typeName Type name.
+     * @param idMapper ID mapper.
+     * @param serializer Serializer.
+     * @param useTs Use timestamp flag.
+     * @param metaDataEnabled Metadata enabled flag.
+     * @param keepDeserialized Keep deserialized flag.
+     * @param registered Whether typeId has been successfully registered by MarshallerContext or not.
+     * @throws PortableException In case of error.
+     */
+    PortableClassDescriptor(
+        PortableContext ctx,
+        Class<?> cls,
+        boolean userType,
+        int typeId,
+        String typeName,
+        @Nullable PortableIdMapper idMapper,
+        @Nullable PortableSerializer serializer,
+        boolean useTs,
+        boolean metaDataEnabled,
+        boolean keepDeserialized,
+        boolean registered
+    ) throws PortableException {
+        assert ctx != null;
+        assert cls != null;
+
+        this.ctx = ctx;
+        this.cls = cls;
+        this.userType = userType;
+        this.typeId = typeId;
+        this.typeName = typeName;
+        this.serializer = serializer;
+        this.useTs = useTs;
+        this.keepDeserialized = keepDeserialized;
+        this.registered = registered;
+
+        excluded = MarshallerExclusions.isExcluded(cls);
+
+        if (excluded)
+            mode = Mode.EXCLUSION;
+        else
+            mode = serializer != null ? Mode.PORTABLE : mode(cls);
+
+        switch (mode) {
+            case BYTE:
+            case SHORT:
+            case INT:
+            case LONG:
+            case FLOAT:
+            case DOUBLE:
+            case CHAR:
+            case BOOLEAN:
+            case DECIMAL:
+            case STRING:
+            case UUID:
+            case DATE:
+            case BYTE_ARR:
+            case SHORT_ARR:
+            case INT_ARR:
+            case LONG_ARR:
+            case FLOAT_ARR:
+            case DOUBLE_ARR:
+            case CHAR_ARR:
+            case BOOLEAN_ARR:
+            case DECIMAL_ARR:
+            case STRING_ARR:
+            case UUID_ARR:
+            case DATE_ARR:
+            case OBJ_ARR:
+            case COL:
+            case MAP:
+            case MAP_ENTRY:
+            case PORTABLE_OBJ:
+            case ENUM:
+            case ENUM_ARR:
+            case CLASS:
+            case EXCLUSION:
+                ctor = null;
+                fields = null;
+                fieldsMeta = null;
+
+                break;
+
+            case PORTABLE:
+            case EXTERNALIZABLE:
+                ctor = constructor(cls);
+                fields = null;
+                fieldsMeta = null;
+
+                break;
+
+            case OBJECT:
+                assert idMapper != null;
+
+                ctor = constructor(cls);
+                fields = new ArrayList<>();
+                fieldsMeta = metaDataEnabled ? new HashMap<String, String>() : null;
+
+                Collection<String> names = new HashSet<>();
+                Collection<Integer> ids = new HashSet<>();
+
+                for (Class<?> c = cls; c != null && !c.equals(Object.class); c = c.getSuperclass()) {
+                    for (Field f : c.getDeclaredFields()) {
+                        int mod = f.getModifiers();
+
+                        if (!isStatic(mod) && !isTransient(mod)) {
+                            f.setAccessible(true);
+
+                            String name = f.getName();
+
+                            if (!names.add(name))
+                                throw new PortableException("Duplicate field name: " + name);
+
+                            int fieldId = idMapper.fieldId(typeId, name);
+
+                            if (!ids.add(fieldId))
+                                throw new PortableException("Duplicate field ID: " + name);
+
+                            FieldInfo fieldInfo = new FieldInfo(f, fieldId);
+
+                            fields.add(fieldInfo);
+
+                            if (metaDataEnabled)
+                                fieldsMeta.put(name, fieldInfo.fieldMode().typeName());
+                        }
+                    }
+                }
+
+                break;
+
+            default:
+                // Should never happen.
+                throw new PortableException("Invalid mode: " + mode);
+        }
+
+        if (mode == Mode.PORTABLE || mode == Mode.EXTERNALIZABLE || mode == Mode.OBJECT) {
+            readResolveMtd = U.findNonPublicMethod(cls, "readResolve");
+            writeReplaceMtd = U.findNonPublicMethod(cls, "writeReplace");
+        }
+        else {
+            readResolveMtd = null;
+            writeReplaceMtd = null;
+        }
+    }
+
+    /**
+     * @return Described class.
+     */
+    Class<?> describedClass() {
+        return cls;
+    }
+
+    /**
+     * @return Type ID.
+     */
+    int typeId() {
+        return typeId;
+    }
+
+    /**
+     * @return Fields meta data.
+     */
+    Map<String, String> fieldsMeta() {
+        return fieldsMeta;
+    }
+
+    /**
+     * @return Use timestamp flag.
+     */
+    boolean isUseTimestamp() {
+        return useTs;
+    }
+
+    /**
+     * @return Keep deserialized flag.
+     */
+    boolean keepDeserialized() {
+        return keepDeserialized;
+    }
+
+    /**
+     * @return Whether typeId has been successfully registered by MarshallerContext or not.
+     */
+    public boolean isRegistered() {
+        return registered;
+    }
+
+    /**
+     * Checks whether the class values are explicitly excluded from marshalling.
+     *
+     * @return {@code true} if excluded, {@code false} otherwise.
+     */
+    public boolean excluded() {
+        return excluded;
+    }
+
+    /**
+     * @return portableWriteReplace() method
+     */
+    @Nullable Method getWriteReplaceMethod() {
+        return writeReplaceMtd;
+    }
+
+    /**
+     * @return portableReadResolve() method
+     */
+    @Nullable Method getReadResolveMethod() {
+        return readResolveMtd;
+    }
+
+    /**
+     * @param obj Object.
+     * @param writer Writer.
+     * @throws PortableException In case of error.
+     */
+    void write(Object obj, PortableWriterExImpl writer) throws PortableException {
+        assert obj != null;
+        assert writer != null;
+
+        switch (mode) {
+            case BYTE:
+                writer.doWriteByte(GridPortableMarshaller.BYTE);
+                writer.doWriteByte((byte)obj);
+
+                break;
+
+            case SHORT:
+                writer.doWriteByte(GridPortableMarshaller.SHORT);
+                writer.doWriteShort((short)obj);
+
+                break;
+
+            case INT:
+                writer.doWriteByte(GridPortableMarshaller.INT);
+                writer.doWriteInt((int)obj);
+
+                break;
+
+            case LONG:
+                writer.doWriteByte(GridPortableMarshaller.LONG);
+                writer.doWriteLong((long)obj);
+
+                break;
+
+            case FLOAT:
+                writer.doWriteByte(GridPortableMarshaller.FLOAT);
+                writer.doWriteFloat((float)obj);
+
+                break;
+
+            case DOUBLE:
+                writer.doWriteByte(GridPortableMarshaller.DOUBLE);
+                writer.doWriteDouble((double)obj);
+
+                break;
+
+            case CHAR:
+                writer.doWriteByte(GridPortableMarshaller.CHAR);
+                writer.doWriteChar((char)obj);
+
+                break;
+
+            case BOOLEAN:
+                writer.doWriteByte(GridPortableMarshaller.BOOLEAN);
+                writer.doWriteBoolean((boolean)obj);
+
+                break;
+
+            case DECIMAL:
+                writer.doWriteDecimal((BigDecimal) obj);
+
+                break;
+
+            case STRING:
+                writer.doWriteString((String)obj);
+
+                break;
+
+            case UUID:
+                writer.doWriteUuid((UUID)obj);
+
+                break;
+
+            case DATE:
+                if (obj instanceof Timestamp)
+                    writer.doWriteTimestamp((Timestamp)obj);
+                else
+                    writer.doWriteDate((Date)obj);
+
+                break;
+
+            case BYTE_ARR:
+                writer.doWriteByteArray((byte[])obj);
+
+                break;
+
+            case SHORT_ARR:
+                writer.doWriteShortArray((short[])obj);
+
+                break;
+
+            case INT_ARR:
+                writer.doWriteIntArray((int[])obj);
+
+                break;
+
+            case LONG_ARR:
+                writer.doWriteLongArray((long[])obj);
+
+                break;
+
+            case FLOAT_ARR:
+                writer.doWriteFloatArray((float[])obj);
+
+                break;
+
+            case DOUBLE_ARR:
+                writer.doWriteDoubleArray((double[])obj);
+
+                break;
+
+            case CHAR_ARR:
+                writer.doWriteCharArray((char[])obj);
+
+                break;
+
+            case BOOLEAN_ARR:
+                writer.doWriteBooleanArray((boolean[])obj);
+
+                break;
+
+            case DECIMAL_ARR:
+                writer.doWriteDecimalArray((BigDecimal[])obj);
+
+                break;
+
+            case STRING_ARR:
+                writer.doWriteStringArray((String[])obj);
+
+                break;
+
+            case UUID_ARR:
+                writer.doWriteUuidArray((UUID[])obj);
+
+                break;
+
+            case DATE_ARR:
+                writer.doWriteDateArray((Date[])obj);
+
+                break;
+
+            case OBJ_ARR:
+                writer.doWriteObjectArray((Object[])obj);
+
+                break;
+
+            case COL:
+                writer.doWriteCollection((Collection<?>)obj);
+
+                break;
+
+            case MAP:
+                writer.doWriteMap((Map<?, ?>)obj);
+
+                break;
+
+            case MAP_ENTRY:
+                writer.doWriteMapEntry((Map.Entry<?, ?>)obj);
+
+                break;
+
+            case ENUM:
+                writer.doWriteEnum((Enum<?>)obj);
+
+                break;
+
+            case ENUM_ARR:
+                writer.doWriteEnumArray((Object[])obj);
+
+                break;
+
+            case CLASS:
+                writer.doWriteClass((Class)obj);
+
+                break;
+
+            case PORTABLE_OBJ:
+                writer.doWritePortableObject((PortableObjectImpl)obj);
+
+                break;
+
+            case PORTABLE:
+                if (writeHeader(obj, writer)) {
+                    if (serializer != null)
+                        serializer.writePortable(obj, writer);
+                    else
+                        ((PortableMarshalAware)obj).writePortable(writer);
+
+                    writer.writeRawOffsetIfNeeded();
+                    writer.writeLength();
+
+                    if (obj.getClass() != PortableMetaDataImpl.class
+                        && ctx.isMetaDataChanged(typeId, writer.metaDataHashSum())) {
+                        PortableMetaDataCollector metaCollector = new PortableMetaDataCollector(typeName);
+
+                        if (serializer != null)
+                            serializer.writePortable(obj, metaCollector);
+                        else
+                            ((PortableMarshalAware)obj).writePortable(metaCollector);
+
+                        ctx.updateMetaData(typeId, typeName, metaCollector.meta());
+                    }
+                }
+
+                break;
+
+            case EXTERNALIZABLE:
+                if (writeHeader(obj, writer)) {
+                    try {
+                        ((Externalizable)obj).writeExternal(writer);
+                    }
+                    catch (IOException e) {
+                        throw new PortableException("Failed to write Externalizable object: " + obj, e);
+                    }
+
+                    writer.writeLength();
+                }
+
+                break;
+
+            case OBJECT:
+                if (writeHeader(obj, writer)) {
+                    for (FieldInfo info : fields)
+                        info.write(obj, writer);
+
+                    writer.writeRawOffsetIfNeeded();
+                    writer.writeLength();
+                }
+
+                break;
+
+            default:
+                assert false : "Invalid mode: " + mode;
+        }
+    }
+
+    /**
+     * @param reader Reader.
+     * @return Object.
+     * @throws PortableException If failed.
+     */
+    Object read(PortableReaderExImpl reader) throws PortableException {
+        assert reader != null;
+
+        Object res;
+
+        switch (mode) {
+            case PORTABLE:
+                res = newInstance();
+
+                reader.setHandler(res);
+
+                if (serializer != null)
+                    serializer.readPortable(res, reader);
+                else
+                    ((PortableMarshalAware)res).readPortable(reader);
+
+                break;
+
+            case EXTERNALIZABLE:
+                res = newInstance();
+
+                reader.setHandler(res);
+
+                try {
+                    ((Externalizable)res).readExternal(reader);
+                }
+                catch (IOException | ClassNotFoundException e) {
+                    throw new PortableException("Failed to read Externalizable object: " +
+                        res.getClass().getName(), e);
+                }
+
+                break;
+
+            case OBJECT:
+                res = newInstance();
+
+                reader.setHandler(res);
+
+                for (FieldInfo info : fields)
+                    info.read(res, reader);
+
+                break;
+
+            default:
+                assert false : "Invalid mode: " + mode;
+
+                return null;
+        }
+
+        if (readResolveMtd != null) {
+            try {
+                res = readResolveMtd.invoke(res);
+
+                reader.setHandler(res);
+            }
+            catch (IllegalAccessException e) {
+                throw new RuntimeException(e);
+            }
+            catch (InvocationTargetException e) {
+                if (e.getTargetException() instanceof PortableException)
+                    throw (PortableException)e.getTargetException();
+
+                throw new PortableException("Failed to execute readResolve() method on " + res, e);
+            }
+        }
+
+        return res;
+    }
+
+    /**
+     * @param obj Object.
+     * @param writer Writer.
+     * @return Whether further write is needed.
+     */
+    private boolean writeHeader(Object obj, PortableWriterExImpl writer) {
+        int handle = writer.handle(obj);
+
+        if (handle >= 0) {
+            writer.doWriteByte(GridPortableMarshaller.HANDLE);
+            writer.doWriteInt(handle);
+
+            return false;
+        }
+        else {
+            int pos = writer.position();
+
+            writer.doWriteByte(GridPortableMarshaller.OBJ);
+            writer.doWriteBoolean(userType);
+            writer.doWriteInt(registered ? typeId : GridPortableMarshaller.UNREGISTERED_TYPE_ID);
+            writer.doWriteInt(obj instanceof CacheObjectImpl ? 0 : obj.hashCode());
+
+            // For length and raw offset.
+            int reserved = writer.reserve(8);
+
+            // Class name in case if typeId registration is failed.
+            if (!registered)
+                writer.doWriteString(cls.getName());
+
+            int current = writer.position();
+            int len = current - pos;
+
+            // Default raw offset (equal to header length).
+            writer.position(reserved + 4);
+            writer.doWriteInt(len);
+            writer.position(current);
+
+            return true;
+        }
+    }
+
+    /**
+     * @return Instance.
+     * @throws PortableException In case of error.
+     */
+    private Object newInstance() throws PortableException {
+        assert ctor != null;
+
+        try {
+            return ctor.newInstance();
+        }
+        catch (InstantiationException | InvocationTargetException | IllegalAccessException e) {
+            throw new PortableException("Failed to instantiate instance: " + cls, e);
+        }
+    }
+
+    /**
+     * @param cls Class.
+     * @return Constructor.
+     * @throws PortableException If constructor doesn't exist.
+     */
+    @Nullable private static Constructor<?> constructor(Class<?> cls) throws PortableException {
+        assert cls != null;
+
+        try {
+            Constructor<?> ctor = U.forceEmptyConstructor(cls);
+
+            ctor.setAccessible(true);
+
+            return ctor;
+        }
+        catch (IgniteCheckedException e) {
+            throw new PortableException("Failed to get constructor for class: " + cls.getName(), e);
+        }
+    }
+
+    /**
+     * @param cls Class.
+     * @return Mode.
+     */
+    @SuppressWarnings("IfMayBeConditional")
+    private static Mode mode(Class<?> cls) {
+        assert cls != null;
+
+        if (cls == byte.class || cls == Byte.class)
+            return Mode.BYTE;
+        else if (cls == short.class || cls == Short.class)
+            return Mode.SHORT;
+        else if (cls == int.class || cls == Integer.class)
+            return Mode.INT;
+        else if (cls == long.class || cls == Long.class)
+            return Mode.LONG;
+        else if (cls == float.class || cls == Float.class)
+            return Mode.FLOAT;
+        else if (cls == double.class || cls == Double.class)
+            return Mode.DOUBLE;
+        else if (cls == char.class || cls == Character.class)
+            return Mode.CHAR;
+        else if (cls == boolean.class || cls == Boolean.class)
+            return Mode.BOOLEAN;
+        else if (cls == BigDecimal.class)
+            return Mode.DECIMAL;
+        else if (cls == String.class)
+            return Mode.STRING;
+        else if (cls == UUID.class)
+            return Mode.UUID;
+        else if (cls == Timestamp.class || cls == Date.class)
+            return Mode.DATE;
+        else if (cls == byte[].class)
+            return Mode.BYTE_ARR;
+        else if (cls == short[].class)
+            return Mode.SHORT_ARR;
+        else if (cls == int[].class)
+            return Mode.INT_ARR;
+        else if (cls == long[].class)
+            return Mode.LONG_ARR;
+        else if (cls == float[].class)
+            return Mode.FLOAT_ARR;
+        else if (cls == double[].class)
+            return Mode.DOUBLE_ARR;
+        else if (cls == char[].class)
+            return Mode.CHAR_ARR;
+        else if (cls == boolean[].class)
+            return Mode.BOOLEAN_ARR;
+        else if (cls == BigDecimal[].class)
+            return Mode.DECIMAL_ARR;
+        else if (cls == String[].class)
+            return Mode.STRING_ARR;
+        else if (cls == UUID[].class)
+            return Mode.UUID_ARR;
+        else if (cls == Date[].class)
+            return Mode.DATE_ARR;
+        else if (cls.isArray())
+            return cls.getComponentType().isEnum() ? Mode.ENUM_ARR : Mode.OBJ_ARR;
+        else if (cls == PortableObjectImpl.class)
+            return Mode.PORTABLE_OBJ;
+        else if (PortableMarshalAware.class.isAssignableFrom(cls))
+           return Mode.PORTABLE;
+        else if (Externalizable.class.isAssignableFrom(cls))
+            return Mode.EXTERNALIZABLE;
+        else if (Map.Entry.class.isAssignableFrom(cls))
+            return Mode.MAP_ENTRY;
+        else if (Collection.class.isAssignableFrom(cls))
+            return Mode.COL;
+        else if (Map.class.isAssignableFrom(cls))
+            return Mode.MAP;
+        else if (cls == PortableObjectImpl.class)
+            return Mode.PORTABLE_OBJ;
+        else if (cls.isEnum())
+            return Mode.ENUM;
+        else if (cls == Class.class)
+            return Mode.CLASS;
+        else
+            return Mode.OBJECT;
+    }
+
+    /** */
+    private static class FieldInfo {
+        /** */
+        private final Field field;
+
+        /** */
+        private final int id;
+
+        /** */
+        private final Mode mode;
+
+        /**
+         * @param field Field.
+         * @param id Field ID.
+         */
+        private FieldInfo(Field field, int id) {
+            assert field != null;
+
+            this.field = field;
+            this.id = id;
+
+            Class<?> type = field.getType();
+
+            mode = mode(type);
+        }
+
+        /**
+         * @return Field mode.
+         */
+        public Mode fieldMode() {
+            return mode;
+        }
+
+        /**
+         * @param obj Object.
+         * @param writer Writer.
+         * @throws PortableException In case of error.
+         */
+        public void write(Object obj, PortableWriterExImpl writer) throws PortableException {
+            assert obj != null;
+            assert writer != null;
+
+            writer.doWriteInt(id);
+
+            Object val;
+
+            try {
+                val = field.get(obj);
+            }
+            catch (IllegalAccessException e) {
+                throw new PortableException("Failed to get value for field: " + field, e);
+            }
+
+            switch (mode) {
+                case BYTE:
+                    writer.writeByteField((Byte)val);
+
+                    break;
+
+                case SHORT:
+                    writer.writeShortField((Short)val);
+
+                    break;
+
+                case INT:
+                    writer.writeIntField((Integer)val);
+
+                    break;
+
+                case LONG:
+                    writer.writeLongField((Long)val);
+
+                    break;
+
+                case FLOAT:
+                    writer.writeFloatField((Float)val);
+
+                    break;
+
+                case DOUBLE:
+                    writer.writeDoubleField((Double)val);
+
+                    break;
+
+                case CHAR:
+                    writer.writeCharField((Character)val);
+
+                    break;
+
+                case BOOLEAN:
+                    writer.writeBooleanField((Boolean)val);
+
+                    break;
+
+                case DECIMAL:
+                    writer.writeDecimalField((BigDecimal)val);
+
+                    break;
+
+                case STRING:
+                    writer.writeStringField((String)val);
+
+                    break;
+
+                case UUID:
+                    writer.writeUuidField((UUID)val);
+
+                    break;
+
+                case DATE:
+                    if (val instanceof Timestamp)
+                        writer.writeTimestampField((Timestamp)val);
+                    else
+                        writer.writeDateField((Date)val);
+
+                    break;
+
+                case BYTE_ARR:
+                    writer.writeByteArrayField((byte[])val);
+
+                    break;
+
+                case SHORT_ARR:
+                    writer.writeShortArrayField((short[])val);
+
+                    break;
+
+                case INT_ARR:
+                    writer.writeIntArrayField((int[])val);
+
+                    break;
+
+                case LONG_ARR:
+                    writer.writeLongArrayField((long[])val);
+
+                    break;
+
+                case FLOAT_ARR:
+                    writer.writeFloatArrayField((float[])val);
+
+                    break;
+
+                case DOUBLE_ARR:
+                    writer.writeDoubleArrayField((double[])val);
+
+                    break;
+
+                case CHAR_ARR:
+                    writer.writeCharArrayField((char[])val);
+
+                    break;
+
+                case BOOLEAN_ARR:
+                    writer.writeBooleanArrayField((boolean[])val);
+
+                    break;
+
+                case DECIMAL_ARR:
+                    writer.writeDecimalArrayField((BigDecimal[])val);
+
+                    break;
+
+                case STRING_ARR:
+                    writer.writeStringArrayField((String[])val);
+
+                    break;
+
+                case UUID_ARR:
+                    writer.writeUuidArrayField((UUID[])val);
+
+                    break;
+
+                case DATE_ARR:
+                    writer.writeDateArrayField((Date[])val);
+
+                    break;
+
+                case OBJ_ARR:
+                    writer.writeObjectArrayField((Object[])val);
+
+                    break;
+
+                case COL:
+                    writer.writeCollectionField((Collection<?>)val);
+
+                    break;
+
+                case MAP:
+                    writer.writeMapField((Map<?, ?>)val);
+
+                    break;
+
+                case MAP_ENTRY:
+                    writer.writeMapEntryField((Map.Entry<?, ?>)val);
+
+                    break;
+
+                case PORTABLE_OBJ:
+                    writer.writePortableObjectField((PortableObjectImpl)val);
+
+                    break;
+
+                case ENUM:
+                    writer.writeEnumField((Enum<?>)val);
+
+                    break;
+
+                case ENUM_ARR:
+                    writer.writeEnumArrayField((Object[])val);
+
+                    break;
+
+                case PORTABLE:
+                case EXTERNALIZABLE:
+                case OBJECT:
+                    writer.writeObjectField(val);
+
+                    break;
+
+                case CLASS:
+                    writer.writeClassField((Class)val);
+
+                    break;
+
+                default:
+                    assert false : "Invalid mode: " + mode;
+            }
+        }
+
+        /**
+         * @param obj Object.
+         * @param reader Reader.
+         * @throws PortableException In case of error.
+         */
+        public void read(Object obj, PortableReaderExImpl reader) throws PortableException {
+            Object val = null;
+
+            switch (mode) {
+                case BYTE:
+                    val = reader.readByte(id);
+
+                    break;
+
+                case SHORT:
+                    val = reader.readShort(id);
+
+                    break;
+
+                case INT:
+                    val = reader.readInt(id);
+
+                    break;
+
+                case LONG:
+                    val = reader.readLong(id);
+
+                    break;
+
+                case FLOAT:
+                    val = reader.readFloat(id);
+
+                    break;
+
+                case DOUBLE:
+                    val = reader.readDouble(id);
+
+                    break;
+
+                case CHAR:
+                    val = reader.readChar(id);
+
+                    break;
+
+                case BOOLEAN:
+                    val = reader.readBoolean(id);
+
+                    break;
+
+                case DECIMAL:
+                    val = reader.readDecimal(id);
+
+                    break;
+
+                case STRING:
+                    val = reader.readString(id);
+
+                    break;
+
+                case UUID:
+                    val = reader.readUuid(id);
+
+                    break;
+
+                case DATE:
+                    val = field.getType() == Timestamp.class ? reader.readTimestamp(id) : reader.readDate(id);
+
+                    break;
+
+                case BYTE_ARR:
+                    val = reader.readByteArray(id);
+
+                    break;
+
+                case SHORT_ARR:
+                    val = reader.readShortArray(id);
+
+                    break;
+
+                case INT_ARR:
+                    val = reader.readIntArray(id);
+
+                    break;
+
+                case LONG_ARR:
+                    val = reader.readLongArray(id);
+
+                    break;
+
+                case FLOAT_ARR:
+                    val = reader.readFloatArray(id);
+
+                    break;
+
+                case DOUBLE_ARR:
+                    val = reader.readDoubleArray(id);
+
+                    break;
+
+                case CHAR_ARR:
+                    val = reader.readCharArray(id);
+
+                    break;
+
+                case BOOLEAN_ARR:
+                    val = reader.readBooleanArray(id);
+
+                    break;
+
+                case DECIMAL_ARR:
+                    val = reader.readDecimalArray(id);
+
+                    break;
+
+                case STRING_ARR:
+                    val = reader.readStringArray(id);
+
+                    break;
+
+                case UUID_ARR:
+                    val = reader.readUuidArray(id);
+
+                    break;
+
+                case DATE_ARR:
+                    val = reader.readDateArray(id);
+
+                    break;
+
+                case OBJ_ARR:
+                    val = reader.readObjectArray(id);
+
+                    break;
+
+                case COL:
+                    val = reader.readCollection(id, null);
+
+                    break;
+
+                case MAP:
+                    val = reader.readMap(id, null);
+
+                    break;
+
+                case MAP_ENTRY:
+                    val = reader.readMapEntry(id);
+
+                    break;
+
+                case PORTABLE_OBJ:
+                    val = reader.readPortableObject(id);
+
+                    break;
+
+                case ENUM:
+                    val = reader.readEnum(id, field.getType());
+
+                    break;
+
+                case ENUM_ARR:
+                    val = reader.readEnumArray(id, field.getType().getComponentType());
+
+                    break;
+
+                case PORTABLE:
+                case EXTERNALIZABLE:
+                case OBJECT:
+                    val = reader.readObject(id);
+
+                    break;
+
+                case CLASS:
+                    val = reader.readClass(id);
+
+                    break;
+
+                default:
+                    assert false : "Invalid mode: " + mode;
+            }
+
+            try {
+                if (val != null || !field.getType().isPrimitive())
+                    field.set(obj, val);
+            }
+            catch (IllegalAccessException e) {
+                throw new PortableException("Failed to set value for field: " + field, e);
+            }
+        }
+    }
+
+    /** */
+    enum Mode {
+        /** */
+        BYTE("byte"),
+
+        /** */
+        SHORT("short"),
+
+        /** */
+        INT("int"),
+
+        /** */
+        LONG("long"),
+
+        /** */
+        FLOAT("float"),
+
+        /** */
+        DOUBLE("double"),
+
+        /** */
+        CHAR("char"),
+
+        /** */
+        BOOLEAN("boolean"),
+
+        /** */
+        DECIMAL("decimal"),
+
+        /** */
+        STRING("String"),
+
+        /** */
+        UUID("UUID"),
+
+        /** */
+        DATE("Date"),
+
+        /** */
+        BYTE_ARR("byte[]"),
+
+        /** */
+        SHORT_ARR("short[]"),
+
+        /** */
+        INT_ARR("int[]"),
+
+        /** */
+        LONG_ARR("long[]"),
+
+        /** */
+        FLOAT_ARR("float[]"),
+
+        /** */
+        DOUBLE_ARR("double[]"),
+
+        /** */
+        CHAR_ARR("char[]"),
+
+        /** */
+        BOOLEAN_ARR("boolean[]"),
+
+        /** */
+        DECIMAL_ARR("decimal[]"),
+
+        /** */
+        STRING_ARR("String[]"),
+
+        /** */
+        UUID_ARR("UUID[]"),
+
+        /** */
+        DATE_ARR("Date[]"),
+
+        /** */
+        OBJ_ARR("Object[]"),
+
+        /** */
+        COL("Collection"),
+
+        /** */
+        MAP("Map"),
+
+        /** */
+        MAP_ENTRY("Entry"),
+
+        /** */
+        PORTABLE_OBJ("Object"),
+
+        /** */
+        ENUM("Enum"),
+
+        /** */
+        ENUM_ARR("Enum[]"),
+
+        /** */
+        CLASS("Class"),
+
+        /** */
+        PORTABLE("Object"),
+
+        /** */
+        EXTERNALIZABLE("Object"),
+
+        /** */
+        OBJECT("Object"),
+
+        /** */
+        EXCLUSION("Exclusion");
+
+        /** */
+        private final String typeName;
+
+        /**
+         * @param typeName Type name.
+         */
+        Mode(String typeName) {
+            this.typeName = typeName;
+        }
+
+        /**
+         * @return Type name.
+         */
+        String typeName() {
+            return typeName;
+        }
+    }
+}


[41/59] [abbrv] ignite git commit: Moving platform utility methods to Ignite.

Posted by vk...@apache.org.
Moving platform utility methods to Ignite.


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

Branch: refs/heads/ignite-884
Commit: bcf3054b0f6861fad32cc81d2ecf89ecd9eaf6aa
Parents: 7c351bf
Author: vozerov-gridgain <vo...@gridgain.com>
Authored: Wed Aug 26 12:28:17 2015 +0300
Committer: vozerov-gridgain <vo...@gridgain.com>
Committed: Wed Aug 26 12:28:17 2015 +0300

----------------------------------------------------------------------
 .../platform/utils/PlatformUtils.java           | 531 +++++++++++++++++++
 1 file changed, 531 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/bcf3054b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/utils/PlatformUtils.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/utils/PlatformUtils.java b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/utils/PlatformUtils.java
new file mode 100644
index 0000000..a620f8e
--- /dev/null
+++ b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/utils/PlatformUtils.java
@@ -0,0 +1,531 @@
+/*
+ * 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.platform.utils;
+
+import org.apache.ignite.*;
+import org.apache.ignite.cache.*;
+import org.apache.ignite.internal.portable.*;
+import org.apache.ignite.internal.processors.platform.*;
+import org.apache.ignite.internal.processors.platform.memory.*;
+import org.apache.ignite.internal.util.typedef.internal.*;
+import org.apache.ignite.lang.*;
+import org.jetbrains.annotations.*;
+
+import javax.cache.*;
+import javax.cache.event.*;
+import java.util.*;
+
+/**
+ * Platform utility methods.
+ */
+@SuppressWarnings({"UnusedDeclaration", "unchecked"})
+public class PlatformUtils {
+    /** Amount of peek modes available. */
+    private static final int CACHE_PEEK_MODES_CNT = CachePeekMode.values().length;
+
+    /** Cache peek modes. */
+    private static volatile CachePeekMode[][] CACHE_PEEK_MODES;
+
+    /**
+     * Static initializer.
+     */
+    static {
+        int len = 1 << CACHE_PEEK_MODES_CNT;
+
+        synchronized (PlatformUtils.class) {
+            CACHE_PEEK_MODES = new CachePeekMode[len][];
+
+            CACHE_PEEK_MODES[0] = new CachePeekMode[0];
+        }
+    }
+
+    /**
+     * Write nullable collection to the writer.
+     *
+     * @param writer Writer.
+     * @param col Collection to write.
+     */
+    public static <T> void writeNullableCollection(PortableRawWriterEx writer, @Nullable Collection<T> col) {
+        writeNullableCollection(writer, col, null, null);
+    }
+
+    /**
+     * Write nullable collection to the writer.
+     *
+     * @param writer Writer.
+     * @param col Collection to write.
+     * @param writeClo Writer closure.
+     */
+    public static <T> void writeNullableCollection(PortableRawWriterEx writer, @Nullable Collection<T> col,
+        @Nullable PlatformWriterClosure<T> writeClo) {
+        writeNullableCollection(writer, col, writeClo, null);
+    }
+
+    /**
+     * Write collection to the writer.
+     *
+     * @param writer Writer.
+     * @param col Collection to write.
+     * @param writeClo Optional writer closure.
+     * @param filter Optional filter.
+     */
+    public static <T> void writeNullableCollection(PortableRawWriterEx writer, @Nullable Collection<T> col,
+        @Nullable PlatformWriterClosure<T> writeClo, @Nullable IgnitePredicate<T> filter) {
+        if (col != null) {
+            writer.writeBoolean(true);
+
+            writeCollection(writer, col, writeClo, filter);
+        }
+        else
+            writer.writeBoolean(false);
+    }
+
+    /**
+     * Write collection to the writer.
+     *
+     * @param writer Writer.
+     * @param col Collection to write.
+     */
+    public static <T> void writeCollection(PortableRawWriterEx writer, Collection<T> col) {
+        writeCollection(writer, col, null, null);
+    }
+
+    /**
+     * Write collection to the writer.
+     *
+     * @param writer Writer.
+     * @param col Collection to write.
+     * @param writeClo Writer closure.
+     */
+    public static <T> void writeCollection(PortableRawWriterEx writer, Collection<T> col,
+        @Nullable PlatformWriterClosure<T> writeClo) {
+        writeCollection(writer, col, writeClo, null);
+    }
+
+    /**
+     * Write collection to the writer.
+     *
+     * @param writer Writer.
+     * @param col Collection to write.
+     * @param writeClo Optional writer closure.
+     * @param filter Optional filter.
+     */
+    public static <T> void writeCollection(PortableRawWriterEx writer, Collection<T> col,
+        @Nullable PlatformWriterClosure<T> writeClo, @Nullable IgnitePredicate<T> filter) {
+        assert col != null;
+
+        if (filter == null) {
+            writer.writeInt(col.size());
+
+            if (writeClo == null) {
+                for (T entry : col)
+                    writer.writeObject(entry);
+            }
+            else {
+                for (T entry : col)
+                    writeClo.write(writer, entry);
+            }
+        }
+        else {
+            int pos = writer.reserveInt();
+            int cnt = 0;
+
+            for (T entry : col) {
+                if (filter.apply(entry)) {
+                    cnt++;
+
+                    if (writeClo == null)
+                        writer.writeObject(entry);
+                    else
+                        writeClo.write(writer, entry);
+                }
+            }
+
+            writer.writeInt(pos, cnt);
+        }
+    }
+
+    /**
+     * Write nullable map to the writer.
+     *
+     * @param writer Writer.
+     * @param map Map to write.
+     */
+    public static <K, V> void writeNullableMap(PortableRawWriterEx writer, @Nullable Map<K, V> map) {
+        if (map != null) {
+            writer.writeBoolean(true);
+
+            writeMap(writer, map);
+        }
+        else
+            writer.writeBoolean(false);
+    }
+
+    /**
+     * Write nullable map to the writer.
+     *
+     * @param writer Writer.
+     * @param map Map to write.
+     */
+    public static <K, V> void writeMap(PortableRawWriterEx writer, Map<K, V> map) {
+        assert map != null;
+
+        writeMap(writer, map, null);
+    }
+
+    /**
+     * Write nullable map to the writer.
+     *
+     * @param writer Writer.
+     * @param map Map to write.
+     * @param writeClo Writer closure.
+     */
+    public static <K, V> void writeMap(PortableRawWriterEx writer, Map<K, V> map,
+        @Nullable PlatformWriterBiClosure<K, V> writeClo) {
+        assert map != null;
+
+        writer.writeInt(map.size());
+
+        if (writeClo == null) {
+            for (Map.Entry<K, V> entry : map.entrySet()) {
+                writer.writeObject(entry.getKey());
+                writer.writeObject(entry.getValue());
+            }
+        }
+        else {
+            for (Map.Entry<K, V> entry : map.entrySet())
+                writeClo.write(writer, entry.getKey(), entry.getValue());
+        }
+    }
+
+    /**
+     * Read collection.
+     *
+     * @param reader Reader.
+     * @return List.
+     */
+    public static <T> List<T> readCollection(PortableRawReaderEx reader) {
+        return readCollection(reader, null);
+    }
+
+    /**
+     * Read collection.
+     *
+     * @param reader Reader.
+     * @param readClo Optional reader closure.
+     * @return List.
+     */
+    public static <T> List<T> readCollection(PortableRawReaderEx reader, @Nullable PlatformReaderClosure<T> readClo) {
+        int cnt = reader.readInt();
+
+        List<T> res = new ArrayList<>(cnt);
+
+        if (readClo == null) {
+            for (int i = 0; i < cnt; i++)
+                res.add((T)reader.readObjectDetached());
+        }
+        else {
+            for (int i = 0; i < cnt; i++)
+                res.add(readClo.read(reader));
+        }
+
+        return res;
+    }
+
+    /**
+     * Read nullable collection.
+     *
+     * @param reader Reader.
+     * @return List.
+     */
+    public static <T> List<T> readNullableCollection(PortableRawReaderEx reader) {
+        return readNullableCollection(reader, null);
+    }
+
+    /**
+     * Read nullable collection.
+     *
+     * @param reader Reader.
+     * @return List.
+     */
+    public static <T> List<T> readNullableCollection(PortableRawReaderEx reader,
+        @Nullable PlatformReaderClosure<T> readClo) {
+        if (!reader.readBoolean())
+            return null;
+
+        return readCollection(reader, readClo);
+    }
+
+    /**
+     * @param reader Reader.
+     * @return Set.
+     */
+    public static <T> Set<T> readSet(PortableRawReaderEx reader) {
+        int cnt = reader.readInt();
+
+        Set<T> res = U.newHashSet(cnt);
+
+        for (int i = 0; i < cnt; i++)
+            res.add((T)reader.readObjectDetached());
+
+        return res;
+    }
+
+    /**
+     * @param reader Reader.
+     * @return Set.
+     */
+    public static <T> Set<T> readNullableSet(PortableRawReaderEx reader) {
+        if (!reader.readBoolean())
+            return null;
+
+        return readSet(reader);
+    }
+
+    /**
+     * Read map.
+     *
+     * @param reader Reader.
+     * @return Map.
+     */
+    public static <K, V> Map<K, V> readMap(PortableRawReaderEx reader) {
+        return readMap(reader, null);
+    }
+
+    /**
+     * Read map.
+     *
+     * @param reader Reader.
+     * @param readClo Reader closure.
+     * @return Map.
+     */
+    public static <K, V> Map<K, V> readMap(PortableRawReaderEx reader,
+        @Nullable PlatformReaderBiClosure<K, V> readClo) {
+        int cnt = reader.readInt();
+
+        Map<K, V> map = U.newHashMap(cnt);
+
+        if (readClo == null) {
+            for (int i = 0; i < cnt; i++)
+                map.put((K)reader.readObjectDetached(), (V)reader.readObjectDetached());
+        }
+        else {
+            for (int i = 0; i < cnt; i++) {
+                IgniteBiTuple<K, V> entry = readClo.read(reader);
+
+                map.put(entry.getKey(), entry.getValue());
+            }
+        }
+
+        return map;
+    }
+
+    /**
+     * Read nullable map.
+     *
+     * @param reader Reader.
+     * @return Map.
+     */
+    public static <K, V> Map<K, V> readNullableMap(PortableRawReaderEx reader) {
+        if (!reader.readBoolean())
+            return null;
+
+        return readMap(reader);
+    }
+
+    /**
+     * Writes IgniteUuid to a writer.
+     *
+     * @param writer Writer.
+     * @param val Values.
+     */
+    public static void writeIgniteUuid(PortableRawWriterEx writer, IgniteUuid val) {
+        if (val == null)
+            writer.writeUuid(null);
+        else {
+            writer.writeUuid(val.globalId());
+            writer.writeLong(val.localId());
+        }
+    }
+
+    /**
+     * Convert native cache peek modes to Java cache peek modes.
+     *
+     * @param modes Encoded peek modes.
+     * @return Cache peek modes.
+     */
+    public static CachePeekMode[] decodeCachePeekModes(int modes) {
+        // 1. Try getting cache value.
+        CachePeekMode[] res = CACHE_PEEK_MODES[modes];
+
+        if (res == null) {
+            // 2. Calculate modes from scratch.
+            List<CachePeekMode> res0 = new ArrayList<>(CACHE_PEEK_MODES_CNT);
+
+            for (int i = 0; i < CACHE_PEEK_MODES_CNT; i++) {
+                int mask = 1 << i;
+
+                if ((modes & mask) == mask)
+                    res0.add(CachePeekMode.fromOrdinal((byte)i));
+            }
+
+            res = res0.toArray(new CachePeekMode[res0.size()]);
+
+            synchronized (PlatformUtils.class) {
+                CACHE_PEEK_MODES[modes] = res;
+            }
+        }
+
+        return res;
+    }
+
+    /**
+     * Unwrap query exception.
+     *
+     * @param err Initial error.
+     * @return Unwrapped error.
+     */
+    public static IgniteCheckedException unwrapQueryException(Throwable err) {
+        assert err != null;
+
+        Throwable parent = err;
+        Throwable child = parent.getCause();
+
+        while (true) {
+            if (child == null || child == parent)
+                break;
+
+            if (child instanceof IgniteException || child instanceof IgniteCheckedException
+                || child instanceof CacheException) {
+                // Continue unwrapping.
+                parent = child;
+
+                child = parent.getCause();
+
+                continue;
+            }
+
+            break;
+        }
+
+        // Specific exception found, but detailed message doesn't exist. Just pass exception name then.
+        if (parent.getMessage() == null)
+            return new IgniteCheckedException("Query execution failed due to exception: " +
+                parent.getClass().getName(), err);
+
+        return new IgniteCheckedException(parent.getMessage(), err);
+    }
+
+    /**
+     * Apply continuous query events to listener.
+     *
+     * @param ctx Interop context.
+     * @param lsnrPtr Listener pointer.
+     * @param evts Events.
+     * @throws javax.cache.event.CacheEntryListenerException In case of failure.
+     */
+    public static void applyContinuousQueryEvents(PlatformContext ctx, long lsnrPtr, Iterable<CacheEntryEvent> evts)
+        throws CacheEntryListenerException {
+        assert lsnrPtr != 0;
+        assert evts != null;
+
+        try (PlatformMemory mem = ctx.memory().allocate()) {
+            PlatformOutputStream out = mem.output();
+
+            PortableRawWriterEx writer = ctx.writer(out);
+
+            int cntPos = writer.reserveInt();
+
+            int cnt = 0;
+
+            for (CacheEntryEvent evt : evts) {
+                writeCacheEntryEvent(writer, evt);
+
+                cnt++;
+            }
+
+            writer.writeInt(cntPos, cnt);
+
+            out.synchronize();
+
+            ctx.gateway().continuousQueryListenerApply(lsnrPtr, mem.pointer());
+        }
+        catch (Exception e) {
+            throw toCacheEntryListenerException(e);
+        }
+    }
+
+    /**
+     * Evaluate the filter.
+     *
+     * @param ctx Interop context.
+     * @param filterPtr Native filter pointer.
+     * @param evt Event.
+     * @return Result.
+     * @throws CacheEntryListenerException In case of failure.
+     */
+    public static boolean evaluateContinuousQueryEvent(PlatformContext ctx, long filterPtr, CacheEntryEvent evt)
+        throws CacheEntryListenerException {
+        assert filterPtr != 0;
+
+        try (PlatformMemory mem = ctx.memory().allocate()) {
+            PlatformOutputStream out = mem.output();
+
+            writeCacheEntryEvent(ctx.writer(out), evt);
+
+            out.synchronize();
+
+            return ctx.gateway().continuousQueryFilterApply(filterPtr, mem.pointer()) == 1;
+        }
+        catch (Exception e) {
+            throw toCacheEntryListenerException(e);
+        }
+    }
+
+    /**
+     * Convert exception into listener exception.
+     *
+     * @param e Listener exception.
+     * @return Exception.
+     */
+    private static CacheEntryListenerException toCacheEntryListenerException(Exception e) {
+        assert e != null;
+
+        return e instanceof CacheEntryListenerException ? (CacheEntryListenerException)e : e.getMessage() != null ?
+            new CacheEntryListenerException(e.getMessage(), e) : new CacheEntryListenerException(e);
+    }
+
+    /**
+     * Write event to the writer.
+     *
+     * @param writer Writer.
+     * @param evt Event.
+     */
+    private static void writeCacheEntryEvent(PortableRawWriterEx writer, CacheEntryEvent evt) {
+        writer.writeObjectDetached(evt.getKey());
+        writer.writeObjectDetached(evt.getOldValue());
+        writer.writeObjectDetached(evt.getValue());
+    }
+
+    /**
+     * Private constructor.
+     */
+    private PlatformUtils() {
+        // No-op.
+    }
+}


[36/59] [abbrv] ignite git commit: IGNITE-1277: Enabled backups in IGFS data cache. Contributed by Ivan Veselovsky.

Posted by vk...@apache.org.
IGNITE-1277: Enabled backups in IGFS data cache.
Contributed by Ivan Veselovsky.


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

Branch: refs/heads/ignite-884
Commit: 28d64d53143119fe64e5b2e8499bb2a978800efc
Parents: 203f00c
Author: vozerov-gridgain <vo...@gridgain.com>
Authored: Wed Aug 26 10:59:54 2015 +0300
Committer: vozerov-gridgain <vo...@gridgain.com>
Committed: Wed Aug 26 10:59:54 2015 +0300

----------------------------------------------------------------------
 .../internal/processors/igfs/IgfsProcessor.java |   8 -
 .../processors/igfs/IgfsAbstractSelfTest.java   |  34 +-
 .../igfs/IgfsBackupFailoverSelfTest.java        | 488 +++++++++++++++++++
 .../igfs/IgfsBackupsDualAsyncSelfTest.java      |  40 ++
 .../igfs/IgfsBackupsDualSyncSelfTest.java       |  40 ++
 .../igfs/IgfsBackupsPrimarySelfTest.java        |  40 ++
 .../ignite/testsuites/IgniteIgfsTestSuite.java  |   7 +
 7 files changed, 643 insertions(+), 14 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/28d64d53/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsProcessor.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsProcessor.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsProcessor.java
index af41ec4..f3522a8 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsProcessor.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsProcessor.java
@@ -311,14 +311,6 @@ public class IgfsProcessor extends IgfsProcessorAdapter {
                         ", maxIgfsSpaceSize=" + maxSpaceSize + ']');
             }
 
-            if (dataCacheCfg.getCacheMode() == PARTITIONED) {
-                int backups = dataCacheCfg.getBackups();
-
-                if (backups != 0)
-                    throw new IgniteCheckedException("IGFS data cache cannot be used with backups (set backup count " +
-                        "to 0 and restart the grid): " + cfg.getDataCacheName());
-            }
-
             if (cfg.getMaxSpaceSize() == 0 && dataCacheCfg.getMemoryMode() == OFFHEAP_VALUES)
                 U.warn(log, "IGFS max space size is not specified but data cache values are stored off-heap (max " +
                     "space will be limited to 80% of max JVM heap size): " + cfg.getName());

http://git-wip-us.apache.org/repos/asf/ignite/blob/28d64d53/modules/core/src/test/java/org/apache/ignite/internal/processors/igfs/IgfsAbstractSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/igfs/IgfsAbstractSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/igfs/IgfsAbstractSelfTest.java
index a8a8957..85aaeb3 100644
--- a/modules/core/src/test/java/org/apache/ignite/internal/processors/igfs/IgfsAbstractSelfTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/igfs/IgfsAbstractSelfTest.java
@@ -146,6 +146,12 @@ public abstract class IgfsAbstractSelfTest extends IgfsCommonAbstractTest {
         this(mode, ONHEAP_TIERED);
     }
 
+    /**
+     * Constructor.
+     *
+     * @param mode
+     * @param memoryMode
+     */
     protected IgfsAbstractSelfTest(IgfsMode mode, CacheMemoryMode memoryMode) {
         assert mode != null && mode != PROXY;
 
@@ -155,7 +161,12 @@ public abstract class IgfsAbstractSelfTest extends IgfsCommonAbstractTest {
         dual = mode != PRIMARY;
     }
 
-    private static byte[] createChunk(int length) {
+    /**
+     *
+     * @param length
+     * @return
+     */
+    static byte[] createChunk(int length) {
         byte[] chunk = new byte[length];
 
         for (int i = 0; i < chunk.length; i++)
@@ -246,6 +257,8 @@ public abstract class IgfsAbstractSelfTest extends IgfsCommonAbstractTest {
 
         discoSpi.setIpFinder(new TcpDiscoveryVmIpFinder(true));
 
+        prepareCacheConfigurations(dataCacheCfg, metaCacheCfg);
+
         cfg.setDiscoverySpi(discoSpi);
         cfg.setCacheConfiguration(dataCacheCfg, metaCacheCfg);
         cfg.setFileSystemConfiguration(igfsCfg);
@@ -257,6 +270,15 @@ public abstract class IgfsAbstractSelfTest extends IgfsCommonAbstractTest {
     }
 
     /**
+     *
+     * @param dataCacheCfg
+     * @param metaCacheCfg
+     */
+    protected void prepareCacheConfigurations(CacheConfiguration dataCacheCfg, CacheConfiguration metaCacheCfg) {
+        // Noop
+    }
+
+    /**
      * Execute provided task in a separate thread.
      *
      * @param task Task to execute.
@@ -2263,7 +2285,7 @@ public abstract class IgfsAbstractSelfTest extends IgfsCommonAbstractTest {
      * @param chunks Data chunks.
      * @throws Exception If failed.
      */
-    protected void createFile(IgfsImpl igfs, IgfsPath file, boolean overwrite, long blockSize,
+    protected static void createFile(IgfsImpl igfs, IgfsPath file, boolean overwrite, long blockSize,
         @Nullable byte[]... chunks) throws Exception {
         IgfsOutputStream os = null;
 
@@ -2287,7 +2309,7 @@ public abstract class IgfsAbstractSelfTest extends IgfsCommonAbstractTest {
      * @param chunks Data chunks.
      * @throws Exception If failed.
      */
-    protected void appendFile(IgfsImpl igfs, IgfsPath file, @Nullable byte[]... chunks)
+    protected static void appendFile(IgfsImpl igfs, IgfsPath file, @Nullable byte[]... chunks)
         throws Exception {
         IgfsOutputStream os = null;
 
@@ -2354,7 +2376,7 @@ public abstract class IgfsAbstractSelfTest extends IgfsCommonAbstractTest {
      * @param paths Paths.
      * @throws IgniteCheckedException If failed.
      */
-    protected void checkExist(IgfsImpl igfs, IgfsPath... paths) throws IgniteCheckedException {
+    protected static void checkExist(IgfsImpl igfs, IgfsPath... paths) throws IgniteCheckedException {
         for (IgfsPath path : paths) {
             assert igfs.context().meta().fileId(path) != null : "Path doesn't exist [igfs=" + igfs.name() +
                 ", path=" + path + ']';
@@ -2463,7 +2485,7 @@ public abstract class IgfsAbstractSelfTest extends IgfsCommonAbstractTest {
      * @throws IOException In case of IO exception.
      * @throws IgniteCheckedException In case of Grid exception.
      */
-    protected void checkFileContent(IgfsImpl igfs, IgfsPath file, @Nullable byte[]... chunks)
+    protected static void checkFileContent(IgfsImpl igfs, IgfsPath file, @Nullable byte[]... chunks)
         throws IOException, IgniteCheckedException {
         if (chunks != null && chunks.length > 0) {
             IgfsInputStream is = null;
@@ -2562,7 +2584,7 @@ public abstract class IgfsAbstractSelfTest extends IgfsCommonAbstractTest {
      * @param paths Paths to group.
      * @return Paths as array.
      */
-    protected IgfsPath[] paths(IgfsPath... paths) {
+    protected static IgfsPath[] paths(IgfsPath... paths) {
         return paths;
     }
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/28d64d53/modules/core/src/test/java/org/apache/ignite/internal/processors/igfs/IgfsBackupFailoverSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/igfs/IgfsBackupFailoverSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/igfs/IgfsBackupFailoverSelfTest.java
new file mode 100644
index 0000000..0162121
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/igfs/IgfsBackupFailoverSelfTest.java
@@ -0,0 +1,488 @@
+/*
+ * 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.igfs;
+
+import org.apache.ignite.*;
+import org.apache.ignite.cache.*;
+import org.apache.ignite.configuration.*;
+import org.apache.ignite.igfs.*;
+import org.apache.ignite.igfs.secondary.*;
+import org.apache.ignite.internal.util.typedef.*;
+import org.apache.ignite.internal.util.typedef.internal.*;
+import org.apache.ignite.testframework.*;
+import org.jetbrains.annotations.*;
+
+import java.io.*;
+import java.util.*;
+import java.util.concurrent.*;
+import java.util.concurrent.atomic.*;
+
+import static org.apache.ignite.cache.CacheAtomicityMode.*;
+import static org.apache.ignite.cache.CacheMode.*;
+import static org.apache.ignite.internal.processors.igfs.IgfsAbstractSelfTest.*;
+
+/**
+ * Tests IGFS behavioral guarantees if some nodes on the cluster are synchronously or asynchronously stopped.
+ * The operations to check are read, write or both.
+ */
+public class IgfsBackupFailoverSelfTest extends IgfsCommonAbstractTest {
+    /** Directory. */
+    protected static final IgfsPath DIR = new IgfsPath("/dir");
+
+    /** Sub-directory. */
+    protected static final IgfsPath SUBDIR = new IgfsPath(DIR, "subdir");
+
+    /** Number of Ignite nodes used in failover tests. */
+    protected final int numIgfsNodes = 5;
+
+    /** Number of backup copies of data (aka replication). */
+    protected final int numBackups = numIgfsNodes - 1;
+
+    /** */
+    private final int fileSize = 16 * 1024;
+
+    /** */
+    private final int files = 500;
+
+    /** File block size. Use Very small blocks to ensure uniform data distribution among the nodes.. */
+    protected int igfsBlockSize = 31;
+
+    /** Affinity group size (see IgfsGroupDataBlocksKeyMapper). */
+    protected int affGrpSize = 1;
+
+    /** IGFS mode. */
+    protected IgfsMode igfsMode = IgfsMode.PRIMARY;
+
+    /** Node data structures. */
+    protected NodeFsData[] nodeDatas;
+
+    /**
+     * Structure to hold Ignite IGFS node data.
+     */
+    static class NodeFsData {
+        /**  */
+        int idx;
+
+        /**  */
+        Ignite ignite;
+
+        /**  */
+        IgfsImpl igfsImpl;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void beforeTest() throws Exception {
+        super.beforeTest();
+
+        nodeDatas = new NodeFsData[numIgfsNodes];
+
+        for (int i = 0; i<numIgfsNodes; i++) {
+            NodeFsData data = new NodeFsData();
+
+            data.idx = i;
+
+            data.ignite = startGridWithIgfs(getTestGridName(i), igfsMode, null);
+
+            data.igfsImpl = (IgfsImpl) data.ignite.fileSystem("igfs");
+
+            nodeDatas[i] = data;
+        }
+
+        // Ensure all the nodes are started and discovered each other:
+        checkTopology(numIgfsNodes);
+    }
+
+    /**
+     * Creates IPC configuration.
+     *
+     * @param port The port to use.
+     * @return The endpoint configuration.
+     */
+    protected IgfsIpcEndpointConfiguration createIgfsRestConfig(int port) {
+        IgfsIpcEndpointConfiguration cfg = new IgfsIpcEndpointConfiguration();
+
+        cfg.setType(IgfsIpcEndpointType.TCP);
+        cfg.setPort(port);
+
+        return cfg;
+    }
+
+    /**
+     * Start grid with IGFS.
+     *
+     * @param gridName Grid name.
+     * @param mode IGFS mode.
+     * @param secondaryFs Secondary file system (optional).
+     * @return Started grid instance.
+     * @throws Exception If failed.
+     */
+    protected Ignite startGridWithIgfs(String gridName, IgfsMode mode, @Nullable IgfsSecondaryFileSystem secondaryFs)
+        throws Exception {
+        final FileSystemConfiguration igfsCfg = new FileSystemConfiguration();
+
+        igfsCfg.setDataCacheName("dataCache");
+        igfsCfg.setMetaCacheName("metaCache");
+        igfsCfg.setName("igfs");
+        igfsCfg.setBlockSize(igfsBlockSize);
+        igfsCfg.setDefaultMode(mode);
+        igfsCfg.setSecondaryFileSystem(secondaryFs);
+
+        CacheConfiguration<?,?> dataCacheCfg = defaultCacheConfiguration();
+
+        dataCacheCfg.setName("dataCache");
+        dataCacheCfg.setCacheMode(PARTITIONED);
+        dataCacheCfg.setWriteSynchronizationMode(CacheWriteSynchronizationMode.FULL_SYNC);
+        dataCacheCfg.setAffinityMapper(new IgfsGroupDataBlocksKeyMapper(affGrpSize));
+        dataCacheCfg.setBackups(numBackups);
+        dataCacheCfg.setAtomicityMode(TRANSACTIONAL);
+
+        CacheConfiguration metaCacheCfg = defaultCacheConfiguration();
+
+        metaCacheCfg.setName("metaCache");
+        metaCacheCfg.setCacheMode(REPLICATED);
+        metaCacheCfg.setWriteSynchronizationMode(CacheWriteSynchronizationMode.FULL_SYNC);
+        metaCacheCfg.setAtomicityMode(TRANSACTIONAL);
+
+        IgniteConfiguration cfg = new IgniteConfiguration();
+
+        cfg.setGridName(gridName);
+
+        cfg.setCacheConfiguration(dataCacheCfg, metaCacheCfg);
+        cfg.setFileSystemConfiguration(igfsCfg);
+
+        cfg.setLocalHost("127.0.0.1");
+
+        return startGrid(gridName, cfg);
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void afterTest() throws Exception {
+        super.afterTest();
+
+        G.stopAll(false);
+
+        Arrays.fill(nodeDatas, null);
+    }
+
+    /**
+     * Creates a chunk of data.
+     *
+     * @param len The chunk length
+     * @param j index to scramble into the data.
+     * @return The chunk.
+     */
+    static byte[] createChunk(int len, int j) {
+        byte[] bb = new byte[len];
+
+        for (int i = 0; i < bb.length; i++)
+            bb[i] = (byte)(i ^ j);
+
+        return bb;
+    }
+
+    /**
+     * Composes the path of the file.
+     */
+    private IgfsPath filePath(int j) {
+        return new IgfsPath(SUBDIR, "file" + j);
+    }
+
+    /**
+     * Checks correct data read *after* N-1 nodes are stopped.
+     *
+     * @throws Exception On error.
+     */
+    public void testReadFailoverAfterStopMultipleNodes() throws Exception {
+        final IgfsImpl igfs0 = nodeDatas[0].igfsImpl;
+
+        clear(igfs0);
+
+        IgfsAbstractSelfTest.create(igfs0, paths(DIR, SUBDIR), null);
+
+        // Create files through the 0th node:
+        for (int f=0; f<files; f++) {
+            final byte[] data = createChunk(fileSize, f);
+
+            createFile(igfs0, filePath(f), true, -1/*block size unused*/, data);
+        }
+
+        // Check files:
+        for (int f=0; f<files; f++) {
+            IgfsPath path = filePath(f);
+            byte[] data = createChunk(fileSize, f);
+
+            // Check through 0th node:
+            checkExist(igfs0, path);
+
+            checkFileContent(igfs0, path, data);
+
+            // Check the same file through other nodes:
+            for (int n=1; n<numIgfsNodes; n++) {
+                checkExist(nodeDatas[n].igfsImpl, path);
+
+                checkFileContent(nodeDatas[n].igfsImpl, path, data);
+            }
+        }
+
+        // Now stop all the nodes but the 1st:
+        for (int n=1; n<numIgfsNodes; n++)
+            stopGrid(n);
+
+        // Check files again:
+        for (int f=0; f<files; f++) {
+            IgfsPath path = filePath(f);
+
+            byte[] data = createChunk(fileSize, f);
+
+            // Check through 0th node:
+            checkExist(igfs0, path);
+
+            checkFileContent(igfs0, path, data);
+        }
+    }
+
+    /**
+     * Checks correct data read *while* N-1 nodes are being concurrently stopped.
+     *
+     * @throws Exception On error.
+     */
+    public void testReadFailoverWhileStoppingMultipleNodes() throws Exception {
+        final IgfsImpl igfs0 = nodeDatas[0].igfsImpl;
+
+        clear(igfs0);
+
+        IgfsAbstractSelfTest.create(igfs0, paths(DIR, SUBDIR), null);
+
+        // Create files:
+        for (int f = 0; f < files; f++) {
+            final byte[] data = createChunk(fileSize, f);
+
+            createFile(igfs0, filePath(f), true, -1/*block size unused*/, data);
+        }
+
+        // Check files:
+        for (int f = 0; f < files; f++) {
+            IgfsPath path = filePath(f);
+            byte[] data = createChunk(fileSize, f);
+
+            // Check through 1st node:
+            checkExist(igfs0, path);
+
+            checkFileContent(igfs0, path, data);
+
+            // Check the same file through other nodes:
+            for (int n = 1; n < numIgfsNodes; n++) {
+                checkExist(nodeDatas[n].igfsImpl, path);
+
+                checkFileContent(nodeDatas[n].igfsImpl, path, data);
+            }
+        }
+
+        final AtomicBoolean stop = new AtomicBoolean();
+
+        GridTestUtils.runMultiThreadedAsync(new Callable() {
+            @Override
+            public Object call() throws Exception {
+                Thread.sleep(1_000); // Some delay to ensure read is in progress.
+
+                // Now stop all the nodes but the 1st:
+                for (int n = 1; n < numIgfsNodes; n++) {
+                    stopGrid(n);
+
+                    X.println("grid " + n + " stopped.");
+                }
+
+                Thread.sleep(1_000);
+
+                stop.set(true);
+
+                return null;
+            }
+        }, 1, "igfs-node-stopper");
+
+        // Read the files repeatedly, while the nodes are being stopped:
+        while (!stop.get()) {
+            // Check files while the nodes are being stopped:
+            for (int f = 0; f < files; f++) {
+                IgfsPath path = filePath(f);
+
+                byte[] data = createChunk(fileSize, f);
+
+                // Check through 1st node:
+                checkExist(igfs0, path);
+
+                checkFileContent(igfs0, path, data);
+            }
+        }
+    }
+
+    /**
+     * Checks possibility to append the data to files *after* N-1 nodes are stopped.
+     * First, some data written to files.
+     * After that N-1 nodes are stopped.
+     * Then data are attempted to append to the streams opened before the nodes stop.
+     * If failed, the streams are attempted to reopen and the files are attempted to append.
+     * After that the read operation is performed to check data correctness.
+     *
+     * The test is temporarily disabled due to issues .... .
+     *
+     * @throws Exception On error.
+     */
+    public void testWriteFailoverAfterStopMultipleNodes() throws Exception {
+        final IgfsImpl igfs0 = nodeDatas[0].igfsImpl;
+
+        clear(igfs0);
+
+        IgfsAbstractSelfTest.create(igfs0, paths(DIR, SUBDIR), null);
+
+        final IgfsOutputStream[] outStreams = new IgfsOutputStream[files];
+
+        // Create files:
+        for (int f = 0; f < files; f++) {
+            final byte[] data = createChunk(fileSize, f);
+
+            IgfsOutputStream os = null;
+
+            try {
+                os = igfs0.create(filePath(f), 256, true, null, 0, -1, null);
+
+                assert os != null;
+
+                writeFileChunks(os, data);
+            }
+            finally {
+                if (os != null)
+                    os.flush();
+            }
+
+            outStreams[f] = os;
+
+            X.println("write #1 completed: " + f);
+        }
+
+        // Now stop all the nodes but the 1st:
+        for (int n = 1; n < numIgfsNodes; n++) {
+            stopGrid(n);
+
+            X.println("#### grid " + n + " stopped.");
+        }
+
+        // Create files:
+        for (int f0 = 0; f0 < files; f0++) {
+            final IgfsOutputStream os = outStreams[f0];
+
+            assert os != null;
+
+            final int f = f0;
+
+            int att = doWithRetries(2, new Callable<Void>() {
+                @Override public Void call() throws Exception {
+                    IgfsOutputStream ios = os;
+
+                    try {
+                        writeChunks0(igfs0, ios, f);
+                    }
+                    catch (IOException ioe) {
+                        log().warning("Attempt to append the data to existing stream failed: ", ioe);
+
+                        ios = igfs0.append(filePath(f), false);
+
+                        assert ios != null;
+
+                        writeChunks0(igfs0, ios, f);
+                    }
+
+                    return null;
+                }
+            });
+
+            X.println("write #2 completed: " + f0 + " in " + att + " attempts.");
+        }
+
+        // Check files:
+        for (int f = 0; f < files; f++) {
+            IgfsPath path = filePath(f);
+
+            byte[] data = createChunk(fileSize, f);
+
+            // Check through 1st node:
+            checkExist(igfs0, path);
+
+            assertEquals("File length mismatch.", data.length * 2, igfs0.size(path));
+
+            checkFileContent(igfs0, path, data, data);
+
+            X.println("Read test completed: " + f);
+        }
+    }
+
+    /**
+     * Writes data to the file of the specified index and closes the output stream.
+     *
+     * @param igfs0 IGFS.
+     * @param ios The output stream
+     * @param fileIdx Th eindex of the file.
+     * @throws IOException On error.
+     */
+    void writeChunks0(IgfsEx igfs0, IgfsOutputStream ios, int fileIdx) throws IOException {
+        try {
+            byte[] data = createChunk(fileSize, fileIdx);
+
+            writeFileChunks(ios, data);
+        }
+        finally {
+            ios.flush();
+
+            U.closeQuiet(ios);
+
+            awaitFileClose(igfs0.asSecondary(), filePath(fileIdx));
+        }
+    }
+
+    /**
+     * Performs an operation with retries.
+     *
+     * @param attempts The maximum number of attempts.
+     * @param clo The closure to execute.
+     * @throws Exception On error.
+     */
+    protected static int doWithRetries(int attempts, Callable<Void> clo) throws Exception {
+        int attemptCnt = 0;
+
+        while (true) {
+            try {
+                attemptCnt++;
+
+                clo.call();
+
+                return attemptCnt;
+            }
+            catch (Exception e) {
+                if (attemptCnt >= attempts)
+                    throw e;
+                else
+                    X.println("Failed to execute closure in " + attempts + " attempts.");
+            }
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override protected long getTestTimeout() {
+        return 20 * 60 * 1000;
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/28d64d53/modules/core/src/test/java/org/apache/ignite/internal/processors/igfs/IgfsBackupsDualAsyncSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/igfs/IgfsBackupsDualAsyncSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/igfs/IgfsBackupsDualAsyncSelfTest.java
new file mode 100644
index 0000000..3c042d6
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/igfs/IgfsBackupsDualAsyncSelfTest.java
@@ -0,0 +1,40 @@
+/*
+ * 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.igfs;
+
+import org.apache.ignite.configuration.*;
+
+import static org.apache.ignite.igfs.IgfsMode.*;
+
+/**
+ * Tests for DUAL_ASYNC mode.
+ */
+public class IgfsBackupsDualAsyncSelfTest extends IgfsDualAbstractSelfTest {
+    /**
+     * Constructor.
+     */
+    public IgfsBackupsDualAsyncSelfTest() {
+        super(DUAL_ASYNC);
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void prepareCacheConfigurations(CacheConfiguration dataCacheCfg,
+        CacheConfiguration metaCacheCfg) {
+        dataCacheCfg.setBackups(1);
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/28d64d53/modules/core/src/test/java/org/apache/ignite/internal/processors/igfs/IgfsBackupsDualSyncSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/igfs/IgfsBackupsDualSyncSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/igfs/IgfsBackupsDualSyncSelfTest.java
new file mode 100644
index 0000000..5d7fdaf
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/igfs/IgfsBackupsDualSyncSelfTest.java
@@ -0,0 +1,40 @@
+/*
+ * 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.igfs;
+
+import org.apache.ignite.configuration.*;
+
+import static org.apache.ignite.igfs.IgfsMode.*;
+
+/**
+ * Tests for DUAL_SYNC mode.
+ */
+public class IgfsBackupsDualSyncSelfTest extends IgfsDualAbstractSelfTest {
+    /**
+     * Constructor.
+     */
+    public IgfsBackupsDualSyncSelfTest() {
+        super(DUAL_SYNC);
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void prepareCacheConfigurations(CacheConfiguration dataCacheCfg,
+        CacheConfiguration metaCacheCfg) {
+        dataCacheCfg.setBackups(1);
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/28d64d53/modules/core/src/test/java/org/apache/ignite/internal/processors/igfs/IgfsBackupsPrimarySelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/igfs/IgfsBackupsPrimarySelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/igfs/IgfsBackupsPrimarySelfTest.java
new file mode 100644
index 0000000..c4958a8
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/igfs/IgfsBackupsPrimarySelfTest.java
@@ -0,0 +1,40 @@
+/*
+ * 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.igfs;
+
+import org.apache.ignite.configuration.*;
+
+import static org.apache.ignite.igfs.IgfsMode.*;
+
+/**
+ * Tests for PRIMARY mode.
+ */
+public class IgfsBackupsPrimarySelfTest extends IgfsAbstractSelfTest {
+    /**
+     * Constructor.
+     */
+    public IgfsBackupsPrimarySelfTest() {
+        super(PRIMARY);
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void prepareCacheConfigurations(CacheConfiguration dataCacheCfg,
+            CacheConfiguration metaCacheCfg) {
+        dataCacheCfg.setBackups(1);
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/28d64d53/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteIgfsTestSuite.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteIgfsTestSuite.java b/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteIgfsTestSuite.java
index f8dac3d..73e6a03 100644
--- a/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteIgfsTestSuite.java
+++ b/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteIgfsTestSuite.java
@@ -79,6 +79,13 @@ public class IgniteIgfsTestSuite extends TestSuite {
 
         suite.addTestSuite(IgfsStartCacheTest.class);
 
+        suite.addTestSuite(IgfsBackupsPrimarySelfTest.class);
+        suite.addTestSuite(IgfsBackupsDualSyncSelfTest.class);
+        suite.addTestSuite(IgfsBackupsDualAsyncSelfTest.class);
+
+        // TODO: Enable when IGFS failover is fixed.
+        //suite.addTestSuite(IgfsBackupFailoverSelfTest.class);
+
         return suite;
     }
 }


[03/59] [abbrv] ignite git commit: ignite-1258: portable objects API support in Ignite

Posted by vk...@apache.org.
http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/java/org/apache/ignite/internal/portable/GridPortableMetaDataDisabledSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/portable/GridPortableMetaDataDisabledSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/portable/GridPortableMetaDataDisabledSelfTest.java
new file mode 100644
index 0000000..47db42b
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/portable/GridPortableMetaDataDisabledSelfTest.java
@@ -0,0 +1,218 @@
+/*
+ * 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.portable;
+
+import org.apache.ignite.*;
+import org.apache.ignite.configuration.*;
+import org.apache.ignite.marshaller.portable.*;
+import org.apache.ignite.portable.*;
+import org.apache.ignite.testframework.junits.common.*;
+
+import java.util.*;
+
+/**
+ * Test for disabled meta data.
+ */
+public class GridPortableMetaDataDisabledSelfTest extends GridCommonAbstractTest {
+    /** */
+    private PortableMarshaller marsh;
+
+    /** {@inheritDoc} */
+    @Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception {
+        IgniteConfiguration cfg = super.getConfiguration(gridName);
+
+        cfg.setMarshaller(marsh);
+
+        return cfg;
+    }
+
+    /**
+     * @return Portables.
+     */
+    private IgnitePortables portables() {
+        return grid().portables();
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testDisableGlobal() throws Exception {
+        marsh = new PortableMarshaller();
+
+        marsh.setClassNames(Arrays.asList(
+            TestObject1.class.getName(),
+            TestObject2.class.getName()
+        ));
+
+        marsh.setMetaDataEnabled(false);
+
+        try {
+            startGrid();
+
+            portables().toPortable(new TestObject1());
+            portables().toPortable(new TestObject2());
+
+            assertEquals(0, portables().metadata(TestObject1.class).fields().size());
+            assertEquals(0, portables().metadata(TestObject2.class).fields().size());
+        }
+        finally {
+            stopGrid();
+        }
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testDisableGlobalSimpleClass() throws Exception {
+        marsh = new PortableMarshaller();
+
+        PortableTypeConfiguration typeCfg = new PortableTypeConfiguration(TestObject2.class.getName());
+
+        typeCfg.setMetaDataEnabled(true);
+
+        marsh.setTypeConfigurations(Arrays.asList(
+            new PortableTypeConfiguration(TestObject1.class.getName()),
+            typeCfg
+        ));
+
+        marsh.setMetaDataEnabled(false);
+
+        try {
+            startGrid();
+
+            portables().toPortable(new TestObject1());
+            portables().toPortable(new TestObject2());
+
+            assertEquals(0, portables().metadata(TestObject1.class).fields().size());
+            assertEquals(1, portables().metadata(TestObject2.class).fields().size());
+        }
+        finally {
+            stopGrid();
+        }
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testDisableGlobalMarshalAwareClass() throws Exception {
+        marsh = new PortableMarshaller();
+
+        PortableTypeConfiguration typeCfg = new PortableTypeConfiguration(TestObject1.class.getName());
+
+        typeCfg.setMetaDataEnabled(true);
+
+        marsh.setTypeConfigurations(Arrays.asList(
+            new PortableTypeConfiguration(TestObject2.class.getName()),
+            typeCfg
+        ));
+
+        marsh.setMetaDataEnabled(false);
+
+        try {
+            startGrid();
+
+            portables().toPortable(new TestObject1());
+            portables().toPortable(new TestObject2());
+
+            assertEquals(1, portables().metadata(TestObject1.class).fields().size());
+            assertEquals(0, portables().metadata(TestObject2.class).fields().size());
+        }
+        finally {
+            stopGrid();
+        }
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testDisableSimpleClass() throws Exception {
+        marsh = new PortableMarshaller();
+
+        PortableTypeConfiguration typeCfg = new PortableTypeConfiguration(TestObject1.class.getName());
+
+        typeCfg.setMetaDataEnabled(false);
+
+        marsh.setTypeConfigurations(Arrays.asList(
+            new PortableTypeConfiguration(TestObject2.class.getName()),
+            typeCfg
+        ));
+
+        try {
+            startGrid();
+
+            portables().toPortable(new TestObject1());
+            portables().toPortable(new TestObject2());
+
+            assertEquals(0, portables().metadata(TestObject1.class).fields().size());
+            assertEquals(1, portables().metadata(TestObject2.class).fields().size());
+        }
+        finally {
+            stopGrid();
+        }
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testDisableMarshalAwareClass() throws Exception {
+        marsh = new PortableMarshaller();
+
+        PortableTypeConfiguration typeCfg = new PortableTypeConfiguration(TestObject2.class.getName());
+
+        typeCfg.setMetaDataEnabled(false);
+
+        marsh.setTypeConfigurations(Arrays.asList(
+            new PortableTypeConfiguration(TestObject1.class.getName()),
+            typeCfg
+        ));
+
+        try {
+            startGrid();
+
+            portables().toPortable(new TestObject1());
+            portables().toPortable(new TestObject2());
+
+            assertEquals(1, portables().metadata(TestObject1.class).fields().size());
+            assertEquals(0, portables().metadata(TestObject2.class).fields().size());
+        }
+        finally {
+            stopGrid();
+        }
+    }
+
+    /**
+     */
+    @SuppressWarnings("UnusedDeclaration")
+    private static class TestObject1 {
+        /** */
+        private int field;
+    }
+
+    /**
+     */
+    private static class TestObject2 implements PortableMarshalAware {
+        /** {@inheritDoc} */
+        @Override public void writePortable(PortableWriter writer) throws PortableException {
+            writer.writeInt("field", 1);
+        }
+
+        /** {@inheritDoc} */
+        @Override public void readPortable(PortableReader reader) throws PortableException {
+            // No-op.
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/java/org/apache/ignite/internal/portable/GridPortableMetaDataSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/portable/GridPortableMetaDataSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/portable/GridPortableMetaDataSelfTest.java
new file mode 100644
index 0000000..e5ca91e
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/portable/GridPortableMetaDataSelfTest.java
@@ -0,0 +1,343 @@
+/*
+ * 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.portable;
+
+import org.apache.ignite.*;
+import org.apache.ignite.configuration.*;
+import org.apache.ignite.marshaller.portable.*;
+import org.apache.ignite.portable.*;
+import org.apache.ignite.testframework.junits.common.*;
+
+import java.math.*;
+import java.util.*;
+
+/**
+ * Portable meta data test.
+ */
+public class GridPortableMetaDataSelfTest extends GridCommonAbstractTest {
+    /** */
+    private static int idx;
+
+    /** {@inheritDoc} */
+    @Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception {
+        IgniteConfiguration cfg = super.getConfiguration(gridName);
+
+        PortableMarshaller marsh = new PortableMarshaller();
+
+        marsh.setClassNames(Arrays.asList(TestObject1.class.getName(), TestObject2.class.getName()));
+
+        cfg.setMarshaller(marsh);
+
+        CacheConfiguration ccfg = new CacheConfiguration();
+
+        cfg.setCacheConfiguration(ccfg);
+
+        return cfg;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void beforeTest() throws Exception {
+        idx = 0;
+
+        startGrid();
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void afterTest() throws Exception {
+        stopGrid();
+    }
+
+    /**
+     * @return Portables API.
+     */
+    protected IgnitePortables portables() {
+        return grid().portables();
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testGetAll() throws Exception {
+        portables().toPortable(new TestObject2());
+
+        Collection<PortableMetadata> metas = portables().metadata();
+
+        assertEquals(2, metas.size());
+
+        for (PortableMetadata meta : metas) {
+            Collection<String> fields;
+
+            switch (meta.typeName()) {
+                case "TestObject1":
+                    fields = meta.fields();
+
+                    assertEquals(7, fields.size());
+
+                    assertTrue(fields.contains("intVal"));
+                    assertTrue(fields.contains("strVal"));
+                    assertTrue(fields.contains("arrVal"));
+                    assertTrue(fields.contains("obj1Val"));
+                    assertTrue(fields.contains("obj2Val"));
+                    assertTrue(fields.contains("decVal"));
+                    assertTrue(fields.contains("decArrVal"));
+
+                    assertEquals("int", meta.fieldTypeName("intVal"));
+                    assertEquals("String", meta.fieldTypeName("strVal"));
+                    assertEquals("byte[]", meta.fieldTypeName("arrVal"));
+                    assertEquals("Object", meta.fieldTypeName("obj1Val"));
+                    assertEquals("Object", meta.fieldTypeName("obj2Val"));
+                    assertEquals("decimal", meta.fieldTypeName("decVal"));
+                    assertEquals("decimal[]", meta.fieldTypeName("decArrVal"));
+
+                    break;
+
+                case "TestObject2":
+                    fields = meta.fields();
+
+                    assertEquals(7, fields.size());
+
+                    assertTrue(fields.contains("boolVal"));
+                    assertTrue(fields.contains("dateVal"));
+                    assertTrue(fields.contains("uuidArrVal"));
+                    assertTrue(fields.contains("objVal"));
+                    assertTrue(fields.contains("mapVal"));
+                    assertTrue(fields.contains("decVal"));
+                    assertTrue(fields.contains("decArrVal"));
+
+                    assertEquals("boolean", meta.fieldTypeName("boolVal"));
+                    assertEquals("Date", meta.fieldTypeName("dateVal"));
+                    assertEquals("UUID[]", meta.fieldTypeName("uuidArrVal"));
+                    assertEquals("Object", meta.fieldTypeName("objVal"));
+                    assertEquals("Map", meta.fieldTypeName("mapVal"));
+                    assertEquals("decimal", meta.fieldTypeName("decVal"));
+                    assertEquals("decimal[]", meta.fieldTypeName("decArrVal"));
+
+                    break;
+
+                default:
+                    assert false : meta.typeName();
+            }
+        }
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testReflection() throws Exception {
+        PortableMetadata meta = portables().metadata(TestObject1.class);
+
+        assertNotNull(meta);
+
+        assertEquals("TestObject1", meta.typeName());
+
+        Collection<String> fields = meta.fields();
+
+        assertEquals(7, fields.size());
+
+        assertTrue(fields.contains("intVal"));
+        assertTrue(fields.contains("strVal"));
+        assertTrue(fields.contains("arrVal"));
+        assertTrue(fields.contains("obj1Val"));
+        assertTrue(fields.contains("obj2Val"));
+        assertTrue(fields.contains("decVal"));
+        assertTrue(fields.contains("decArrVal"));
+
+        assertEquals("int", meta.fieldTypeName("intVal"));
+        assertEquals("String", meta.fieldTypeName("strVal"));
+        assertEquals("byte[]", meta.fieldTypeName("arrVal"));
+        assertEquals("Object", meta.fieldTypeName("obj1Val"));
+        assertEquals("Object", meta.fieldTypeName("obj2Val"));
+        assertEquals("decimal", meta.fieldTypeName("decVal"));
+        assertEquals("decimal[]", meta.fieldTypeName("decArrVal"));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testPortableMarshalAware() throws Exception {
+        portables().toPortable(new TestObject2());
+
+        PortableMetadata meta = portables().metadata(TestObject2.class);
+
+        assertNotNull(meta);
+
+        assertEquals("TestObject2", meta.typeName());
+
+        Collection<String> fields = meta.fields();
+
+        assertEquals(7, fields.size());
+
+        assertTrue(fields.contains("boolVal"));
+        assertTrue(fields.contains("dateVal"));
+        assertTrue(fields.contains("uuidArrVal"));
+        assertTrue(fields.contains("objVal"));
+        assertTrue(fields.contains("mapVal"));
+        assertTrue(fields.contains("decVal"));
+        assertTrue(fields.contains("decArrVal"));
+
+        assertEquals("boolean", meta.fieldTypeName("boolVal"));
+        assertEquals("Date", meta.fieldTypeName("dateVal"));
+        assertEquals("UUID[]", meta.fieldTypeName("uuidArrVal"));
+        assertEquals("Object", meta.fieldTypeName("objVal"));
+        assertEquals("Map", meta.fieldTypeName("mapVal"));
+        assertEquals("decimal", meta.fieldTypeName("decVal"));
+        assertEquals("decimal[]", meta.fieldTypeName("decArrVal"));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testMerge() throws Exception {
+        portables().toPortable(new TestObject2());
+
+        idx = 1;
+
+        portables().toPortable(new TestObject2());
+
+        PortableMetadata meta = portables().metadata(TestObject2.class);
+
+        assertNotNull(meta);
+
+        assertEquals("TestObject2", meta.typeName());
+
+        Collection<String> fields = meta.fields();
+
+        assertEquals(9, fields.size());
+
+        assertTrue(fields.contains("boolVal"));
+        assertTrue(fields.contains("dateVal"));
+        assertTrue(fields.contains("uuidArrVal"));
+        assertTrue(fields.contains("objVal"));
+        assertTrue(fields.contains("mapVal"));
+        assertTrue(fields.contains("charVal"));
+        assertTrue(fields.contains("colVal"));
+        assertTrue(fields.contains("decVal"));
+        assertTrue(fields.contains("decArrVal"));
+
+        assertEquals("boolean", meta.fieldTypeName("boolVal"));
+        assertEquals("Date", meta.fieldTypeName("dateVal"));
+        assertEquals("UUID[]", meta.fieldTypeName("uuidArrVal"));
+        assertEquals("Object", meta.fieldTypeName("objVal"));
+        assertEquals("Map", meta.fieldTypeName("mapVal"));
+        assertEquals("char", meta.fieldTypeName("charVal"));
+        assertEquals("Collection", meta.fieldTypeName("colVal"));
+        assertEquals("decimal", meta.fieldTypeName("decVal"));
+        assertEquals("decimal[]", meta.fieldTypeName("decArrVal"));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testSerializedObject() throws Exception {
+        TestObject1 obj = new TestObject1();
+
+        obj.intVal = 10;
+        obj.strVal = "str";
+        obj.arrVal = new byte[] {2, 4, 6};
+        obj.obj1Val = null;
+        obj.obj2Val = new TestObject2();
+        obj.decVal = BigDecimal.ZERO;
+        obj.decArrVal = new BigDecimal[] { BigDecimal.ONE };
+
+        PortableObject po = portables().toPortable(obj);
+
+        info(po.toString());
+
+        PortableMetadata meta = po.metaData();
+
+        assertNotNull(meta);
+
+        assertEquals("TestObject1", meta.typeName());
+
+        Collection<String> fields = meta.fields();
+
+        assertEquals(7, fields.size());
+
+        assertTrue(fields.contains("intVal"));
+        assertTrue(fields.contains("strVal"));
+        assertTrue(fields.contains("arrVal"));
+        assertTrue(fields.contains("obj1Val"));
+        assertTrue(fields.contains("obj2Val"));
+        assertTrue(fields.contains("decVal"));
+        assertTrue(fields.contains("decArrVal"));
+
+        assertEquals("int", meta.fieldTypeName("intVal"));
+        assertEquals("String", meta.fieldTypeName("strVal"));
+        assertEquals("byte[]", meta.fieldTypeName("arrVal"));
+        assertEquals("Object", meta.fieldTypeName("obj1Val"));
+        assertEquals("Object", meta.fieldTypeName("obj2Val"));
+        assertEquals("decimal", meta.fieldTypeName("decVal"));
+        assertEquals("decimal[]", meta.fieldTypeName("decArrVal"));
+    }
+
+    /**
+     */
+    @SuppressWarnings("UnusedDeclaration")
+    private static class TestObject1 {
+        /** */
+        private int intVal;
+
+        /** */
+        private String strVal;
+
+        /** */
+        private byte[] arrVal;
+
+        /** */
+        private TestObject1 obj1Val;
+
+        /** */
+        private TestObject2 obj2Val;
+
+        /** */
+        private BigDecimal decVal;
+
+        /** */
+        private BigDecimal[] decArrVal;
+    }
+
+    /**
+     */
+    private static class TestObject2 implements PortableMarshalAware {
+        /** {@inheritDoc} */
+        @Override public void writePortable(PortableWriter writer) throws PortableException {
+            writer.writeBoolean("boolVal", false);
+            writer.writeDate("dateVal", new Date());
+            writer.writeUuidArray("uuidArrVal", null);
+            writer.writeObject("objVal", null);
+            writer.writeMap("mapVal", new HashMap<>());
+            writer.writeDecimal("decVal", BigDecimal.ZERO);
+            writer.writeDecimalArray("decArrVal", new BigDecimal[] { BigDecimal.ONE });
+
+            if (idx == 1) {
+                writer.writeChar("charVal", (char)0);
+                writer.writeCollection("colVal", null);
+            }
+
+            PortableRawWriter raw = writer.rawWriter();
+
+            raw.writeChar((char)0);
+            raw.writeCollection(null);
+        }
+
+        /** {@inheritDoc} */
+        @Override public void readPortable(PortableReader reader) throws PortableException {
+            // No-op.
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/java/org/apache/ignite/internal/portable/GridPortableWildcardsSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/portable/GridPortableWildcardsSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/portable/GridPortableWildcardsSelfTest.java
new file mode 100644
index 0000000..7e873f3
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/portable/GridPortableWildcardsSelfTest.java
@@ -0,0 +1,480 @@
+/*
+ * 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.portable;
+
+import org.apache.ignite.internal.util.typedef.internal.*;
+import org.apache.ignite.marshaller.*;
+import org.apache.ignite.marshaller.portable.*;
+import org.apache.ignite.portable.*;
+import org.apache.ignite.testframework.junits.common.*;
+
+import java.util.*;
+
+/**
+ * Wildcards test.
+ */
+public class GridPortableWildcardsSelfTest extends GridCommonAbstractTest {
+    /** */
+    private static final PortableMetaDataHandler META_HND = new PortableMetaDataHandler() {
+        @Override public void addMeta(int typeId, PortableMetadata meta) {
+            // No-op.
+        }
+
+        @Override public PortableMetadata metadata(int typeId) {
+            return null;
+        }
+    };
+
+    /**
+     * @return Portable context.
+     */
+    private PortableContext portableContext() {
+        return new PortableContext(META_HND, null);
+    }
+
+    /**
+     * @return Portable marshaller.
+     */
+    private PortableMarshaller portableMarshaller() {
+        PortableMarshaller marsh = new PortableMarshaller();
+        marsh.setContext(new MarshallerContextTestImpl(null));
+
+        return marsh;
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testClassNames() throws Exception {
+        PortableContext ctx = portableContext();
+
+        PortableMarshaller marsh = portableMarshaller();
+
+        marsh.setClassNames(Arrays.asList(
+            "org.apache.ignite.internal.portable.test.*",
+            "unknown.*"
+        ));
+
+        ctx.configure(marsh);
+
+        Map<Integer, Class> typeIds = U.field(ctx, "userTypes");
+
+        assertEquals(3, typeIds.size());
+
+        assertTrue(typeIds.containsKey("gridportabletestclass1".hashCode()));
+        assertTrue(typeIds.containsKey("gridportabletestclass2".hashCode()));
+        assertTrue(typeIds.containsKey("innerclass".hashCode()));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testClassNamesWithMapper() throws Exception {
+        PortableContext ctx = portableContext();
+
+        PortableMarshaller marsh = portableMarshaller();
+
+        marsh.setIdMapper(new PortableIdMapper() {
+            @SuppressWarnings("IfMayBeConditional")
+            @Override public int typeId(String clsName) {
+                if (clsName.endsWith("1"))
+                    return 100;
+                else if (clsName.endsWith("2"))
+                    return 200;
+                else if (clsName.endsWith("InnerClass"))
+                    return 300;
+                else
+                    return -500;
+            }
+
+            @Override public int fieldId(int typeId, String fieldName) {
+                return 0;
+            }
+        });
+
+        marsh.setClassNames(Arrays.asList(
+            "org.apache.ignite.internal.portable.test.*",
+            "unknown.*"
+        ));
+
+        ctx.configure(marsh);
+
+        Map<String, PortableIdMapper> typeMappers = U.field(ctx, "typeMappers");
+
+        assertEquals(3, typeMappers.size());
+
+        assertEquals(100, typeMappers.get("GridPortableTestClass1").typeId("GridPortableTestClass1"));
+        assertEquals(200, typeMappers.get("GridPortableTestClass2").typeId("GridPortableTestClass2"));
+        assertEquals(300, typeMappers.get("InnerClass").typeId("InnerClass"));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testTypeConfigurations() throws Exception {
+        PortableContext ctx = portableContext();
+
+        PortableMarshaller marsh = portableMarshaller();
+
+        marsh.setTypeConfigurations(Arrays.asList(
+            new PortableTypeConfiguration("org.apache.ignite.internal.portable.test.*"),
+            new PortableTypeConfiguration("unknown.*")
+        ));
+
+        ctx.configure(marsh);
+
+        Map<Integer, Class> typeIds = U.field(ctx, "userTypes");
+
+        assertEquals(3, typeIds.size());
+
+        assertTrue(typeIds.containsKey("gridportabletestclass1".hashCode()));
+        assertTrue(typeIds.containsKey("gridportabletestclass2".hashCode()));
+        assertTrue(typeIds.containsKey("innerclass".hashCode()));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testTypeConfigurationsWithGlobalMapper() throws Exception {
+        PortableContext ctx = portableContext();
+
+        PortableMarshaller marsh = portableMarshaller();
+
+        marsh.setIdMapper(new PortableIdMapper() {
+            @SuppressWarnings("IfMayBeConditional")
+            @Override public int typeId(String clsName) {
+                if (clsName.endsWith("1"))
+                    return 100;
+                else if (clsName.endsWith("2"))
+                    return 200;
+                else if (clsName.endsWith("InnerClass"))
+                    return 300;
+                else
+                    return -500;
+            }
+
+            @Override public int fieldId(int typeId, String fieldName) {
+                return 0;
+            }
+        });
+
+        marsh.setTypeConfigurations(Arrays.asList(
+            new PortableTypeConfiguration("org.apache.ignite.internal.portable.test.*"),
+            new PortableTypeConfiguration("unknown.*")
+        ));
+
+        ctx.configure(marsh);
+
+        Map<String, PortableIdMapper> typeMappers = U.field(ctx, "typeMappers");
+
+        assertEquals(3, typeMappers.size());
+
+        assertEquals(100, typeMappers.get("GridPortableTestClass1").typeId("GridPortableTestClass1"));
+        assertEquals(200, typeMappers.get("GridPortableTestClass2").typeId("GridPortableTestClass2"));
+        assertEquals(300, typeMappers.get("InnerClass").typeId("InnerClass"));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testTypeConfigurationsWithNonGlobalMapper() throws Exception {
+        PortableContext ctx = portableContext();
+
+        PortableMarshaller marsh = portableMarshaller();
+
+        marsh.setIdMapper(new PortableIdMapper() {
+            @SuppressWarnings("IfMayBeConditional")
+            @Override public int typeId(String clsName) {
+                if (clsName.endsWith("1"))
+                    return 100;
+                else if (clsName.endsWith("2"))
+                    return 200;
+                else if (clsName.endsWith("InnerClass"))
+                    return 300;
+                else
+                    return -500;
+            }
+
+            @Override public int fieldId(int typeId, String fieldName) {
+                return 0;
+            }
+        });
+
+        marsh.setTypeConfigurations(Arrays.asList(
+            new PortableTypeConfiguration("org.apache.ignite.internal.portable.test.*"),
+            new PortableTypeConfiguration("unknown.*")
+        ));
+
+        ctx.configure(marsh);
+
+        Map<String, PortableIdMapper> typeMappers = U.field(ctx, "typeMappers");
+
+        assertEquals(3, typeMappers.size());
+
+        assertEquals(100, typeMappers.get("GridPortableTestClass1").typeId("GridPortableTestClass1"));
+        assertEquals(200, typeMappers.get("GridPortableTestClass2").typeId("GridPortableTestClass2"));
+        assertEquals(300, typeMappers.get("InnerClass").typeId("InnerClass"));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testOverride() throws Exception {
+        PortableContext ctx = portableContext();
+
+        PortableMarshaller marsh = portableMarshaller();
+
+        marsh.setClassNames(Arrays.asList(
+            "org.apache.ignite.internal.portable.test.*"
+        ));
+
+        PortableTypeConfiguration typeCfg = new PortableTypeConfiguration();
+
+        typeCfg.setClassName("org.apache.ignite.internal.portable.test.GridPortableTestClass2");
+        typeCfg.setIdMapper(new PortableIdMapper() {
+            @Override public int typeId(String clsName) {
+                return 100;
+            }
+
+            @Override public int fieldId(int typeId, String fieldName) {
+                return 0;
+            }
+        });
+
+        marsh.setTypeConfigurations(Arrays.asList(typeCfg));
+
+        ctx.configure(marsh);
+
+        Map<Integer, Class> typeIds = U.field(ctx, "userTypes");
+
+        assertEquals(3, typeIds.size());
+
+        assertTrue(typeIds.containsKey("gridportabletestclass1".hashCode()));
+        assertTrue(typeIds.containsKey("innerclass".hashCode()));
+        assertFalse(typeIds.containsKey("gridportabletestclass2".hashCode()));
+
+        Map<String, PortableIdMapper> typeMappers = U.field(ctx, "typeMappers");
+
+        assertEquals(100, typeMappers.get("GridPortableTestClass2").typeId("GridPortableTestClass2"));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testClassNamesJar() throws Exception {
+        PortableContext ctx = portableContext();
+
+        PortableMarshaller marsh = portableMarshaller();
+
+        marsh.setClassNames(Arrays.asList(
+            "org.apache.ignite.portable.testjar.*",
+            "unknown.*"
+        ));
+
+        ctx.configure(marsh);
+
+        Map<Integer, Class> typeIds = U.field(ctx, "userTypes");
+
+        assertEquals(3, typeIds.size());
+
+        assertTrue(typeIds.containsKey("gridportabletestclass1".hashCode()));
+        assertTrue(typeIds.containsKey("gridportabletestclass2".hashCode()));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testClassNamesWithMapperJar() throws Exception {
+        PortableContext ctx = portableContext();
+
+        PortableMarshaller marsh = portableMarshaller();
+
+        marsh.setIdMapper(new PortableIdMapper() {
+            @SuppressWarnings("IfMayBeConditional")
+            @Override public int typeId(String clsName) {
+                if (clsName.endsWith("1"))
+                    return 100;
+                else if (clsName.endsWith("2"))
+                    return 200;
+                else
+                    return -500;
+            }
+
+            @Override public int fieldId(int typeId, String fieldName) {
+                return 0;
+            }
+        });
+
+        marsh.setClassNames(Arrays.asList(
+            "org.apache.ignite.portable.testjar.*",
+            "unknown.*"
+        ));
+
+        ctx.configure(marsh);
+
+        Map<String, PortableIdMapper> typeMappers = U.field(ctx, "typeMappers");
+
+        assertEquals(3, typeMappers.size());
+
+        assertEquals(100, typeMappers.get("GridPortableTestClass1").typeId("GridPortableTestClass1"));
+        assertEquals(200, typeMappers.get("GridPortableTestClass2").typeId("GridPortableTestClass2"));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testTypeConfigurationsJar() throws Exception {
+        PortableContext ctx = portableContext();
+
+        PortableMarshaller marsh = portableMarshaller();
+
+        marsh.setTypeConfigurations(Arrays.asList(
+            new PortableTypeConfiguration("org.apache.ignite.portable.testjar.*"),
+            new PortableTypeConfiguration("unknown.*")
+        ));
+
+        ctx.configure(marsh);
+
+        Map<Integer, Class> typeIds = U.field(ctx, "userTypes");
+
+        assertEquals(3, typeIds.size());
+
+        assertTrue(typeIds.containsKey("gridportabletestclass1".hashCode()));
+        assertTrue(typeIds.containsKey("gridportabletestclass2".hashCode()));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testTypeConfigurationsWithGlobalMapperJar() throws Exception {
+        PortableContext ctx = portableContext();
+
+        PortableMarshaller marsh = portableMarshaller();
+
+        marsh.setIdMapper(new PortableIdMapper() {
+            @SuppressWarnings("IfMayBeConditional")
+            @Override public int typeId(String clsName) {
+                if (clsName.endsWith("1"))
+                    return 100;
+                else if (clsName.endsWith("2"))
+                    return 200;
+                else
+                    return -500;
+            }
+
+            @Override public int fieldId(int typeId, String fieldName) {
+                return 0;
+            }
+        });
+
+        marsh.setTypeConfigurations(Arrays.asList(
+            new PortableTypeConfiguration("org.apache.ignite.portable.testjar.*"),
+            new PortableTypeConfiguration("unknown.*")
+        ));
+
+        ctx.configure(marsh);
+
+        Map<String, PortableIdMapper> typeMappers = U.field(ctx, "typeMappers");
+
+        assertEquals(3, typeMappers.size());
+
+        assertEquals(100, typeMappers.get("GridPortableTestClass1").typeId("GridPortableTestClass1"));
+        assertEquals(200, typeMappers.get("GridPortableTestClass2").typeId("GridPortableTestClass2"));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testTypeConfigurationsWithNonGlobalMapperJar() throws Exception {
+        PortableContext ctx = portableContext();
+
+        PortableMarshaller marsh = portableMarshaller();
+
+        marsh.setIdMapper(new PortableIdMapper() {
+            @SuppressWarnings("IfMayBeConditional")
+            @Override public int typeId(String clsName) {
+                if (clsName.endsWith("1"))
+                    return 100;
+                else if (clsName.endsWith("2"))
+                    return 200;
+                else
+                    return -500;
+            }
+
+            @Override public int fieldId(int typeId, String fieldName) {
+                return 0;
+            }
+        });
+
+        marsh.setTypeConfigurations(Arrays.asList(
+            new PortableTypeConfiguration("org.apache.ignite.portable.testjar.*"),
+            new PortableTypeConfiguration("unknown.*")
+        ));
+
+        ctx.configure(marsh);
+
+        Map<String, PortableIdMapper> typeMappers = U.field(ctx, "typeMappers");
+
+        assertEquals(3, typeMappers.size());
+
+        assertEquals(100, typeMappers.get("GridPortableTestClass1").typeId("GridPortableTestClass1"));
+        assertEquals(200, typeMappers.get("GridPortableTestClass2").typeId("GridPortableTestClass2"));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testOverrideJar() throws Exception {
+        PortableContext ctx = portableContext();
+
+        PortableMarshaller marsh = portableMarshaller();
+
+        marsh.setClassNames(Arrays.asList(
+            "org.apache.ignite.portable.testjar.*"
+        ));
+
+        PortableTypeConfiguration typeCfg = new PortableTypeConfiguration(
+            "org.apache.ignite.portable.testjar.GridPortableTestClass2");
+
+        typeCfg.setIdMapper(new PortableIdMapper() {
+            @Override public int typeId(String clsName) {
+                return 100;
+            }
+
+            @Override public int fieldId(int typeId, String fieldName) {
+                return 0;
+            }
+        });
+
+        marsh.setTypeConfigurations(Arrays.asList(typeCfg));
+
+        ctx.configure(marsh);
+
+        Map<Integer, Class> typeIds = U.field(ctx, "userTypes");
+
+        assertEquals(3, typeIds.size());
+
+        assertTrue(typeIds.containsKey("gridportabletestclass1".hashCode()));
+
+        Map<String, PortableIdMapper> typeMappers = U.field(ctx, "typeMappers");
+
+        assertEquals(3, typeMappers.size());
+
+        assertEquals(100, typeMappers.get("GridPortableTestClass2").typeId("GridPortableTestClass2"));
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/java/org/apache/ignite/internal/portable/mutabletest/GridPortableMarshalerAwareTestClass.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/portable/mutabletest/GridPortableMarshalerAwareTestClass.java b/modules/core/src/test/java/org/apache/ignite/internal/portable/mutabletest/GridPortableMarshalerAwareTestClass.java
new file mode 100644
index 0000000..0b1ecff
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/portable/mutabletest/GridPortableMarshalerAwareTestClass.java
@@ -0,0 +1,62 @@
+/*
+ * 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.portable.mutabletest;
+
+import org.apache.ignite.internal.util.typedef.internal.*;
+import org.apache.ignite.portable.*;
+import org.apache.ignite.testframework.*;
+
+/**
+ *
+ */
+public class GridPortableMarshalerAwareTestClass implements PortableMarshalAware {
+    /** */
+    public String s;
+
+    /** */
+    public String sRaw;
+
+    /** {@inheritDoc} */
+    @Override public void writePortable(PortableWriter writer) throws PortableException {
+        writer.writeString("s", s);
+
+        PortableRawWriter raw = writer.rawWriter();
+
+        raw.writeString(sRaw);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void readPortable(PortableReader reader) throws PortableException {
+        s = reader.readString("s");
+
+        PortableRawReader raw = reader.rawReader();
+
+        sRaw = raw.readString();
+    }
+
+    /** {@inheritDoc} */
+    @SuppressWarnings("FloatingPointEquality")
+    @Override public boolean equals(Object other) {
+        return this == other || GridTestUtils.deepEquals(this, other);
+    }
+
+    /** {@inheritDoc} */
+    @Override public String toString() {
+        return S.toString(GridPortableMarshalerAwareTestClass.class, this);
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/java/org/apache/ignite/internal/portable/mutabletest/GridPortableTestClasses.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/portable/mutabletest/GridPortableTestClasses.java b/modules/core/src/test/java/org/apache/ignite/internal/portable/mutabletest/GridPortableTestClasses.java
new file mode 100644
index 0000000..8407495
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/portable/mutabletest/GridPortableTestClasses.java
@@ -0,0 +1,425 @@
+/*
+ * 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.portable.mutabletest;
+
+import org.apache.ignite.internal.util.lang.*;
+import org.apache.ignite.portable.*;
+
+import com.google.common.base.*;
+
+import java.io.*;
+import java.util.*;
+
+/**
+ *
+ */
+@SuppressWarnings({"PublicInnerClass", "PublicField"})
+public class GridPortableTestClasses {
+    /**
+     *
+     */
+    public static class TestObjectContainer {
+        /** */
+        public Object foo;
+
+        /**
+         *
+         */
+        public TestObjectContainer() {
+            // No-op.
+        }
+
+        /**
+         * @param foo Object.
+         */
+        public TestObjectContainer(Object foo) {
+            this.foo = foo;
+        }
+    }
+
+    /**
+     *
+     */
+    public static class TestObjectOuter {
+        /** */
+        public TestObjectInner inner;
+
+        /** */
+        public String foo;
+
+        /**
+         *
+         */
+        public TestObjectOuter() {
+
+        }
+
+        /**
+         * @param inner Inner object.
+         */
+        public TestObjectOuter(TestObjectInner inner) {
+            this.inner = inner;
+        }
+    }
+
+    /** */
+    public static class TestObjectInner {
+        /** */
+        public Object foo;
+
+        /** */
+        public TestObjectOuter outer;
+    }
+
+    /** */
+    public static class TestObjectArrayList {
+        /** */
+        public List<String> list = new ArrayList<>();
+    }
+
+    /**
+     *
+     */
+    public static class TestObjectPlainPortable {
+        /** */
+        public PortableObject plainPortable;
+
+        /**
+         *
+         */
+        public TestObjectPlainPortable() {
+            // No-op.
+        }
+
+        /**
+         * @param plainPortable Object.
+         */
+        public TestObjectPlainPortable(PortableObject plainPortable) {
+            this.plainPortable = plainPortable;
+        }
+    }
+
+    /**
+     *
+     */
+    public static class TestObjectAllTypes implements Serializable {
+        /** */
+        public Byte b_;
+
+        /** */
+        public Short s_;
+
+        /** */
+        public Integer i_;
+
+        /** */
+        public Long l_;
+
+        /** */
+        public Float f_;
+
+        /** */
+        public Double d_;
+
+        /** */
+        public Character c_;
+
+        /** */
+        public Boolean z_;
+
+        /** */
+        public byte b;
+
+        /** */
+        public short s;
+
+        /** */
+        public int i;
+
+        /** */
+        public long l;
+
+        /** */
+        public float f;
+
+        /** */
+        public double d;
+
+        /** */
+        public char c;
+
+        /** */
+        public boolean z;
+
+        /** */
+        public String str;
+
+        /** */
+        public UUID uuid;
+
+        /** */
+        public Date date;
+
+
+        /** */
+        public byte[] bArr;
+
+        /** */
+        public short[] sArr;
+
+        /** */
+        public int[] iArr;
+
+        /** */
+        public long[] lArr;
+
+        /** */
+        public float[] fArr;
+
+        /** */
+        public double[] dArr;
+
+        /** */
+        public char[] cArr;
+
+        /** */
+        public boolean[] zArr;
+
+        /** */
+        public String[] strArr;
+
+        /** */
+        public UUID[] uuidArr;
+
+        /** */
+        public TestObjectEnum anEnum;
+
+        /** */
+        public TestObjectEnum[] enumArr;
+
+        /** */
+        public Map.Entry entry;
+
+        //public Date[] dateArr; // todo test date array.
+
+        /**
+         * @return Array.
+         */
+        private byte[] serialize() {
+            ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
+
+            try {
+                ObjectOutput out = new ObjectOutputStream(byteOut);
+
+                out.writeObject(this);
+
+                out.close();
+            }
+            catch (IOException e) {
+                Throwables.propagate(e);
+            }
+
+            return byteOut.toByteArray();
+        }
+
+        /**
+         *
+         */
+        public void setDefaultData() {
+            b_ = 11;
+            s_ = 22;
+            i_ = 33;
+            l_ = 44L;
+            f_ = 55f;
+            d_ = 66d;
+            c_ = 'e';
+            z_ = true;
+
+            b = 1;
+            s = 2;
+            i = 3;
+            l = 4;
+            f = 5;
+            d = 6;
+            c = 7;
+            z = true;
+
+            str = "abc";
+            uuid = new UUID(1, 1);
+            date = new Date(1000000);
+
+            bArr = new byte[]{1, 2, 3};
+            sArr = new short[]{1, 2, 3};
+            iArr = new int[]{1, 2, 3};
+            lArr = new long[]{1, 2, 3};
+            fArr = new float[]{1, 2, 3};
+            dArr = new double[]{1, 2, 3};
+            cArr = new char[]{1, 2, 3};
+            zArr = new boolean[]{true, false};
+
+            strArr = new String[]{"abc", "ab", "a"};
+            uuidArr = new UUID[]{new UUID(1, 1), new UUID(2, 2)};
+
+            anEnum = TestObjectEnum.A;
+
+            enumArr = new TestObjectEnum[]{TestObjectEnum.B};
+
+            entry = new GridMapEntry<>(1, "a");
+        }
+    }
+
+    /**
+     *
+     */
+    public enum TestObjectEnum {
+        A, B, C
+    }
+
+    /**
+     *
+     */
+    public static class Address {
+        /** City. */
+        public String city;
+
+        /** Street. */
+        public String street;
+
+        /** Street number. */
+        public int streetNumber;
+
+        /** Flat number. */
+        public int flatNumber;
+
+        /**
+         * Default constructor.
+         */
+        public Address() {
+            // No-op.
+        }
+
+        /**
+         * Constructor.
+         *
+         * @param city City.
+         * @param street Street.
+         * @param streetNumber Street number.
+         * @param flatNumber Flat number.
+         */
+        public Address(String city, String street, int streetNumber, int flatNumber) {
+            this.city = city;
+            this.street = street;
+            this.streetNumber = streetNumber;
+            this.flatNumber = flatNumber;
+        }
+    }
+
+    /**
+     *
+     */
+    public static class Company {
+        /** ID. */
+        public int id;
+
+        /** Name. */
+        public String name;
+
+        /** Size. */
+        public int size;
+
+        /** Address. */
+        public Address address;
+
+        /** Occupation. */
+        public String occupation;
+
+        /**
+         * Default constructor.
+         */
+        public Company() {
+            // No-op.
+        }
+
+        /**
+         * Constructor.
+         *
+         * @param id ID.
+         * @param name Name.
+         * @param size Size.
+         * @param address Address.
+         * @param occupation Occupation.
+         */
+        public Company(int id, String name, int size, Address address, String occupation) {
+            this.id = id;
+            this.name = name;
+            this.size = size;
+            this.address = address;
+            this.occupation = occupation;
+        }
+    }
+
+    /**
+     *
+     */
+    public static class AddressBook {
+        /** */
+        private Map<String, List<Company>> companyByStreet = new TreeMap<>();
+
+        /**
+         *
+         * @param street Street.
+         * @return Company.
+         */
+        public List<Company> findCompany(String street) {
+            return companyByStreet.get(street);
+        }
+
+        /**
+         *
+         * @param company Company.
+         */
+        public void addCompany(Company company) {
+            List<Company> list = companyByStreet.get(company.address.street);
+
+            if (list == null) {
+                list = new ArrayList<>();
+
+                companyByStreet.put(company.address.street, list);
+            }
+
+            list.add(company);
+        }
+
+        /**
+         *
+         * @return map
+         */
+        public Map<String, List<Company>> getCompanyByStreet() {
+            return companyByStreet;
+        }
+
+        /**
+         *
+         * @param companyByStreet map
+         */
+        public void setCompanyByStreet(Map<String, List<Company>> companyByStreet) {
+            this.companyByStreet = companyByStreet;
+        }
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/java/org/apache/ignite/internal/portable/mutabletest/package-info.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/portable/mutabletest/package-info.java b/modules/core/src/test/java/org/apache/ignite/internal/portable/mutabletest/package-info.java
new file mode 100644
index 0000000..daa13d5
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/portable/mutabletest/package-info.java
@@ -0,0 +1,22 @@
+/*
+ * 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 description. -->
+ * Contains internal tests or test related classes and interfaces.
+ */
+package org.apache.ignite.internal.portable.mutabletest;
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/java/org/apache/ignite/internal/portable/package-info.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/portable/package-info.java b/modules/core/src/test/java/org/apache/ignite/internal/portable/package-info.java
new file mode 100644
index 0000000..26897e6
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/portable/package-info.java
@@ -0,0 +1,22 @@
+/*
+ * 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 description. -->
+ * Contains internal tests or test related classes and interfaces.
+ */
+package org.apache.ignite.internal.portable;
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/java/org/apache/ignite/internal/portable/test/GridPortableTestClass1.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/portable/test/GridPortableTestClass1.java b/modules/core/src/test/java/org/apache/ignite/internal/portable/test/GridPortableTestClass1.java
new file mode 100644
index 0000000..fa5b047
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/portable/test/GridPortableTestClass1.java
@@ -0,0 +1,28 @@
+/*
+ * 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.portable.test;
+
+/**
+ */
+public class GridPortableTestClass1 {
+    /**
+     */
+    private static class InnerClass {
+        // No-op.
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/java/org/apache/ignite/internal/portable/test/GridPortableTestClass2.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/portable/test/GridPortableTestClass2.java b/modules/core/src/test/java/org/apache/ignite/internal/portable/test/GridPortableTestClass2.java
new file mode 100644
index 0000000..52131a9
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/portable/test/GridPortableTestClass2.java
@@ -0,0 +1,24 @@
+/*
+ * 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.portable.test;
+
+/**
+ */
+public class GridPortableTestClass2 {
+    // No-op.
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/java/org/apache/ignite/internal/portable/test/package-info.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/portable/test/package-info.java b/modules/core/src/test/java/org/apache/ignite/internal/portable/test/package-info.java
new file mode 100644
index 0000000..e63b814
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/portable/test/package-info.java
@@ -0,0 +1,22 @@
+/*
+ * 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 description. -->
+ * Contains internal tests or test related classes and interfaces.
+ */
+package org.apache.ignite.internal.portable.test;
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/java/org/apache/ignite/internal/portable/test/subpackage/GridPortableTestClass3.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/portable/test/subpackage/GridPortableTestClass3.java b/modules/core/src/test/java/org/apache/ignite/internal/portable/test/subpackage/GridPortableTestClass3.java
new file mode 100644
index 0000000..f620ea7
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/portable/test/subpackage/GridPortableTestClass3.java
@@ -0,0 +1,24 @@
+/*
+ * 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.portable.test.subpackage;
+
+/**
+ */
+public class GridPortableTestClass3 {
+    // No-op.
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/java/org/apache/ignite/internal/portable/test/subpackage/package-info.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/portable/test/subpackage/package-info.java b/modules/core/src/test/java/org/apache/ignite/internal/portable/test/subpackage/package-info.java
new file mode 100644
index 0000000..ae8ee73
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/portable/test/subpackage/package-info.java
@@ -0,0 +1,22 @@
+/*
+ * 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 description. -->
+ * Contains internal tests or test related classes and interfaces.
+ */
+package org.apache.ignite.internal.portable.test.subpackage;
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/GridCacheClientNodePortableMetadataMultinodeTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/GridCacheClientNodePortableMetadataMultinodeTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/GridCacheClientNodePortableMetadataMultinodeTest.java
new file mode 100644
index 0000000..bb57ab0
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/GridCacheClientNodePortableMetadataMultinodeTest.java
@@ -0,0 +1,277 @@
+/*
+ * 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.portable;
+
+import org.apache.ignite.*;
+import org.apache.ignite.configuration.*;
+import org.apache.ignite.internal.*;
+import org.apache.ignite.internal.util.typedef.internal.*;
+import org.apache.ignite.marshaller.portable.*;
+import org.apache.ignite.portable.*;
+import org.apache.ignite.spi.discovery.tcp.*;
+import org.apache.ignite.spi.discovery.tcp.ipfinder.*;
+import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.*;
+import org.apache.ignite.testframework.*;
+import org.apache.ignite.testframework.junits.common.*;
+
+import org.eclipse.jetty.util.*;
+
+import java.util.*;
+import java.util.concurrent.*;
+import java.util.concurrent.atomic.*;
+
+import static org.apache.ignite.cache.CacheWriteSynchronizationMode.*;
+
+/**
+ *
+ */
+public class GridCacheClientNodePortableMetadataMultinodeTest extends GridCommonAbstractTest {
+    /** */
+    protected static TcpDiscoveryIpFinder ipFinder = new TcpDiscoveryVmIpFinder(true);
+
+    /** */
+    private boolean client;
+
+    /** {@inheritDoc} */
+    @Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception {
+        IgniteConfiguration cfg = super.getConfiguration(gridName);
+
+        cfg.setPeerClassLoadingEnabled(false);
+
+        ((TcpDiscoverySpi)cfg.getDiscoverySpi()).setIpFinder(ipFinder).setForceServerMode(true);
+
+        cfg.setMarshaller(new PortableMarshaller());
+
+        CacheConfiguration ccfg = new CacheConfiguration();
+
+        ccfg.setWriteSynchronizationMode(FULL_SYNC);
+
+        cfg.setCacheConfiguration(ccfg);
+
+        cfg.setClientMode(client);
+
+        return cfg;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void afterTest() throws Exception {
+        super.afterTest();
+
+        stopAllGrids();
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testClientMetadataInitialization() throws Exception {
+        startGrids(2);
+
+        final AtomicBoolean stop = new AtomicBoolean();
+
+        final ConcurrentHashSet<String> allTypes = new ConcurrentHashSet<>();
+
+        IgniteInternalFuture<?> fut;
+
+        try {
+            // Update portable metadata concurrently with client nodes start.
+            fut = GridTestUtils.runMultiThreadedAsync(new Callable<Object>() {
+                @Override public Object call() throws Exception {
+                    IgnitePortables portables = ignite(0).portables();
+
+                    IgniteCache<Object, Object> cache = ignite(0).cache(null).withKeepPortable();
+
+                    ThreadLocalRandom rnd = ThreadLocalRandom.current();
+
+                    for (int i = 0; i < 1000; i++) {
+                        log.info("Iteration: " + i);
+
+                        String type = "portable-type-" + i;
+
+                        allTypes.add(type);
+
+                        for (int f = 0; f < 10; f++) {
+                            PortableBuilder builder = portables.builder(type);
+
+                            String fieldName = "f" + f;
+
+                            builder.setField(fieldName, i);
+
+                            cache.put(rnd.nextInt(0, 100_000), builder.build());
+
+                            if (f % 100 == 0)
+                                log.info("Put iteration: " + f);
+                        }
+
+                        if (stop.get())
+                            break;
+                    }
+
+                    return null;
+                }
+            }, 5, "update-thread");
+        }
+        finally {
+            stop.set(true);
+        }
+
+        client = true;
+
+        startGridsMultiThreaded(2, 5);
+
+        fut.get();
+
+        assertFalse(allTypes.isEmpty());
+
+        log.info("Expected portable types: " + allTypes.size());
+
+        assertEquals(7, ignite(0).cluster().nodes().size());
+
+        for (int i = 0; i < 7; i++) {
+            log.info("Check metadata on node: " + i);
+
+            boolean client = i > 1;
+
+            assertEquals((Object)client, ignite(i).configuration().isClientMode());
+
+            IgnitePortables portables = ignite(i).portables();
+
+            Collection<PortableMetadata> metaCol = portables.metadata();
+
+            assertEquals(allTypes.size(), metaCol.size());
+
+            Set<String> names = new HashSet<>();
+
+            for (PortableMetadata meta : metaCol) {
+                assertTrue(names.add(meta.typeName()));
+
+                assertNull(meta.affinityKeyFieldName());
+
+                assertEquals(10, meta.fields().size());
+            }
+
+            assertEquals(allTypes.size(), names.size());
+        }
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testFailoverOnStart() throws Exception {
+        startGrids(4);
+
+        IgnitePortables portables = ignite(0).portables();
+
+        IgniteCache<Object, Object> cache = ignite(0).cache(null).withKeepPortable();
+
+        for (int i = 0; i < 1000; i++) {
+            PortableBuilder builder = portables.builder("type-" + i);
+
+            builder.setField("f0", i);
+
+            cache.put(i, builder.build());
+        }
+
+        client = true;
+
+        final CyclicBarrier barrier = new CyclicBarrier(6);
+
+        final AtomicInteger startIdx = new AtomicInteger(4);
+
+        IgniteInternalFuture<?> fut = GridTestUtils.runMultiThreadedAsync(new Callable<Object>() {
+            @Override public Object call() throws Exception {
+                barrier.await();
+
+                Ignite ignite = startGrid(startIdx.getAndIncrement());
+
+                assertTrue(ignite.configuration().isClientMode());
+
+                log.info("Started node: " + ignite.name());
+
+                return null;
+            }
+        }, 5, "start-thread");
+
+        barrier.await();
+
+        U.sleep(ThreadLocalRandom.current().nextInt(10, 100));
+
+        for (int i = 0; i < 3; i++)
+            stopGrid(i);
+
+        fut.get();
+
+        assertEquals(6, ignite(3).cluster().nodes().size());
+
+        for (int i = 3; i < 7; i++) {
+            log.info("Check metadata on node: " + i);
+
+            boolean client = i > 3;
+
+            assertEquals((Object) client, ignite(i).configuration().isClientMode());
+
+            portables = ignite(i).portables();
+
+            Collection<PortableMetadata> metaCol = portables.metadata();
+
+            assertEquals(1000, metaCol.size());
+
+            Set<String> names = new HashSet<>();
+
+            for (PortableMetadata meta : metaCol) {
+                assertTrue(names.add(meta.typeName()));
+
+                assertNull(meta.affinityKeyFieldName());
+
+                assertEquals(1, meta.fields().size());
+            }
+
+            assertEquals(1000, names.size());
+        }
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testClientStartsFirst() throws Exception {
+        client = true;
+
+        Ignite ignite0 = startGrid(0);
+
+        assertTrue(ignite0.configuration().isClientMode());
+
+        client = false;
+
+        Ignite ignite1 = startGrid(1);
+
+        assertFalse(ignite1.configuration().isClientMode());
+
+        IgnitePortables portables = ignite(1).portables();
+
+        IgniteCache<Object, Object> cache = ignite(1).cache(null).withKeepPortable();
+
+        for (int i = 0; i < 100; i++) {
+            PortableBuilder builder = portables.builder("type-" + i);
+
+            builder.setField("f0", i);
+
+            cache.put(i, builder.build());
+        }
+
+        assertEquals(100, ignite(0).portables().metadata().size());
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/GridCacheClientNodePortableMetadataTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/GridCacheClientNodePortableMetadataTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/GridCacheClientNodePortableMetadataTest.java
new file mode 100644
index 0000000..2ac0bf0
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/GridCacheClientNodePortableMetadataTest.java
@@ -0,0 +1,280 @@
+/*
+ * 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.portable;
+
+import org.apache.ignite.*;
+import org.apache.ignite.cache.*;
+import org.apache.ignite.cache.affinity.*;
+import org.apache.ignite.configuration.*;
+import org.apache.ignite.internal.processors.cache.*;
+import org.apache.ignite.marshaller.portable.*;
+import org.apache.ignite.portable.*;
+import org.apache.ignite.spi.discovery.tcp.*;
+
+import java.util.*;
+
+import static org.apache.ignite.cache.CacheAtomicityMode.*;
+
+/**
+ *
+ */
+public class GridCacheClientNodePortableMetadataTest extends GridCacheAbstractSelfTest {
+    /** {@inheritDoc} */
+    @Override protected int gridCount() {
+        return 4;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected CacheMode cacheMode() {
+        return CacheMode.PARTITIONED;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected CacheAtomicityMode atomicityMode() {
+        return ATOMIC;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected NearCacheConfiguration nearConfiguration() {
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception {
+        IgniteConfiguration cfg = super.getConfiguration(gridName);
+
+        PortableMarshaller marsh = new PortableMarshaller();
+
+        marsh.setClassNames(Arrays.asList(TestObject1.class.getName(), TestObject2.class.getName()));
+
+        PortableTypeConfiguration typeCfg = new PortableTypeConfiguration();
+
+        typeCfg.setClassName(TestObject1.class.getName());
+        typeCfg.setAffinityKeyFieldName("val2");
+
+        marsh.setTypeConfigurations(Arrays.asList(typeCfg));
+
+        if (gridName.equals(getTestGridName(gridCount() - 1)))
+            cfg.setClientMode(true);
+
+        cfg.setMarshaller(marsh);
+
+        ((TcpDiscoverySpi)cfg.getDiscoverySpi()).setForceServerMode(true);
+
+        return cfg;
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testPortableMetadataOnClient() throws Exception {
+        Ignite ignite0 = ignite(gridCount() - 1);
+
+        assertTrue(ignite0.configuration().isClientMode());
+
+        Ignite ignite1 = ignite(0);
+
+        assertFalse(ignite1.configuration().isClientMode());
+
+        Affinity<Object> aff0 = ignite0.affinity(null);
+        Affinity<Object> aff1 = ignite1.affinity(null);
+
+        for (int i = 0 ; i < 100; i++) {
+            TestObject1 obj1 = new TestObject1(i, i + 1);
+
+            assertEquals(aff1.mapKeyToPrimaryAndBackups(obj1),
+                aff0.mapKeyToPrimaryAndBackups(obj1));
+
+            TestObject2 obj2 = new TestObject2(i, i + 1);
+
+            assertEquals(aff1.mapKeyToPrimaryAndBackups(obj2),
+                aff0.mapKeyToPrimaryAndBackups(obj2));
+        }
+
+        {
+            PortableBuilder builder = ignite0.portables().builder("TestObject3");
+
+            builder.setField("f1", 1);
+
+            ignite0.cache(null).put(0, builder.build());
+
+            IgniteCache<Integer, PortableObject> cache = ignite0.cache(null).withKeepPortable();
+
+            PortableObject obj = cache.get(0);
+
+            PortableMetadata meta = obj.metaData();
+
+            assertNotNull(meta);
+            assertEquals(1, meta.fields().size());
+
+            meta = ignite0.portables().metadata(TestObject1.class);
+
+            assertNotNull(meta);
+            assertEquals("val2", meta.affinityKeyFieldName());
+
+            meta = ignite0.portables().metadata(TestObject2.class);
+
+            assertNotNull(meta);
+            assertNull(meta.affinityKeyFieldName());
+        }
+
+        {
+            PortableBuilder builder = ignite1.portables().builder("TestObject3");
+
+            builder.setField("f2", 2);
+
+            ignite1.cache(null).put(1, builder.build());
+
+            IgniteCache<Integer, PortableObject> cache = ignite1.cache(null).withKeepPortable();
+
+            PortableObject obj = cache.get(0);
+
+            PortableMetadata meta = obj.metaData();
+
+            assertNotNull(meta);
+            assertEquals(2, meta.fields().size());
+
+            meta = ignite1.portables().metadata(TestObject1.class);
+
+            assertNotNull(meta);
+            assertEquals("val2", meta.affinityKeyFieldName());
+
+            meta = ignite1.portables().metadata(TestObject2.class);
+
+            assertNotNull(meta);
+            assertNull(meta.affinityKeyFieldName());
+        }
+
+        PortableMetadata meta = ignite0.portables().metadata("TestObject3");
+
+        assertNotNull(meta);
+        assertEquals(2, meta.fields().size());
+
+        IgniteCache<Integer, PortableObject> cache = ignite0.cache(null).withKeepPortable();
+
+        PortableObject obj = cache.get(1);
+
+        assertEquals(Integer.valueOf(2), obj.field("f2"));
+        assertNull(obj.field("f1"));
+
+        meta = obj.metaData();
+
+        assertNotNull(meta);
+        assertEquals(2, meta.fields().size());
+
+        Collection<PortableMetadata> meta1 = ignite1.portables().metadata();
+        Collection<PortableMetadata> meta2 = ignite1.portables().metadata();
+
+        assertEquals(meta1.size(), meta2.size());
+
+        for (PortableMetadata m1 : meta1) {
+            boolean found = false;
+
+            for (PortableMetadata m2 : meta1) {
+                if (m1.typeName().equals(m2.typeName())) {
+                    assertEquals(m1.affinityKeyFieldName(), m2.affinityKeyFieldName());
+                    assertEquals(m1.fields(), m2.fields());
+
+                    found = true;
+
+                    break;
+                }
+            }
+
+            assertTrue(found);
+        }
+    }
+
+    /**
+     *
+     */
+    static class TestObject1 {
+        /** */
+        private int val1;
+
+        /** */
+        private int val2;
+
+        /**
+         * @param val1 Value 1.
+         * @param val2 Value 2.
+         */
+        public TestObject1(int val1, int val2) {
+            this.val1 = val1;
+            this.val2 = val2;
+        }
+
+        /** {@inheritDoc} */
+        @Override public boolean equals(Object o) {
+            if (this == o)
+                return true;
+
+            if (o == null || getClass() != o.getClass())
+                return false;
+
+            TestObject1 that = (TestObject1)o;
+
+            return val1 == that.val1;
+
+        }
+
+        /** {@inheritDoc} */
+        @Override public int hashCode() {
+            return val1;
+        }
+    }
+
+    /**
+     *
+     */
+    static class TestObject2 {
+        /** */
+        private int val1;
+
+        /** */
+        private int val2;
+
+        /**
+         * @param val1 Value 1.
+         * @param val2 Value 2.
+         */
+        public TestObject2(int val1, int val2) {
+            this.val1 = val1;
+            this.val2 = val2;
+        }
+
+        /** {@inheritDoc} */
+        @Override public boolean equals(Object o) {
+            if (this == o)
+                return true;
+
+            if (o == null || getClass() != o.getClass())
+                return false;
+
+            TestObject2 that = (TestObject2)o;
+
+            return val2 == that.val2;
+
+        }
+
+        /** {@inheritDoc} */
+        @Override public int hashCode() {
+            return val2;
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/GridCachePortableObjectsAbstractDataStreamerSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/GridCachePortableObjectsAbstractDataStreamerSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/GridCachePortableObjectsAbstractDataStreamerSelfTest.java
new file mode 100644
index 0000000..9f8f1f5
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/GridCachePortableObjectsAbstractDataStreamerSelfTest.java
@@ -0,0 +1,183 @@
+/*
+ * 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.portable;
+
+import org.apache.ignite.*;
+import org.apache.ignite.cache.*;
+import org.apache.ignite.configuration.*;
+import org.apache.ignite.internal.*;
+import org.apache.ignite.marshaller.portable.*;
+import org.apache.ignite.portable.*;
+import org.apache.ignite.testframework.junits.common.*;
+
+import org.jsr166.*;
+
+import java.io.*;
+import java.util.*;
+import java.util.concurrent.*;
+import java.util.concurrent.atomic.*;
+
+import static org.apache.ignite.cache.CacheWriteSynchronizationMode.*;
+
+/**
+ * Test for portable objects stored in cache.
+ */
+public abstract class GridCachePortableObjectsAbstractDataStreamerSelfTest extends GridCommonAbstractTest {
+    /** */
+    private static final int THREAD_CNT = 64;
+
+    /** {@inheritDoc} */
+    @Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception {
+        IgniteConfiguration cfg = super.getConfiguration(gridName);
+
+        CacheConfiguration cacheCfg = new CacheConfiguration();
+
+        cacheCfg.setCacheMode(cacheMode());
+        cacheCfg.setAtomicityMode(atomicityMode());
+        cacheCfg.setNearConfiguration(nearConfiguration());
+        cacheCfg.setWriteSynchronizationMode(writeSynchronizationMode());
+
+        cfg.setCacheConfiguration(cacheCfg);
+
+        PortableMarshaller marsh = new PortableMarshaller();
+
+        marsh.setTypeConfigurations(Arrays.asList(
+            new PortableTypeConfiguration(TestObject.class.getName())));
+
+        cfg.setMarshaller(marsh);
+
+        return cfg;
+    }
+
+    /**
+     * @return Sync mode.
+     */
+    protected CacheWriteSynchronizationMode writeSynchronizationMode() {
+        return PRIMARY_SYNC;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void beforeTestsStarted() throws Exception {
+        startGridsMultiThreaded(gridCount());
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void afterTestsStopped() throws Exception {
+        stopAllGrids();
+    }
+
+    /**
+     * @return Cache mode.
+     */
+    protected abstract CacheMode cacheMode();
+
+    /**
+     * @return Atomicity mode.
+     */
+    protected abstract CacheAtomicityMode atomicityMode();
+
+    /**
+     * @return Near configuration.
+     */
+    protected abstract NearCacheConfiguration nearConfiguration();
+
+    /**
+     * @return Grid count.
+     */
+    protected int gridCount() {
+        return 1;
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    @SuppressWarnings("BusyWait")
+    public void testGetPut() throws Exception {
+        final AtomicBoolean flag = new AtomicBoolean();
+
+        final LongAdder8 cnt = new LongAdder8();
+
+        try (IgniteDataStreamer<Object, Object> ldr = grid(0).dataStreamer(null)) {
+            IgniteInternalFuture<?> f = multithreadedAsync(
+                new Callable<Object>() {
+                    @Override public Object call() throws Exception {
+                        ThreadLocalRandom rnd = ThreadLocalRandom.current();
+
+                        while (!flag.get()) {
+                            ldr.addData(rnd.nextInt(10000), new TestObject(rnd.nextInt(10000)));
+
+                            cnt.add(1);
+                        }
+
+                        return null;
+                    }
+                },
+                THREAD_CNT
+            );
+
+            for (int i = 0; i < 30 && !f.isDone(); i++)
+                Thread.sleep(1000);
+
+            flag.set(true);
+
+            f.get();
+        }
+
+        info("Operations in 30 sec: " + cnt.sum());
+    }
+
+    /**
+     */
+    private static class TestObject implements PortableMarshalAware, Serializable {
+        /** */
+        private int val;
+
+        /**
+         */
+        private TestObject() {
+            // No-op.
+        }
+
+        /**
+         * @param val Value.
+         */
+        private TestObject(int val) {
+            this.val = val;
+        }
+
+        /** {@inheritDoc} */
+        @Override public int hashCode() {
+            return val;
+        }
+
+        /** {@inheritDoc} */
+        @Override public boolean equals(Object obj) {
+            return obj instanceof TestObject && ((TestObject)obj).val == val;
+        }
+
+        /** {@inheritDoc} */
+        @Override public void writePortable(PortableWriter writer) throws PortableException {
+            writer.writeInt("val", val);
+        }
+
+        /** {@inheritDoc} */
+        @Override public void readPortable(PortableReader reader) throws PortableException {
+            val = reader.readInt("val");
+        }
+    }
+}


[35/59] [abbrv] ignite git commit: Merge remote-tracking branch 'origin/master'

Posted by vk...@apache.org.
Merge remote-tracking branch 'origin/master'


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

Branch: refs/heads/ignite-884
Commit: 76bc7d61352f68c3e1fe83652a747f234adcd0c1
Parents: 194df76 203f00c
Author: sboikov <sb...@gridgain.com>
Authored: Wed Aug 26 10:45:25 2015 +0300
Committer: sboikov <sb...@gridgain.com>
Committed: Wed Aug 26 10:45:25 2015 +0300

----------------------------------------------------------------------
 .../internal/platform/PlatformBootstrap.java    |  36 -
 .../platform/PlatformBootstrapFactory.java      |  37 -
 .../internal/platform/PlatformException.java    |  71 --
 .../internal/platform/PlatformIgnition.java     | 187 ----
 .../platform/PlatformNoCallbackException.java   |  50 --
 .../callback/PlatformCallbackGateway.java       | 869 -------------------
 .../callback/PlatformCallbackUtils.java         | 468 ----------
 .../platform/memory/PlatformAbstractMemory.java | 121 ---
 .../PlatformBigEndianInputStreamImpl.java       | 126 ---
 .../PlatformBigEndianOutputStreamImpl.java      | 162 ----
 .../platform/memory/PlatformExternalMemory.java |  55 --
 .../platform/memory/PlatformInputStream.java    |  30 -
 .../memory/PlatformInputStreamImpl.java         | 323 -------
 .../platform/memory/PlatformMemory.java         |  77 --
 .../platform/memory/PlatformMemoryManager.java  |  46 -
 .../memory/PlatformMemoryManagerImpl.java       |  83 --
 .../platform/memory/PlatformMemoryPool.java     | 133 ---
 .../platform/memory/PlatformMemoryUtils.java    | 468 ----------
 .../platform/memory/PlatformOutputStream.java   |  30 -
 .../memory/PlatformOutputStreamImpl.java        | 259 ------
 .../platform/memory/PlatformPooledMemory.java   |  63 --
 .../platform/memory/PlatformUnpooledMemory.java |  51 --
 .../platform/utils/PlatformReaderBiClosure.java |  34 -
 .../platform/utils/PlatformReaderClosure.java   |  34 -
 .../platform/utils/PlatformWriterBiClosure.java |  34 -
 .../platform/utils/PlatformWriterClosure.java   |  33 -
 .../platform/PlatformAbstractBootstrap.java     |  47 +
 .../processors/platform/PlatformBootstrap.java  |  36 +
 .../platform/PlatformBootstrapFactory.java      |  37 +
 .../processors/platform/PlatformException.java  |  71 ++
 .../processors/platform/PlatformIgnition.java   | 186 ++++
 .../platform/PlatformNoCallbackException.java   |  50 ++
 .../callback/PlatformCallbackGateway.java       | 869 +++++++++++++++++++
 .../callback/PlatformCallbackUtils.java         | 468 ++++++++++
 .../platform/memory/PlatformAbstractMemory.java | 121 +++
 .../PlatformBigEndianInputStreamImpl.java       | 126 +++
 .../PlatformBigEndianOutputStreamImpl.java      | 162 ++++
 .../platform/memory/PlatformExternalMemory.java |  55 ++
 .../platform/memory/PlatformInputStream.java    |  30 +
 .../memory/PlatformInputStreamImpl.java         | 323 +++++++
 .../platform/memory/PlatformMemory.java         |  77 ++
 .../platform/memory/PlatformMemoryManager.java  |  46 +
 .../memory/PlatformMemoryManagerImpl.java       |  83 ++
 .../platform/memory/PlatformMemoryPool.java     | 133 +++
 .../platform/memory/PlatformMemoryUtils.java    | 468 ++++++++++
 .../platform/memory/PlatformOutputStream.java   |  30 +
 .../memory/PlatformOutputStreamImpl.java        | 259 ++++++
 .../platform/memory/PlatformPooledMemory.java   |  63 ++
 .../platform/memory/PlatformUnpooledMemory.java |  51 ++
 .../platform/utils/PlatformReaderBiClosure.java |  34 +
 .../platform/utils/PlatformReaderClosure.java   |  34 +
 .../platform/utils/PlatformWriterBiClosure.java |  34 +
 .../platform/utils/PlatformWriterClosure.java   |  33 +
 53 files changed, 3926 insertions(+), 3880 deletions(-)
----------------------------------------------------------------------



[21/59] [abbrv] ignite git commit: IGNITE-1287: Ignite .Net projects changes.

Posted by vk...@apache.org.
IGNITE-1287: Ignite .Net projects changes.


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

Branch: refs/heads/ignite-884
Commit: e5358de721be3f9248cf0528b4d1c48441cec3a7
Parents: 75e04fa
Author: vozerov-gridgain <vo...@gridgain.com>
Authored: Tue Aug 25 16:38:07 2015 +0300
Committer: vozerov-gridgain <vo...@gridgain.com>
Committed: Tue Aug 25 16:38:07 2015 +0300

----------------------------------------------------------------------
 .../main/dotnet/Apache.Ignite.Core/Properties/AssemblyInfo.cs | 6 +++++-
 .../Apache.Ignite.Core.Tests/Apache.Ignite.Core.Tests.csproj  | 7 -------
 2 files changed, 5 insertions(+), 8 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/e5358de7/modules/platform/src/main/dotnet/Apache.Ignite.Core/Properties/AssemblyInfo.cs
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Properties/AssemblyInfo.cs b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Properties/AssemblyInfo.cs
index 4127523..8deafec 100644
--- a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Properties/AssemblyInfo.cs
+++ b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Properties/AssemblyInfo.cs
@@ -38,4 +38,8 @@ using System.Runtime.InteropServices;
 
 [assembly: CLSCompliant(true)]
 
-[assembly: InternalsVisibleTo("Apache.Ignite.Core.Tests")]
\ No newline at end of file
+#if !EXCLUDE_TESTS
+
+[assembly: InternalsVisibleTo("Apache.Ignite.Core.Tests")]
+
+#endif
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5358de7/modules/platform/src/test/dotnet/Apache.Ignite.Core.Tests/Apache.Ignite.Core.Tests.csproj
----------------------------------------------------------------------
diff --git a/modules/platform/src/test/dotnet/Apache.Ignite.Core.Tests/Apache.Ignite.Core.Tests.csproj b/modules/platform/src/test/dotnet/Apache.Ignite.Core.Tests/Apache.Ignite.Core.Tests.csproj
index 9e8f9d1..418f467 100644
--- a/modules/platform/src/test/dotnet/Apache.Ignite.Core.Tests/Apache.Ignite.Core.Tests.csproj
+++ b/modules/platform/src/test/dotnet/Apache.Ignite.Core.Tests/Apache.Ignite.Core.Tests.csproj
@@ -31,13 +31,6 @@
     <PlatformTarget>x86</PlatformTarget>
     <OutputPath>bin\x86\Release\</OutputPath>
   </PropertyGroup>
-  <PropertyGroup>
-    <SignAssembly>true</SignAssembly>
-  </PropertyGroup>
-  <PropertyGroup>
-    <AssemblyOriginatorKeyFile>
-    </AssemblyOriginatorKeyFile>
-  </PropertyGroup>
   <ItemGroup>
     <Reference Include="nunit-console-runner">
       <HintPath>..\libs\nunit-console-runner.dll</HintPath>


[23/59] [abbrv] ignite git commit: ignite-1217: apply-pull-request.sh

Posted by vk...@apache.org.
ignite-1217: apply-pull-request.sh


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

Branch: refs/heads/ignite-884
Commit: 3d0dac6a28ca390e5618bc8d0419e951e2babb20
Parents: 2c86d60
Author: ashutak <as...@gridgain.com>
Authored: Tue Aug 25 19:39:06 2015 +0300
Committer: ashutak <as...@gridgain.com>
Committed: Tue Aug 25 19:39:06 2015 +0300

----------------------------------------------------------------------
 scripts/apply-pull-request.sh | 141 +++++++++++++++++++++++++++++++++++++
 1 file changed, 141 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/3d0dac6a/scripts/apply-pull-request.sh
----------------------------------------------------------------------
diff --git a/scripts/apply-pull-request.sh b/scripts/apply-pull-request.sh
new file mode 100755
index 0000000..baa73b5
--- /dev/null
+++ b/scripts/apply-pull-request.sh
@@ -0,0 +1,141 @@
+#!/bin/bash
+#
+# 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.
+#
+
+#
+# Pull request applier.
+#
+echo 'Usage: scripts/apply-pull-request.sh <pull-request-id>'
+echo 'The script takes pull-request by given id and merges (with squash) all changes too master branch.'
+echo "Argument 'pull-request-id' is mandatory."
+echo
+
+IGNITE_HOME="$(dirname "$(cd "$(dirname "$0")"; "pwd")")";
+
+. ${IGNITE_HOME}/scripts/git-patch-functions.sh # Import patch functions.
+
+# Constants.
+APACHE_GIT="https://git-wip-us.apache.org/repos/asf/ignite"
+GITHUB_MIRROR="https://github.com/apache/ignite.git"
+
+# Get paramethers.
+PR_ID=$1
+
+# Initial checks.
+if [ "${PR_ID}" = "" ]; then
+    echo $0", ERROR:"
+    echo >&2 "You have to specify 'pull-request-id'."
+    exit 1
+fi
+
+requireCleanWorkTree ${IGNITE_HOME}
+
+CURRENT_BRANCH=`git rev-parse --abbrev-ref HEAD`
+
+if [ "$CURRENT_BRANCH" != "master" ]; then
+    echo $0", ERROR:"
+    echo "You have to be on master branch."
+
+    exit 1
+fi
+
+# Check that master is up-to-date.
+APACHE_GIT_MASTER_BRANCH="apache-git-master-tmp"
+
+git fetch ${APACHE_GIT} master:${APACHE_GIT_MASTER_BRANCH} &> /dev/null
+
+LOCAL_MASTER_HASH=$(git rev-parse @)
+REMOTE_MASTER_HASH=$(git rev-parse ${APACHE_GIT_MASTER_BRANCH})
+BASE_HASH=$(git merge-base @ ${APACHE_GIT_MASTER_BRANCH})
+
+git branch -D ${APACHE_GIT_MASTER_BRANCH} &> /dev/null
+
+if [ $LOCAL_MASTER_HASH != $REMOTE_MASTER_HASH ]; then
+    echo $0", ERROR:"
+
+    if [ $LOCAL_MASTER_HASH = $BASE_HASH ]; then
+        echo "Your local master branch is not up-to-date. You need to pull."
+    elif [ $REMOTE_MASTER_HASH = $BASE_HASH ]; then
+        echo "Your local master branch is ahead of master branch at Apache git. You need to push."
+    else
+        echo "Your local master and Apache git master branches diverged. You need to pull, merge and pull."
+    fi
+
+    exit 1
+fi
+
+echo "Local master is Up-to-date."
+echo
+
+# Checkout pull-request branch.
+PR_BRANCH_NAME="pull-${PR_ID}-head"
+
+git fetch ${GITHUB_MIRROR} pull/${PR_ID}/head:${PR_BRANCH_NAME} &> /dev/null
+if test $? != 0; then
+    echo $0", ERROR:"
+    echo >&2 "There was not found pull request by ID = '${PR_ID}'."
+    exit 1
+fi
+
+# Get author name number.
+git checkout ${PR_BRANCH_NAME} &> /dev/null
+if test $? != 0; then
+    echo $0", ERROR:"
+    echo >&2 "Failed to checkout '${PR_BRANCH_NAME}' branch (the branch not found or already exists)."
+    exit 1
+fi
+
+AUTHOR="$(git --no-pager show -s --format="%aN <%aE>" HEAD)"
+ORIG_COMMENT="$(git log -1 --pretty=%B)"
+
+echo "Author of pull-request: '$AUTHOR'."
+echo
+
+# Update local master.
+git checkout master &> /dev/null
+
+# Take changes.
+git merge --squash ${PR_BRANCH_NAME} &> /dev/null
+if test $? != 0; then
+    git reset --hard &> /dev/null
+
+    echo $0", ERROR:"
+    echo >&2 "Could not merge the pull-request to master without conflicts. All local changes have been discarded. You're on master branch."
+    exit 1
+fi
+
+echo "Original comment is"
+echo "\"${ORIG_COMMENT}\""
+echo "Press [ENTER] if you're agree with the comment or type your comment and press [ENTER]:"
+read COMMENT
+echo
+
+if [ "${COMMENT}" == "" ]; then
+    COMMENT=${ORIG_COMMENT}
+fi
+
+git commit --author "${AUTHOR}" -a -s -m "${COMMENT}" &> /dev/null
+
+echo "Squash commit for pull request with id='${PR_ID}' has been added. The commit has been added with comment '${COMMENT}'."
+echo "Now you can review changes of the last commit at master and push it to Ignite Apche git after."
+echo "If you want to decline changes, you can remove the last commit from your repo by 'git reset --hard HEAD^'."
+echo
+
+# Clean-up.
+git branch -D ${PR_BRANCH_NAME} &> /dev/null
+
+echo 'Successfully completed.'


[12/59] [abbrv] ignite git commit: ignite-1258: portable objects API support in Ignite

Posted by vk...@apache.org.
http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableContext.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableContext.java b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableContext.java
new file mode 100644
index 0000000..83dd01d
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableContext.java
@@ -0,0 +1,1089 @@
+/*
+ * 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.portable;
+
+import org.apache.ignite.*;
+import org.apache.ignite.internal.*;
+import org.apache.ignite.internal.processors.cache.portable.*;
+import org.apache.ignite.internal.util.*;
+import org.apache.ignite.internal.util.lang.*;
+import org.apache.ignite.internal.util.typedef.*;
+import org.apache.ignite.internal.util.typedef.internal.*;
+import org.apache.ignite.lang.*;
+import org.apache.ignite.marshaller.*;
+import org.apache.ignite.marshaller.optimized.*;
+import org.apache.ignite.marshaller.portable.*;
+import org.apache.ignite.portable.*;
+
+import org.jetbrains.annotations.*;
+import org.jsr166.*;
+
+import java.io.*;
+import java.math.*;
+import java.net.*;
+import java.sql.*;
+import java.util.*;
+import java.util.Date;
+import java.util.concurrent.*;
+import java.util.jar.*;
+
+/**
+ * Portable context.
+ */
+public class PortableContext implements Externalizable {
+    /** */
+    private static final long serialVersionUID = 0L;
+
+    /** */
+    static final PortableIdMapper DFLT_ID_MAPPER = new IdMapperWrapper(null);
+
+    /** */
+    static final PortableIdMapper BASIC_CLS_ID_MAPPER = new BasicClassIdMapper();
+
+    /** */
+    static final char[] LOWER_CASE_CHARS;
+
+    /** */
+    static final char MAX_LOWER_CASE_CHAR = 0x7e;
+
+    /**
+     *
+     */
+    static {
+        LOWER_CASE_CHARS = new char[MAX_LOWER_CASE_CHAR + 1];
+
+        for (char c = 0; c <= MAX_LOWER_CASE_CHAR; c++)
+            LOWER_CASE_CHARS[c] = Character.toLowerCase(c);
+    }
+
+    /** */
+    private final ConcurrentMap<Integer, Collection<Integer>> metaDataCache = new ConcurrentHashMap8<>();
+
+    /** */
+    private final ConcurrentMap<Class<?>, PortableClassDescriptor> descByCls = new ConcurrentHashMap8<>();
+
+    /** */
+    private final ConcurrentMap<Integer, PortableClassDescriptor> userTypes = new ConcurrentHashMap8<>(0);
+
+    /** */
+    private final Map<Integer, PortableClassDescriptor> predefinedTypes = new HashMap<>();
+
+    /** */
+    private final Set<Class> predefinedClasses = new HashSet<>();
+
+    /** */
+    private final Map<Class<? extends Collection>, Byte> colTypes = new HashMap<>();
+
+    /** */
+    private final Map<Class<? extends Map>, Byte> mapTypes = new HashMap<>();
+
+    /** */
+    private final Map<Integer, PortableIdMapper> mappers = new ConcurrentHashMap8<>(0);
+
+    /** */
+    private final Map<String, PortableIdMapper> typeMappers = new ConcurrentHashMap8<>(0);
+
+    /** */
+    private Map<Integer, Boolean> metaEnabled = new HashMap<>(0);
+
+    /** */
+    private Set<Integer> usingTs = new HashSet<>();
+
+    /** */
+    private PortableMetaDataHandler metaHnd;
+
+    /** */
+    private MarshallerContext marshCtx;
+
+    /** */
+    private String gridName;
+
+    /** */
+    private PortableMarshaller marsh;
+
+    /** */
+    private final OptimizedMarshaller optmMarsh = new OptimizedMarshaller();
+
+    /**
+     * For {@link Externalizable}.
+     */
+    public PortableContext() {
+        // No-op.
+    }
+
+    /**
+     * @param metaHnd Meta data handler.
+     * @param gridName Grid name.
+     */
+    public PortableContext(PortableMetaDataHandler metaHnd, @Nullable String gridName) {
+        assert metaHnd != null;
+
+        this.metaHnd = metaHnd;
+        this.gridName = gridName;
+
+        colTypes.put(ArrayList.class, GridPortableMarshaller.ARR_LIST);
+        colTypes.put(LinkedList.class, GridPortableMarshaller.LINKED_LIST);
+        colTypes.put(HashSet.class, GridPortableMarshaller.HASH_SET);
+        colTypes.put(LinkedHashSet.class, GridPortableMarshaller.LINKED_HASH_SET);
+        colTypes.put(TreeSet.class, GridPortableMarshaller.TREE_SET);
+        colTypes.put(ConcurrentSkipListSet.class, GridPortableMarshaller.CONC_SKIP_LIST_SET);
+
+        mapTypes.put(HashMap.class, GridPortableMarshaller.HASH_MAP);
+        mapTypes.put(LinkedHashMap.class, GridPortableMarshaller.LINKED_HASH_MAP);
+        mapTypes.put(TreeMap.class, GridPortableMarshaller.TREE_MAP);
+        mapTypes.put(ConcurrentHashMap.class, GridPortableMarshaller.CONC_HASH_MAP);
+        mapTypes.put(ConcurrentHashMap8.class, GridPortableMarshaller.CONC_HASH_MAP);
+        mapTypes.put(Properties.class, GridPortableMarshaller.PROPERTIES_MAP);
+
+        registerPredefinedType(Byte.class, GridPortableMarshaller.BYTE);
+        registerPredefinedType(Boolean.class, GridPortableMarshaller.BOOLEAN);
+        registerPredefinedType(Short.class, GridPortableMarshaller.SHORT);
+        registerPredefinedType(Character.class, GridPortableMarshaller.CHAR);
+        registerPredefinedType(Integer.class, GridPortableMarshaller.INT);
+        registerPredefinedType(Long.class, GridPortableMarshaller.LONG);
+        registerPredefinedType(Float.class, GridPortableMarshaller.FLOAT);
+        registerPredefinedType(Double.class, GridPortableMarshaller.DOUBLE);
+        registerPredefinedType(String.class, GridPortableMarshaller.STRING);
+        registerPredefinedType(BigDecimal.class, GridPortableMarshaller.DECIMAL);
+        registerPredefinedType(Date.class, GridPortableMarshaller.DATE);
+        registerPredefinedType(UUID.class, GridPortableMarshaller.UUID);
+        // TODO: How to handle timestamp? It has the same ID in .Net.
+        registerPredefinedType(Timestamp.class, GridPortableMarshaller.DATE);
+
+        registerPredefinedType(byte[].class, GridPortableMarshaller.BYTE_ARR);
+        registerPredefinedType(short[].class, GridPortableMarshaller.SHORT_ARR);
+        registerPredefinedType(int[].class, GridPortableMarshaller.INT_ARR);
+        registerPredefinedType(long[].class, GridPortableMarshaller.LONG_ARR);
+        registerPredefinedType(float[].class, GridPortableMarshaller.FLOAT_ARR);
+        registerPredefinedType(double[].class, GridPortableMarshaller.DOUBLE_ARR);
+        registerPredefinedType(char[].class, GridPortableMarshaller.CHAR_ARR);
+        registerPredefinedType(boolean[].class, GridPortableMarshaller.BOOLEAN_ARR);
+        registerPredefinedType(BigDecimal[].class, GridPortableMarshaller.DECIMAL_ARR);
+        registerPredefinedType(String[].class, GridPortableMarshaller.STRING_ARR);
+        registerPredefinedType(UUID[].class, GridPortableMarshaller.UUID_ARR);
+        registerPredefinedType(Date[].class, GridPortableMarshaller.DATE_ARR);
+        registerPredefinedType(Object[].class, GridPortableMarshaller.OBJ_ARR);
+
+        registerPredefinedType(ArrayList.class, 0);
+        registerPredefinedType(LinkedList.class, 0);
+        registerPredefinedType(HashSet.class, 0);
+        registerPredefinedType(LinkedHashSet.class, 0);
+        registerPredefinedType(TreeSet.class, 0);
+        registerPredefinedType(ConcurrentSkipListSet.class, 0);
+
+        registerPredefinedType(HashMap.class, 0);
+        registerPredefinedType(LinkedHashMap.class, 0);
+        registerPredefinedType(TreeMap.class, 0);
+        registerPredefinedType(ConcurrentHashMap.class, 0);
+        registerPredefinedType(ConcurrentHashMap8.class, 0);
+
+        registerPredefinedType(GridMapEntry.class, 60);
+        registerPredefinedType(IgniteBiTuple.class, 61);
+        registerPredefinedType(T2.class, 62);
+
+        registerPredefinedType(PortableObjectImpl.class, 63);
+
+        registerPredefinedType(PortableMetaDataImpl.class, 64);
+
+// TODO: IGNITE-1258
+//        registerPredefinedType(DrSenderAttributes.class, 65);
+//        registerPredefinedType(DrSenderRemoteAttributes.class, 66);
+//
+//        registerPredefinedType(InteropClusterNode.class, 67);
+//        registerPredefinedType(InteropClusterMetrics.class, 68);
+//        registerPredefinedType(InteropTransactionMetrics.class, 69);
+//        registerPredefinedType(InteropMetadata.class, 70);
+//
+//        registerPredefinedType(InteropDotNetConfiguration.class, 71);
+//        registerPredefinedType(InteropDotNetPortableConfiguration.class, 72);
+//        registerPredefinedType(InteropDotNetPortableTypeConfiguration.class, 73);
+//        registerPredefinedType(InteropIgniteProxy.class, 74);
+//        registerPredefinedType(InteropCacheMetrics.class, 75);
+//        registerPredefinedType(InteropProductLicence.class, 78);
+    }
+
+    /**
+     * @param marsh Portable marshaller.
+     * @throws PortableException In case of error.
+     */
+    public void configure(PortableMarshaller marsh) throws PortableException {
+        if (marsh == null)
+            return;
+
+        this.marsh = marsh;
+        marshCtx = marsh.getContext();
+
+        assert marshCtx != null;
+
+        optmMarsh.setContext(marshCtx);
+
+        PortableIdMapper globalIdMapper = marsh.getIdMapper();
+        PortableSerializer globalSerializer = marsh.getSerializer();
+        boolean globalUseTs = marsh.isUseTimestamp();
+        boolean globalMetaDataEnabled = marsh.isMetaDataEnabled();
+        boolean globalKeepDeserialized = marsh.isKeepDeserialized();
+
+        TypeDescriptors descs = new TypeDescriptors();
+
+        if (marsh.getClassNames() != null) {
+            PortableIdMapper idMapper = new IdMapperWrapper(globalIdMapper);
+
+            for (String clsName : marsh.getClassNames()) {
+                if (clsName.endsWith(".*")) { // Package wildcard
+                    String pkgName = clsName.substring(0, clsName.length() - 2);
+
+                    for (String clsName0 : classesInPackage(pkgName))
+                        descs.add(clsName0, idMapper, null, null, globalUseTs, globalMetaDataEnabled,
+                                  globalKeepDeserialized, true);
+                }
+                else // Regular single class
+                    descs.add(clsName, idMapper, null, null, globalUseTs, globalMetaDataEnabled,
+                              globalKeepDeserialized, true);
+            }
+        }
+
+        if (marsh.getTypeConfigurations() != null) {
+            for (PortableTypeConfiguration typeCfg : marsh.getTypeConfigurations()) {
+                String clsName = typeCfg.getClassName();
+
+                if (clsName == null)
+                    throw new PortableException("Class name is required for portable type configuration.");
+
+                PortableIdMapper idMapper = globalIdMapper;
+
+                if (typeCfg.getIdMapper() != null)
+                    idMapper = typeCfg.getIdMapper();
+
+                idMapper = new IdMapperWrapper(idMapper);
+
+                PortableSerializer serializer = globalSerializer;
+
+                if (typeCfg.getSerializer() != null)
+                    serializer = typeCfg.getSerializer();
+
+                boolean useTs = typeCfg.isUseTimestamp() != null ? typeCfg.isUseTimestamp() : globalUseTs;
+                boolean metaDataEnabled = typeCfg.isMetaDataEnabled() != null ? typeCfg.isMetaDataEnabled() :
+                    globalMetaDataEnabled;
+                boolean keepDeserialized = typeCfg.isKeepDeserialized() != null ? typeCfg.isKeepDeserialized() :
+                    globalKeepDeserialized;
+
+                if (clsName.endsWith(".*")) {
+                    String pkgName = clsName.substring(0, clsName.length() - 2);
+
+                    for (String clsName0 : classesInPackage(pkgName))
+                        descs.add(clsName0, idMapper, serializer, typeCfg.getAffinityKeyFieldName(), useTs,
+                                  metaDataEnabled, keepDeserialized, true);
+                }
+                else
+                    descs.add(clsName, idMapper, serializer, typeCfg.getAffinityKeyFieldName(), useTs,
+                              metaDataEnabled, keepDeserialized, false);
+            }
+        }
+
+        for (TypeDescriptor desc : descs.descriptors())
+            registerUserType(desc.clsName, desc.idMapper, desc.serializer, desc.affKeyFieldName, desc.useTs,
+                             desc.metadataEnabled, desc.keepDeserialized);
+    }
+
+    /**
+     * @param pkgName Package name.
+     * @return Class names.
+     */
+    @SuppressWarnings("ConstantConditions")
+    private static Iterable<String> classesInPackage(String pkgName) {
+        assert pkgName != null;
+
+        Collection<String> clsNames = new ArrayList<>();
+
+        ClassLoader ldr = U.gridClassLoader();
+
+        if (ldr instanceof URLClassLoader) {
+            String pkgPath = pkgName.replaceAll("\\.", "/");
+
+            URL[] urls = ((URLClassLoader)ldr).getURLs();
+
+            for (URL url : urls) {
+                String proto = url.getProtocol().toLowerCase();
+
+                if ("file".equals(proto)) {
+                    try {
+                        File cpElement = new File(url.toURI());
+
+                        if (cpElement.isDirectory()) {
+                            File pkgDir = new File(cpElement, pkgPath);
+
+                            if (pkgDir.isDirectory()) {
+                                for (File file : pkgDir.listFiles()) {
+                                    String fileName = file.getName();
+
+                                    if (file.isFile() && fileName.toLowerCase().endsWith(".class"))
+                                        clsNames.add(pkgName + '.' + fileName.substring(0, fileName.length() - 6));
+                                }
+                            }
+                        }
+                        else if (cpElement.isFile()) {
+                            try {
+                                JarFile jar = new JarFile(cpElement);
+
+                                Enumeration<JarEntry> entries = jar.entries();
+
+                                while (entries.hasMoreElements()) {
+                                    String entry = entries.nextElement().getName();
+
+                                    if (entry.startsWith(pkgPath) && entry.endsWith(".class")) {
+                                        String clsName = entry.substring(pkgPath.length() + 1, entry.length() - 6);
+
+                                        if (!clsName.contains("/") && !clsName.contains("\\"))
+                                            clsNames.add(pkgName + '.' + clsName);
+                                    }
+                                }
+                            }
+                            catch (IOException ignored) {
+                                // No-op.
+                            }
+                        }
+                    }
+                    catch (URISyntaxException ignored) {
+                        // No-op.
+                    }
+                }
+            }
+        }
+
+        return clsNames;
+    }
+
+    /**
+     * @param cls Class.
+     * @return Class descriptor.
+     * @throws PortableException In case of error.
+     */
+    public PortableClassDescriptor descriptorForClass(Class<?> cls)
+        throws PortableException {
+        assert cls != null;
+
+        PortableClassDescriptor desc = descByCls.get(cls);
+
+        if (desc == null || !desc.isRegistered())
+            desc = registerClassDescriptor(cls);
+
+        return desc;
+    }
+
+    /**
+     * @param userType User type or not.
+     * @param typeId Type ID.
+     * @param ldr Class loader.
+     * @return Class descriptor.
+     */
+    public PortableClassDescriptor descriptorForTypeId(boolean userType, int typeId, ClassLoader ldr) {
+        assert typeId != GridPortableMarshaller.UNREGISTERED_TYPE_ID;
+
+        PortableClassDescriptor desc = userType ? userTypes.get(typeId) : predefinedTypes.get(typeId);
+
+        if (desc != null)
+            return desc;
+
+        Class cls;
+
+        try {
+            cls = marshCtx.getClass(typeId, ldr);
+
+            desc = descByCls.get(cls);
+        }
+        catch (ClassNotFoundException e) {
+            throw new PortableInvalidClassException(e);
+        }
+        catch (IgniteCheckedException e) {
+            throw new PortableException("Failed resolve class for ID: " + typeId, e);
+        }
+
+        if (desc == null) {
+            desc = registerClassDescriptor(cls);
+
+            assert desc.typeId() == typeId;
+        }
+
+        return desc;
+    }
+
+    /**
+     * Creates and registers {@link PortableClassDescriptor} for the given {@code class}.
+     *
+     * @param cls Class.
+     * @return Class descriptor.
+     */
+    private PortableClassDescriptor registerClassDescriptor(Class<?> cls) {
+        PortableClassDescriptor desc;
+
+        String clsName = cls.getName();
+
+        if (marshCtx.isSystemType(clsName)) {
+            desc = new PortableClassDescriptor(this,
+                cls,
+                false,
+                clsName.hashCode(),
+                clsName,
+                BASIC_CLS_ID_MAPPER,
+                null,
+                marsh.isUseTimestamp(),
+                marsh.isMetaDataEnabled(),
+                marsh.isKeepDeserialized());
+
+            PortableClassDescriptor old = descByCls.putIfAbsent(cls, desc);
+
+            if (old != null)
+                desc = old;
+        }
+        else
+            desc = registerUserClassDescriptor(cls);
+
+        return desc;
+    }
+
+    /**
+     * Creates and registers {@link PortableClassDescriptor} for the given user {@code class}.
+     *
+     * @param cls Class.
+     * @return Class descriptor.
+     */
+    private PortableClassDescriptor registerUserClassDescriptor(Class<?> cls) {
+        PortableClassDescriptor desc;
+
+        boolean registered;
+
+        String typeName = typeName(cls.getName());
+
+        PortableIdMapper idMapper = idMapper(typeName);
+
+        int typeId = idMapper.typeId(typeName);
+
+        try {
+            registered = marshCtx.registerClass(typeId, cls);
+
+        } catch (IgniteCheckedException e) {
+            throw new PortableException("Failed to register class.", e);
+        }
+
+        desc = new PortableClassDescriptor(this,
+            cls,
+            true,
+            typeId,
+            typeName,
+            idMapper,
+            null,
+            marsh.isUseTimestamp(),
+            marsh.isMetaDataEnabled(),
+            marsh.isKeepDeserialized(),
+            registered);
+
+        // perform put() instead of putIfAbsent() because "registered" flag may have been changed.
+        userTypes.put(typeId, desc);
+        descByCls.put(cls, desc);
+
+        return desc;
+    }
+
+    /**
+     * @param cls Collection class.
+     * @return Collection type ID.
+     */
+    public byte collectionType(Class<? extends Collection> cls) {
+        assert cls != null;
+
+        Byte type = colTypes.get(cls);
+
+        if (type != null)
+            return type;
+
+        return Set.class.isAssignableFrom(cls) ? GridPortableMarshaller.USER_SET : GridPortableMarshaller.USER_COL;
+    }
+
+    /**
+     * @param cls Map class.
+     * @return Map type ID.
+     */
+    public byte mapType(Class<? extends Map> cls) {
+        assert cls != null;
+
+        Byte type = mapTypes.get(cls);
+
+        return type != null ? type : GridPortableMarshaller.USER_COL;
+    }
+
+    /**
+     * @param typeName Type name.
+     * @return Type ID.
+     */
+    public int typeId(String typeName) {
+        int id;
+
+        if (marshCtx.isSystemType(typeName))
+            id = typeName.hashCode();
+
+        else {
+            typeName = typeName(typeName);
+
+            id = idMapper(typeName).typeId(typeName);
+        }
+
+        return id;
+    }
+
+    /**
+     * @param cls Class.
+     * @return Type ID.
+     * @throws PortableException In case of error.
+     */
+    public Type typeId(Class cls) throws PortableException {
+        String clsName = cls.getName();
+
+        if (marshCtx.isSystemType(clsName))
+            return new Type(clsName.hashCode(), true);
+
+        if (predefinedClasses.contains(cls))
+            return new Type(DFLT_ID_MAPPER.typeId(typeName(clsName)), true);
+
+        PortableClassDescriptor desc = descByCls.get(cls);
+
+        boolean registered = desc != null && desc.isRegistered();
+
+        if (!registered)
+            // forces to register the class and fill up all required data structures
+            desc = registerUserClassDescriptor(cls);
+
+        return new Type(desc.typeId(), desc.isRegistered());
+    }
+
+    /**
+     * @param typeId Type ID.
+     * @param fieldName Field name.
+     * @return Field ID.
+     */
+    public int fieldId(int typeId, String fieldName) {
+        return idMapper(typeId).fieldId(typeId, fieldName);
+    }
+
+    /**
+     * @param typeId Type ID.
+     * @return Instance of ID mapper.
+     */
+    public PortableIdMapper idMapper(int typeId) {
+        PortableIdMapper idMapper = mappers.get(typeId);
+
+        if (idMapper != null)
+            return idMapper;
+
+        if (userTypes.containsKey(typeId) || predefinedTypes.containsKey(typeId))
+            return DFLT_ID_MAPPER;
+
+        return BASIC_CLS_ID_MAPPER;
+    }
+
+    /**
+     * @param typeName Type name.
+     * @return Instance of ID mapper.
+     */
+    private PortableIdMapper idMapper(String typeName) {
+        PortableIdMapper idMapper = typeMappers.get(typeName);
+
+        return idMapper != null ? idMapper : DFLT_ID_MAPPER;
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeExternal(ObjectOutput out) throws IOException {
+        U.writeString(out, gridName);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
+        gridName = U.readString(in);
+    }
+
+    /**
+     * @return Portable context.
+     * @throws ObjectStreamException In case of error.
+     */
+    protected Object readResolve() throws ObjectStreamException {
+        try {
+            IgniteKernal g = IgnitionEx.gridx(gridName);
+
+            if (g == null)
+                throw new IllegalStateException("Failed to find grid for name: " + gridName);
+
+            return ((CacheObjectPortableProcessorImpl)g.context().cacheObjects()).portableContext();
+        }
+        catch (IllegalStateException e) {
+            throw U.withCause(new InvalidObjectException(e.getMessage()), e);
+        }
+    }
+
+    /**
+     * @param cls Class.
+     * @param id Type ID.
+     * @return PortableClassDescriptor.
+     */
+    private PortableClassDescriptor registerPredefinedType(Class<?> cls, int id) {
+        PortableClassDescriptor desc = new PortableClassDescriptor(
+            this,
+            cls,
+            false,
+            id,
+            typeName(cls.getName()),
+            DFLT_ID_MAPPER,
+            null,
+            false,
+            false,
+            false
+        );
+
+        predefinedClasses.add(cls);
+
+        predefinedTypes.put(id, desc);
+        descByCls.put(cls, desc);
+
+        return desc;
+    }
+
+    /**
+     * @param clsName Class name.
+     * @param idMapper ID mapper.
+     * @param serializer Serializer.
+     * @param affKeyFieldName Affinity key field name.
+     * @param useTs Use timestamp flag.
+     * @param metaDataEnabled Metadata enabled flag.
+     * @param keepDeserialized Keep deserialized flag.
+     * @throws PortableException In case of error.
+     */
+    @SuppressWarnings("ErrorNotRethrown")
+    public void registerUserType(String clsName,
+        PortableIdMapper idMapper,
+        @Nullable PortableSerializer serializer,
+        @Nullable String affKeyFieldName,
+        boolean useTs,
+        boolean metaDataEnabled,
+        boolean keepDeserialized)
+        throws PortableException {
+        assert idMapper != null;
+
+        Class<?> cls = null;
+
+        try {
+            cls = Class.forName(clsName);
+        }
+        catch (ClassNotFoundException | NoClassDefFoundError ignored) {
+            // No-op.
+        }
+
+        int id = idMapper.typeId(clsName);
+
+        if (mappers.put(id, idMapper) != null)
+            throw new PortableException("Duplicate type ID [clsName=" + clsName + ", id=" + id + ']');
+
+        if (useTs)
+            usingTs.add(id);
+
+        String typeName = typeName(clsName);
+
+        typeMappers.put(typeName, idMapper);
+
+        metaEnabled.put(id, metaDataEnabled);
+
+        Map<String, String> fieldsMeta = null;
+
+        if (cls != null) {
+            PortableClassDescriptor desc = new PortableClassDescriptor(
+                this,
+                cls,
+                true,
+                id,
+                typeName,
+                idMapper,
+                serializer,
+                useTs,
+                metaDataEnabled,
+                keepDeserialized);
+
+            fieldsMeta = desc.fieldsMeta();
+
+            userTypes.put(id, desc);
+            descByCls.put(cls, desc);
+        }
+
+        metaHnd.addMeta(id, new PortableMetaDataImpl(typeName, fieldsMeta, affKeyFieldName));
+    }
+
+    /**
+     * @param typeId Type ID.
+     * @return Meta data.
+     * @throws PortableException In case of error.
+     */
+    @Nullable public PortableMetadata metaData(int typeId) throws PortableException {
+        return metaHnd != null ? metaHnd.metadata(typeId) : null;
+    }
+
+    /**
+     * @return Whether meta data is globally enabled.
+     */
+    boolean isMetaDataEnabled() {
+        return marsh.isMetaDataEnabled();
+    }
+
+    /**
+     * @param typeId Type ID.
+     * @return Whether meta data is enabled.
+     */
+    boolean isMetaDataEnabled(int typeId) {
+        Boolean enabled = metaEnabled.get(typeId);
+
+        return enabled != null ? enabled : true;
+    }
+
+    /**
+     * @param typeId Type ID.
+     * @param metaHashSum Meta data hash sum.
+     * @return Whether meta is changed.
+     */
+    boolean isMetaDataChanged(int typeId, @Nullable Integer metaHashSum) {
+        if (metaHashSum == null)
+            return false;
+
+        Collection<Integer> hist = metaDataCache.get(typeId);
+
+        if (hist == null) {
+            Collection<Integer> old = metaDataCache.putIfAbsent(typeId, hist = new GridConcurrentHashSet<>());
+
+            if (old != null)
+                hist = old;
+        }
+
+        return hist.add(metaHashSum);
+    }
+
+    /**
+     * @param typeId Type ID.
+     * @param typeName Type name.
+     * @param fields Fields map.
+     * @throws PortableException In case of error.
+     */
+    void updateMetaData(int typeId, String typeName, Map<String, String> fields) throws PortableException {
+        updateMetaData(typeId, new PortableMetaDataImpl(typeName, fields, null));
+    }
+
+    /**
+     * @param typeId Type ID.
+     * @param meta Meta data.
+     * @throws PortableException In case of error.
+     */
+    public void updateMetaData(int typeId, PortableMetaDataImpl meta) throws PortableException {
+        metaHnd.addMeta(typeId, meta);
+    }
+
+    /**
+     * @return Use timestamp flag.
+     */
+    public boolean isUseTimestamp() {
+        return marsh.isUseTimestamp();
+    }
+
+    /**
+     * @param typeId Type ID.
+     * @return If timestamp used.
+     */
+    public boolean isUseTimestamp(int typeId) {
+        return usingTs.contains(typeId);
+    }
+
+    /**
+     * @return Whether to convert string to UTF8 bytes.
+     */
+    public boolean isConvertString() {
+        return marsh.isConvertStringToBytes();
+    }
+
+    /**
+     * Returns whether {@code cls} is predefined in the context or not.
+     *
+     * @param cls Class.
+     * @return {@code true} if predefined, {@code false} otherwise.
+     */
+    public boolean isPredefinedClass(Class<?> cls) {
+        return predefinedClasses.contains(cls);
+    }
+
+    /**
+     * Returns instance of {@link OptimizedMarshaller}.
+     *
+     * @return Optimized marshaller.
+     */
+    OptimizedMarshaller optimizedMarsh() {
+        return optmMarsh;
+    }
+
+    /**
+     * @param clsName Class name.
+     * @return Type name.
+     */
+    public static String typeName(String clsName) {
+        assert clsName != null;
+
+        int idx = clsName.lastIndexOf('$');
+
+        String typeName;
+
+        if (idx >= 0) {
+            typeName = clsName.substring(idx + 1);
+
+            try {
+                Integer.parseInt(typeName);
+
+                // This is an anonymous class. Don't cut off enclosing class name for it.
+                idx = -1;
+            }
+            catch (NumberFormatException e) {
+                return typeName;
+            }
+        }
+
+        if (idx < 0)
+            idx = clsName.lastIndexOf('.');
+
+        return idx >= 0 ? clsName.substring(idx + 1) : clsName;
+    }
+
+    /**
+     * @param str String.
+     * @return Hash code for given string converted to lower case.
+     */
+    private static int lowerCaseHashCode(String str) {
+        int len = str.length();
+
+        int h = 0;
+
+        for (int i = 0; i < len; i++) {
+            int c = str.charAt(i);
+
+            c = c <= MAX_LOWER_CASE_CHAR ? LOWER_CASE_CHARS[c] : Character.toLowerCase(c);
+
+            h = 31 * h + c;
+        }
+
+        return h;
+    }
+
+    /**
+     */
+    private static class IdMapperWrapper implements PortableIdMapper {
+        /** */
+        private final PortableIdMapper mapper;
+
+        /**
+         * @param mapper Custom ID mapper.
+         */
+        private IdMapperWrapper(@Nullable PortableIdMapper mapper) {
+            this.mapper = mapper;
+        }
+
+        /** {@inheritDoc} */
+        @Override public int typeId(String clsName) {
+            int id = 0;
+
+            if (mapper != null)
+                id = mapper.typeId(clsName);
+
+            return id != 0 ? id : lowerCaseHashCode(typeName(clsName));
+        }
+
+        /** {@inheritDoc} */
+        @Override public int fieldId(int typeId, String fieldName) {
+            int id = 0;
+
+            if (mapper != null)
+                id = mapper.fieldId(typeId, fieldName);
+
+            return id != 0 ? id : lowerCaseHashCode(fieldName);
+        }
+    }
+
+    private static class BasicClassIdMapper implements PortableIdMapper {
+        /** {@inheritDoc} */
+        @Override public int typeId(String clsName) {
+            return clsName.hashCode();
+        }
+
+        /** {@inheritDoc} */
+        @Override public int fieldId(int typeId, String fieldName) {
+            return lowerCaseHashCode(fieldName);
+        }
+    }
+    /**
+     * Type descriptors.
+     */
+    private static class TypeDescriptors {
+        /** Descriptors map. */
+        private final Map<String, TypeDescriptor> descs = new HashMap<>();
+
+        /**
+         * Add type descriptor.
+         *
+         * @param clsName Class name.
+         * @param idMapper ID mapper.
+         * @param serializer Serializer.
+         * @param affKeyFieldName Affinity key field name.
+         * @param useTs Use timestamp flag.
+         * @param metadataEnabled Metadata enabled flag.
+         * @param keepDeserialized Keep deserialized flag.
+         * @param canOverride Whether this descriptor can be override.
+         * @throws PortableException If failed.
+         */
+        private void add(String clsName,
+            PortableIdMapper idMapper,
+            PortableSerializer serializer,
+            String affKeyFieldName,
+            boolean useTs,
+            boolean metadataEnabled,
+            boolean keepDeserialized,
+            boolean canOverride)
+            throws PortableException {
+            TypeDescriptor desc = new TypeDescriptor(clsName,
+                idMapper,
+                serializer,
+                affKeyFieldName,
+                useTs,
+                metadataEnabled,
+                keepDeserialized,
+                canOverride);
+
+            TypeDescriptor oldDesc = descs.get(clsName);
+
+            if (oldDesc == null)
+                descs.put(clsName, desc);
+            else
+                oldDesc.override(desc);
+        }
+
+        /**
+         * Get all collected descriptors.
+         *
+         * @return Descriptors.
+         */
+        private Iterable<TypeDescriptor> descriptors() {
+            return descs.values();
+        }
+    }
+
+    /**
+     * Type descriptor.
+     */
+    private static class TypeDescriptor {
+        /** Class name. */
+        private final String clsName;
+
+        /** ID mapper. */
+        private PortableIdMapper idMapper;
+
+        /** Serializer. */
+        private PortableSerializer serializer;
+
+        /** Affinity key field name. */
+        private String affKeyFieldName;
+
+        /** Use timestamp flag. */
+        private boolean useTs;
+
+        /** Metadata enabled flag. */
+        private boolean metadataEnabled;
+
+        /** Keep deserialized flag. */
+        private boolean keepDeserialized;
+
+        /** Whether this descriptor can be override. */
+        private boolean canOverride;
+
+        /**
+         * Constructor.
+         *
+         * @param clsName Class name.
+         * @param idMapper ID mapper.
+         * @param serializer Serializer.
+         * @param affKeyFieldName Affinity key field name.
+         * @param useTs Use timestamp flag.
+         * @param metadataEnabled Metadata enabled flag.
+         * @param keepDeserialized Keep deserialized flag.
+         * @param canOverride Whether this descriptor can be override.
+         */
+        private TypeDescriptor(String clsName, PortableIdMapper idMapper, PortableSerializer serializer,
+            String affKeyFieldName, boolean useTs, boolean metadataEnabled, boolean keepDeserialized,
+            boolean canOverride) {
+            this.clsName = clsName;
+            this.idMapper = idMapper;
+            this.serializer = serializer;
+            this.affKeyFieldName = affKeyFieldName;
+            this.useTs = useTs;
+            this.metadataEnabled = metadataEnabled;
+            this.keepDeserialized = keepDeserialized;
+            this.canOverride = canOverride;
+        }
+
+        /**
+         * Override portable class descriptor.
+         *
+         * @param other Other descriptor.
+         * @throws PortableException If failed.
+         */
+        private void override(TypeDescriptor other) throws PortableException {
+            assert clsName.equals(other.clsName);
+
+            if (canOverride) {
+                idMapper = other.idMapper;
+                serializer = other.serializer;
+                affKeyFieldName = other.affKeyFieldName;
+                useTs = other.useTs;
+                metadataEnabled = other.metadataEnabled;
+                keepDeserialized = other.keepDeserialized;
+                canOverride = other.canOverride;
+            }
+            else if (!other.canOverride)
+                throw new PortableException("Duplicate explicit class definition in configuration: " + clsName);
+        }
+    }
+
+    /**
+     * Type id wrapper.
+     */
+    static class Type {
+        /** Type id*/
+        private int id;
+
+        /** Whether the following type is registered in a cache or not */
+        private boolean registered;
+
+        public Type(int id, boolean registered) {
+            this.id = id;
+            this.registered = registered;
+        }
+
+        public int id() {
+            return id;
+        }
+
+        public boolean registered() {
+            return registered;
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableEnumArrayLazyValue.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableEnumArrayLazyValue.java b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableEnumArrayLazyValue.java
new file mode 100644
index 0000000..7fa04e8
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableEnumArrayLazyValue.java
@@ -0,0 +1,111 @@
+/*
+ * 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.portable;
+
+import org.apache.ignite.internal.util.typedef.internal.*;
+import org.apache.ignite.portable.*;
+
+/**
+ *
+ */
+class PortableEnumArrayLazyValue extends PortableAbstractLazyValue {
+    /** */
+    private final int len;
+
+    /** */
+    private final int compTypeId;
+
+    /** */
+    private final String clsName;
+
+    /**
+     * @param reader Reader.
+     */
+    protected PortableEnumArrayLazyValue(PortableBuilderReader reader) {
+        super(reader, reader.position() - 1);
+
+        int typeId = reader.readInt();
+
+        if (typeId == GridPortableMarshaller.UNREGISTERED_TYPE_ID) {
+            clsName = reader.readString();
+
+            Class cls;
+
+            try {
+                // TODO: IGNITE-1272 - Is class loader needed here?
+                cls = U.forName(reader.readString(), null);
+            }
+            catch (ClassNotFoundException e) {
+                throw new PortableInvalidClassException("Failed to load the class: " + clsName, e);
+            }
+
+            compTypeId = reader.portableContext().descriptorForClass(cls).typeId();
+        }
+        else {
+            compTypeId = typeId;
+            clsName = null;
+        }
+
+        int size = reader.readInt();
+
+        for (int i = 0; i < size; i++)
+            reader.skipValue();
+
+        len = reader.position() - valOff;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected Object init() {
+        reader.position(valOff + 1);
+
+        //skipping component type id
+        reader.readInt();
+
+        int size = reader.readInt();
+
+        PortableBuilderEnum[] res = new PortableBuilderEnum[size];
+
+        for (int i = 0; i < size; i++) {
+            byte flag = reader.readByte();
+
+            if (flag == GridPortableMarshaller.NULL)
+                continue;
+
+            if (flag != GridPortableMarshaller.ENUM)
+                throw new PortableException("Invalid flag value: " + flag);
+
+            res[i] = new PortableBuilderEnum(reader);
+        }
+
+        return res;
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeTo(PortableWriterExImpl writer, PortableBuilderSerializer ctx) {
+        if (val != null) {
+            if (clsName != null)
+                ctx.writeArray(writer, GridPortableMarshaller.ENUM_ARR, (Object[])val, clsName);
+            else
+                ctx.writeArray(writer, GridPortableMarshaller.ENUM_ARR, (Object[])val, compTypeId);
+
+            return;
+        }
+
+        writer.write(reader.array(), valOff, len);
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableLazyArrayList.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableLazyArrayList.java b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableLazyArrayList.java
new file mode 100644
index 0000000..56dfba9
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableLazyArrayList.java
@@ -0,0 +1,156 @@
+/*
+ * 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.portable;
+
+import java.util.*;
+
+/**
+ *
+ */
+class PortableLazyArrayList extends AbstractList<Object> implements PortableBuilderSerializationAware {
+    /** */
+    private final PortableBuilderReader reader;
+
+    /** */
+    private final int off;
+
+    /** */
+    private List<Object> delegate;
+
+    /**
+     * @param reader Reader.
+     * @param size Size,
+     */
+    PortableLazyArrayList(PortableBuilderReader reader, int size) {
+        this.reader = reader;
+        off = reader.position() - 1/* flag */ - 4/* size */ - 1/* col type */;
+
+        assert size >= 0;
+
+        for (int i = 0; i < size; i++)
+            reader.skipValue();
+    }
+
+    /**
+     *
+     */
+    private void ensureDelegateInit() {
+        if (delegate == null) {
+            int size = reader.readIntAbsolute(off + 1);
+
+            reader.position(off + 1/* flag */ + 4/* size */ + 1/* col type */);
+
+            delegate = new ArrayList<>(size);
+
+            for (int i = 0; i < size; i++)
+                delegate.add(reader.parseValue());
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override public Object get(int idx) {
+        ensureDelegateInit();
+
+        return PortableUtils.unwrapLazy(delegate.get(idx));
+    }
+
+    /** {@inheritDoc} */
+    @Override public boolean add(Object o) {
+        ensureDelegateInit();
+
+        return delegate.add(o);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void add(int idx, Object element) {
+        ensureDelegateInit();
+
+        delegate.add(idx, element);
+    }
+
+    /** {@inheritDoc} */
+    @Override public Object set(int idx, Object element) {
+        ensureDelegateInit();
+
+        return PortableUtils.unwrapLazy(delegate.set(idx, element));
+    }
+
+    /** {@inheritDoc} */
+    @Override public Object remove(int idx) {
+        ensureDelegateInit();
+
+        return PortableUtils.unwrapLazy(delegate.remove(idx));
+    }
+
+    /** {@inheritDoc} */
+    @Override public void clear() {
+        if (delegate == null)
+            delegate = new ArrayList<>();
+        else
+            delegate.clear();
+    }
+
+    /** {@inheritDoc} */
+    @Override public boolean addAll(int idx, Collection<?> c) {
+        return delegate.addAll(idx, c);
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void removeRange(int fromIdx, int toIdx) {
+        ensureDelegateInit();
+
+        delegate.subList(fromIdx, toIdx).clear();
+    }
+
+    /** {@inheritDoc} */
+    @Override public int size() {
+        if (delegate == null)
+            return reader.readIntAbsolute(off + 1);
+
+        return delegate.size();
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeTo(PortableWriterExImpl writer, PortableBuilderSerializer ctx) {
+        if (delegate == null) {
+            int size = reader.readIntAbsolute(off + 1);
+
+            int hdrSize = 1 /* flag */ + 4 /* size */ + 1 /* col type */;
+
+            writer.write(reader.array(), off, hdrSize);
+
+            reader.position(off + hdrSize);
+
+            for (int i = 0; i < size; i++) {
+                Object o = reader.parseValue();
+
+                ctx.writeValue(writer, o);
+            }
+        }
+        else {
+            writer.writeByte(GridPortableMarshaller.COL);
+            writer.writeInt(delegate.size());
+
+            byte colType = reader.array()[off + 1 /* flag */ + 4 /* size */];
+            writer.writeByte(colType);
+
+            for (Object o : delegate)
+                ctx.writeValue(writer, o);
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableLazyLinkedList.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableLazyLinkedList.java b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableLazyLinkedList.java
new file mode 100644
index 0000000..9395aeb
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableLazyLinkedList.java
@@ -0,0 +1,210 @@
+/*
+ * 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.portable;
+
+import java.util.*;
+
+/**
+ *
+ */
+class PortableLazyLinkedList extends AbstractList<Object> implements PortableBuilderSerializationAware {
+    /** */
+    private final PortableBuilderReader reader;
+
+    /** */
+    private final int off;
+
+    /** */
+    private List<Object> delegate;
+
+    /**
+     * @param reader Reader.
+     * @param size Size,
+     */
+    PortableLazyLinkedList(PortableBuilderReader reader, int size) {
+        this.reader = reader;
+        off = reader.position() - 1/* flag */ - 4/* size */ - 1/* col type */;
+
+        assert size >= 0;
+
+        for (int i = 0; i < size; i++)
+            reader.skipValue();
+    }
+
+    /**
+     *
+     */
+    private void ensureDelegateInit() {
+        if (delegate == null) {
+            int size = reader.readIntAbsolute(off + 1);
+
+            reader.position(off + 1/* flag */ + 4/* size */ + 1/* col type */);
+
+            delegate = new LinkedList<>();
+
+            for (int i = 0; i < size; i++)
+                delegate.add(reader.parseValue());
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override public Object get(int idx) {
+        ensureDelegateInit();
+
+        return PortableUtils.unwrapLazy(delegate.get(idx));
+    }
+
+    /** {@inheritDoc} */
+    @Override public boolean add(Object o) {
+        ensureDelegateInit();
+
+        return delegate.add(o);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void add(int idx, Object element) {
+        ensureDelegateInit();
+
+        delegate.add(idx, element);
+    }
+
+    /** {@inheritDoc} */
+    @Override public Object set(int idx, Object element) {
+        ensureDelegateInit();
+
+        return PortableUtils.unwrapLazy(delegate.set(idx, element));
+    }
+
+    /** {@inheritDoc} */
+    @Override public Object remove(int idx) {
+        ensureDelegateInit();
+
+        return PortableUtils.unwrapLazy(delegate.remove(idx));
+    }
+
+    /** {@inheritDoc} */
+    @Override public void clear() {
+        if (delegate == null)
+            delegate = new LinkedList<>();
+        else
+            delegate.clear();
+    }
+
+    /** {@inheritDoc} */
+    @Override public boolean addAll(int idx, Collection<?> c) {
+        ensureDelegateInit();
+
+        return delegate.addAll(idx, c);
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void removeRange(int fromIdx, int toIdx) {
+        ensureDelegateInit();
+
+        delegate.subList(fromIdx, toIdx).clear();
+    }
+
+    /** {@inheritDoc} */
+    @Override public int size() {
+        if (delegate == null)
+            return reader.readIntAbsolute(off + 1);
+
+        return delegate.size();
+    }
+
+    /** {@inheritDoc} */
+    @Override public ListIterator<Object> listIterator(final int idx) {
+        ensureDelegateInit();
+
+        return new ListIterator<Object>() {
+            /** */
+            private final ListIterator<Object> delegate = PortableLazyLinkedList.super.listIterator(idx);
+
+            @Override public boolean hasNext() {
+                return delegate.hasNext();
+            }
+
+            @Override public Object next() {
+                return PortableUtils.unwrapLazy(delegate.next());
+            }
+
+            @Override public boolean hasPrevious() {
+                return delegate.hasPrevious();
+            }
+
+            @Override public Object previous() {
+                return PortableUtils.unwrapLazy(delegate.previous());
+            }
+
+            @Override public int nextIndex() {
+                return delegate.nextIndex();
+            }
+
+            @Override public int previousIndex() {
+                return delegate.previousIndex();
+            }
+
+            @Override public void remove() {
+                delegate.remove();
+            }
+
+            @Override public void set(Object o) {
+                delegate.set(o);
+            }
+
+            @Override public void add(Object o) {
+                delegate.add(o);
+            }
+        };
+    }
+
+    /** {@inheritDoc} */
+    @Override public Iterator<Object> iterator() {
+        ensureDelegateInit();
+
+        return PortableUtils.unwrapLazyIterator(super.iterator());
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeTo(PortableWriterExImpl writer, PortableBuilderSerializer ctx) {
+        if (delegate == null) {
+            int size = reader.readIntAbsolute(off + 1);
+
+            int hdrSize = 1 /* flag */ + 4 /* size */ + 1 /* col type */;
+            writer.write(reader.array(), off, hdrSize);
+
+            reader.position(off + hdrSize);
+
+            for (int i = 0; i < size; i++) {
+                Object o = reader.parseValue();
+
+                ctx.writeValue(writer, o);
+            }
+        }
+        else {
+            writer.writeByte(GridPortableMarshaller.COL);
+            writer.writeInt(delegate.size());
+
+            byte colType = reader.array()[off + 1 /* flag */ + 4 /* size */];
+            writer.writeByte(colType);
+
+            for (Object o : delegate)
+                ctx.writeValue(writer, o);
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableLazyMap.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableLazyMap.java b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableLazyMap.java
new file mode 100644
index 0000000..e7f7727
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableLazyMap.java
@@ -0,0 +1,214 @@
+/*
+ * 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.portable;
+
+import org.jetbrains.annotations.*;
+
+import java.util.*;
+
+/**
+ *
+ */
+class PortableLazyMap extends AbstractMap<Object, Object> implements PortableBuilderSerializationAware {
+    /** */
+    private final PortableBuilderReader reader;
+
+    /** */
+    private final int off;
+
+    /** */
+    private Map<Object, Object> delegate;
+
+    /**
+     * @param reader Reader.
+     * @param off Offset.
+     */
+    private PortableLazyMap(PortableBuilderReader reader, int off) {
+        this.reader = reader;
+        this.off = off;
+    }
+
+    /**
+     * @param reader Reader.
+     * @return PortableLazyMap.
+     */
+    @Nullable public static PortableLazyMap parseMap(PortableBuilderReader reader) {
+        int off = reader.position() - 1;
+
+        int size = reader.readInt();
+
+        reader.skip(1); // map type.
+
+        for (int i = 0; i < size; i++) {
+            reader.skipValue(); // skip key
+            reader.skipValue(); // skip value
+        }
+
+        return new PortableLazyMap(reader, off);
+    }
+
+    /**
+     *
+     */
+    private void ensureDelegateInit() {
+        if (delegate == null) {
+            int size = reader.readIntAbsolute(off + 1);
+
+            reader.position(off + 1/* flag */ + 4/* size */ + 1/* col type */);
+
+            delegate = new LinkedHashMap<>();
+
+            for (int i = 0; i < size; i++)
+                delegate.put(PortableUtils.unwrapLazy(reader.parseValue()), reader.parseValue());
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeTo(PortableWriterExImpl writer, PortableBuilderSerializer ctx) {
+        if (delegate == null) {
+            int size = reader.readIntAbsolute(off + 1);
+
+            int hdrSize = 1 /* flag */ + 4 /* size */ + 1 /* col type */;
+            writer.write(reader.array(), off, hdrSize);
+
+            reader.position(off + hdrSize);
+
+            for (int i = 0; i < size; i++) {
+                ctx.writeValue(writer, reader.parseValue()); // key
+                ctx.writeValue(writer, reader.parseValue()); // value
+            }
+        }
+        else {
+            writer.writeByte(GridPortableMarshaller.MAP);
+            writer.writeInt(delegate.size());
+
+            byte colType = reader.array()[off + 1 /* flag */ + 4 /* size */];
+
+            writer.writeByte(colType);
+
+            for (Entry<Object, Object> entry : delegate.entrySet()) {
+                ctx.writeValue(writer, entry.getKey());
+                ctx.writeValue(writer, entry.getValue());
+            }
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override public int size() {
+        if (delegate == null)
+            return reader.readIntAbsolute(off + 1);
+
+        return delegate.size();
+    }
+
+    /** {@inheritDoc} */
+    @Override public boolean containsKey(Object key) {
+        ensureDelegateInit();
+
+        return delegate.containsKey(key);
+    }
+
+    /** {@inheritDoc} */
+    @Override public boolean containsValue(Object val) {
+        return values().contains(val);
+    }
+
+    /** {@inheritDoc} */
+    @Override public Set<Object> keySet() {
+        ensureDelegateInit();
+
+        return delegate.keySet();
+    }
+
+    /** {@inheritDoc} */
+    @Override public void clear() {
+        if (delegate == null)
+            delegate = new LinkedHashMap<>();
+        else
+            delegate.clear();
+    }
+
+    /** {@inheritDoc} */
+    @Override public Object get(Object key) {
+        ensureDelegateInit();
+
+        return PortableUtils.unwrapLazy(delegate.get(key));
+    }
+
+    /** {@inheritDoc} */
+    @Override public Object put(Object key, Object val) {
+        ensureDelegateInit();
+
+        return PortableUtils.unwrapLazy(delegate.put(key, val));
+    }
+
+    /** {@inheritDoc} */
+    @Override public Object remove(Object key) {
+        ensureDelegateInit();
+
+        return PortableUtils.unwrapLazy(delegate.remove(key));
+    }
+
+    /** {@inheritDoc} */
+    @Override public Set<Entry<Object, Object>> entrySet() {
+        ensureDelegateInit();
+
+        return new AbstractSet<Entry<Object, Object>>() {
+            @Override public boolean contains(Object o) {
+                throw new UnsupportedOperationException();
+            }
+
+            @Override public Iterator<Entry<Object, Object>> iterator() {
+                return new Iterator<Entry<Object, Object>>() {
+                    /** */
+                    private final Iterator<Entry<Object, Object>> itr = delegate.entrySet().iterator();
+
+                    @Override public boolean hasNext() {
+                        return itr.hasNext();
+                    }
+
+                    @Override public Entry<Object, Object> next() {
+                        Entry<Object, Object> res = itr.next();
+
+                        final Object val = res.getValue();
+
+                        if (val instanceof PortableLazyValue) {
+                            return new SimpleEntry<Object, Object>(res.getKey(), val) {
+                                private static final long serialVersionUID = 0L;
+
+                                @Override public Object getValue() {
+                                    return ((PortableLazyValue)val).value();
+                                }
+                            };
+                        }
+
+                        return res;
+                    }
+
+                    @Override public void remove() {
+                        itr.remove();
+                    }
+                };
+            }
+
+            @Override public int size() {
+                return delegate.size();
+            }
+        };
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableLazyMapEntry.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableLazyMapEntry.java b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableLazyMapEntry.java
new file mode 100644
index 0000000..389ab33
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableLazyMapEntry.java
@@ -0,0 +1,66 @@
+/*
+ * 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.portable;
+
+import java.util.*;
+
+/**
+ *
+ */
+class PortableLazyMapEntry implements Map.Entry<Object, Object>, PortableBuilderSerializationAware {
+    /** */
+    private final Object key;
+
+    /** */
+    private Object val;
+
+    /**
+     * @param reader GridMutablePortableReader
+     */
+    PortableLazyMapEntry(PortableBuilderReader reader) {
+        key = reader.parseValue();
+        val = reader.parseValue();
+    }
+
+    /** {@inheritDoc} */
+    @Override public Object getKey() {
+        return PortableUtils.unwrapLazy(key);
+    }
+
+    /** {@inheritDoc} */
+    @Override public Object getValue() {
+        return PortableUtils.unwrapLazy(val);
+    }
+
+    /** {@inheritDoc} */
+    @Override public Object setValue(Object val) {
+        Object res = getValue();
+
+        this.val = val;
+
+        return res;
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeTo(PortableWriterExImpl writer, PortableBuilderSerializer ctx) {
+        writer.writeByte(GridPortableMarshaller.MAP_ENTRY);
+
+        ctx.writeValue(writer, key);
+        ctx.writeValue(writer, val);
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableLazySet.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableLazySet.java b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableLazySet.java
new file mode 100644
index 0000000..d5a59a0
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableLazySet.java
@@ -0,0 +1,89 @@
+/*
+ * 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.portable;
+
+import org.apache.ignite.internal.util.typedef.internal.*;
+
+import java.util.*;
+
+/**
+ *
+ */
+class PortableLazySet extends PortableAbstractLazyValue {
+    /** */
+    private final int off;
+
+    /**
+     * @param reader Reader.
+     * @param size Size.
+     */
+    PortableLazySet(PortableBuilderReader reader, int size) {
+        super(reader, reader.position() - 1);
+
+        off = reader.position() - 1/* flag */ - 4/* size */ - 1/* col type */;
+
+        assert size >= 0;
+
+        for (int i = 0; i < size; i++)
+            reader.skipValue();
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeTo(PortableWriterExImpl writer, PortableBuilderSerializer ctx) {
+        if (val == null) {
+            int size = reader.readIntAbsolute(off + 1);
+
+            int hdrSize = 1 /* flag */ + 4 /* size */ + 1 /* col type */;
+            writer.write(reader.array(), off, hdrSize);
+
+            reader.position(off + hdrSize);
+
+            for (int i = 0; i < size; i++) {
+                Object o = reader.parseValue();
+
+                ctx.writeValue(writer, o);
+            }
+        }
+        else {
+            Collection<Object> c = (Collection<Object>)val;
+
+            writer.writeByte(GridPortableMarshaller.COL);
+            writer.writeInt(c.size());
+
+            byte colType = reader.array()[off + 1 /* flag */ + 4 /* size */];
+            writer.writeByte(colType);
+
+            for (Object o : c)
+                ctx.writeValue(writer, o);
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override protected Object init() {
+        int size = reader.readIntAbsolute(off + 1);
+
+        reader.position(off + 1/* flag */ + 4/* size */ + 1/* col type */);
+
+        Set<Object> res = U.newLinkedHashSet(size);
+
+        for (int i = 0; i < size; i++)
+            res.add(PortableUtils.unwrapLazy(reader.parseValue()));
+
+        return res;
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableLazyValue.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableLazyValue.java b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableLazyValue.java
new file mode 100644
index 0000000..fcce4a5
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableLazyValue.java
@@ -0,0 +1,28 @@
+/*
+ * 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.portable;
+
+/**
+ *
+ */
+interface PortableLazyValue extends PortableBuilderSerializationAware {
+    /**
+     * @return Value.
+     */
+    public Object value();
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableMetaDataCollector.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableMetaDataCollector.java b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableMetaDataCollector.java
new file mode 100644
index 0000000..30978ad
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableMetaDataCollector.java
@@ -0,0 +1,253 @@
+/*
+ * 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.portable;
+
+import org.apache.ignite.portable.*;
+
+import org.jetbrains.annotations.*;
+
+import java.lang.reflect.*;
+import java.math.*;
+import java.sql.*;
+import java.util.*;
+import java.util.Date;
+
+/**
+ * Writer for meta data collection.
+ */
+class PortableMetaDataCollector implements PortableWriter {
+    /** */
+    private final Map<String, String> meta = new HashMap<>();
+
+    /** */
+    private final String typeName;
+
+    /**
+     * @param typeName Type name.
+     */
+    PortableMetaDataCollector(String typeName) {
+        this.typeName = typeName;
+    }
+
+    /**
+     * @return Field meta data.
+     */
+    Map<String, String> meta() {
+        return meta;
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeByte(String fieldName, byte val) throws PortableException {
+        add(fieldName, byte.class);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeShort(String fieldName, short val) throws PortableException {
+        add(fieldName, short.class);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeInt(String fieldName, int val) throws PortableException {
+        add(fieldName, int.class);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeLong(String fieldName, long val) throws PortableException {
+        add(fieldName, long.class);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeFloat(String fieldName, float val) throws PortableException {
+        add(fieldName, float.class);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeDouble(String fieldName, double val) throws PortableException {
+        add(fieldName, double.class);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeChar(String fieldName, char val) throws PortableException {
+        add(fieldName, char.class);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeBoolean(String fieldName, boolean val) throws PortableException {
+        add(fieldName, boolean.class);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeDecimal(String fieldName, @Nullable BigDecimal val) throws PortableException {
+        add(fieldName, PortableClassDescriptor.Mode.DECIMAL.typeName());
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeString(String fieldName, @Nullable String val) throws PortableException {
+        add(fieldName, String.class);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeUuid(String fieldName, @Nullable UUID val) throws PortableException {
+        add(fieldName, UUID.class);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeDate(String fieldName, @Nullable Date val) throws PortableException {
+        add(fieldName, Date.class);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeTimestamp(String fieldName, @Nullable Timestamp val) throws PortableException {
+        add(fieldName, Timestamp.class);
+    }
+
+    /** {@inheritDoc} */
+    @Override public <T extends Enum<?>> void writeEnum(String fieldName, T val) throws PortableException {
+        add(fieldName, Enum.class);
+    }
+
+    /** {@inheritDoc} */
+    @Override public <T extends Enum<?>> void writeEnumArray(String fieldName, T[] val) throws PortableException {
+        add(fieldName, Enum[].class);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeObject(String fieldName, @Nullable Object obj) throws PortableException {
+        add(fieldName, Object.class);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeByteArray(String fieldName, @Nullable byte[] val) throws PortableException {
+        add(fieldName, byte[].class);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeShortArray(String fieldName, @Nullable short[] val) throws PortableException {
+        add(fieldName, short[].class);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeIntArray(String fieldName, @Nullable int[] val) throws PortableException {
+        add(fieldName, int[].class);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeLongArray(String fieldName, @Nullable long[] val) throws PortableException {
+        add(fieldName, long[].class);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeFloatArray(String fieldName, @Nullable float[] val) throws PortableException {
+        add(fieldName, float[].class);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeDoubleArray(String fieldName, @Nullable double[] val) throws PortableException {
+        add(fieldName, double[].class);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeCharArray(String fieldName, @Nullable char[] val) throws PortableException {
+        add(fieldName, char[].class);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeBooleanArray(String fieldName, @Nullable boolean[] val) throws PortableException {
+        add(fieldName, boolean[].class);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeDecimalArray(String fieldName, @Nullable BigDecimal[] val) throws PortableException {
+        add(fieldName, PortableClassDescriptor.Mode.DECIMAL_ARR.typeName());
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeStringArray(String fieldName, @Nullable String[] val) throws PortableException {
+        add(fieldName, String[].class);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeUuidArray(String fieldName, @Nullable UUID[] val) throws PortableException {
+        add(fieldName, UUID[].class);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeDateArray(String fieldName, @Nullable Date[] val) throws PortableException {
+        add(fieldName, Date[].class);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeObjectArray(String fieldName, @Nullable Object[] val) throws PortableException {
+        add(fieldName, Object[].class);
+    }
+
+    /** {@inheritDoc} */
+    @Override public <T> void writeCollection(String fieldName, @Nullable Collection<T> col)
+        throws PortableException {
+        add(fieldName, Collection.class);
+    }
+
+    /** {@inheritDoc} */
+    @Override public <K, V> void writeMap(String fieldName, @Nullable Map<K, V> map) throws PortableException {
+        add(fieldName, Map.class);
+    }
+
+    /** {@inheritDoc} */
+    @Override public PortableRawWriter rawWriter() {
+        return (PortableRawWriter)Proxy.newProxyInstance(getClass().getClassLoader(),
+            new Class<?>[] { PortableRawWriterEx.class },
+            new InvocationHandler() {
+                @Override public Object invoke(Object proxy, Method mtd, Object[] args) throws Throwable {
+                    return null;
+                }
+            });
+    }
+
+    /**
+     * @param name Field name.
+     * @param fieldType Field type.
+     * @throws PortableException In case of error.
+     */
+    private void add(String name, Class<?> fieldType) throws PortableException {
+        assert fieldType != null;
+
+        add(name, fieldType.getSimpleName());
+    }
+
+    /**
+     * @param name Field name.
+     * @param fieldTypeName Field type name.
+     * @throws PortableException In case of error.
+     */
+    private void add(String name, String fieldTypeName) throws PortableException {
+        assert name != null;
+
+        String oldFieldTypeName = meta.put(name, fieldTypeName);
+
+        if (oldFieldTypeName != null && !oldFieldTypeName.equals(fieldTypeName)) {
+            throw new PortableException(
+                "Field is written twice with different types [" +
+                "typeName=" + typeName +
+                ", fieldName=" + name +
+                ", fieldTypeName1=" + oldFieldTypeName +
+                ", fieldTypeName2=" + fieldTypeName +
+                ']'
+            );
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableMetaDataHandler.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableMetaDataHandler.java b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableMetaDataHandler.java
new file mode 100644
index 0000000..e8154ab
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableMetaDataHandler.java
@@ -0,0 +1,43 @@
+/*
+ * 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.portable;
+
+import org.apache.ignite.portable.*;
+
+/**
+ * Portable meta data handler.
+ */
+public interface PortableMetaDataHandler {
+    /**
+     * Adds meta data.
+     *
+     * @param typeId Type ID.
+     * @param meta Meta data.
+     * @throws PortableException In case of error.
+     */
+    public void addMeta(int typeId, PortableMetadata meta) throws PortableException;
+
+    /**
+     * Gets meta data for provided type ID.
+     *
+     * @param typeId Type ID.
+     * @return Meta data.
+     * @throws PortableException In case of error.
+     */
+    public PortableMetadata metadata(int typeId) throws PortableException;
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableMetaDataImpl.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableMetaDataImpl.java b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableMetaDataImpl.java
new file mode 100644
index 0000000..697a981
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableMetaDataImpl.java
@@ -0,0 +1,140 @@
+/*
+ * 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.portable;
+
+import org.apache.ignite.internal.util.tostring.*;
+import org.apache.ignite.internal.util.typedef.internal.*;
+import org.apache.ignite.portable.*;
+
+import org.jetbrains.annotations.*;
+
+import java.io.*;
+import java.util.*;
+
+/**
+ * Portable meta data implementation.
+ */
+public class PortableMetaDataImpl implements PortableMetadata, PortableMarshalAware, Externalizable {
+    /** */
+    private static final long serialVersionUID = 0L;
+
+    /** */
+    private String typeName;
+
+    /** */
+    @GridToStringInclude
+    private Map<String, String> fields;
+
+    /** */
+    private volatile Map<Integer, String> fldIdToName;
+
+    /** */
+    private String affKeyFieldName;
+
+    /**
+     * For {@link Externalizable}.
+     */
+    public PortableMetaDataImpl() {
+        // No-op.
+    }
+
+    /**
+     * @param typeName Type name.
+     * @param fields Fields map.
+     * @param affKeyFieldName Affinity key field name.
+     */
+    public PortableMetaDataImpl(String typeName, @Nullable Map<String, String> fields,
+        @Nullable String affKeyFieldName) {
+        assert typeName != null;
+
+        this.typeName = typeName;
+        this.fields = fields;
+        this.affKeyFieldName = affKeyFieldName;
+    }
+
+    /** {@inheritDoc} */
+    @Override public String typeName() {
+        return typeName;
+    }
+
+    /** {@inheritDoc} */
+    @Override public Collection<String> fields() {
+        return fields != null ? fields.keySet() : Collections.<String>emptyList();
+    }
+
+    /**
+     * @return Fields.
+     */
+    public Map<String, String> fields0() {
+        return fields != null ? fields : Collections.<String, String>emptyMap();
+    }
+
+    /** {@inheritDoc} */
+    @Nullable @Override public String fieldTypeName(String fieldName) {
+        return fields != null ? fields.get(fieldName) : null;
+    }
+
+    /** {@inheritDoc} */
+    @Nullable @Override public String affinityKeyFieldName() {
+        return affKeyFieldName;
+    }
+
+    /**
+     * @return Fields meta data.
+     */
+    public Map<String, String> fieldsMeta() {
+        return fields != null ? fields : Collections.<String, String>emptyMap();
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeExternal(ObjectOutput out) throws IOException {
+        U.writeString(out, typeName);
+        U.writeMap(out, fields);
+        U.writeString(out, affKeyFieldName);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
+        typeName = U.readString(in);
+        fields = U.readMap(in);
+        affKeyFieldName = U.readString(in);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writePortable(PortableWriter writer) throws PortableException {
+        PortableRawWriter raw = writer.rawWriter();
+
+        raw.writeString(typeName);
+        raw.writeString(affKeyFieldName);
+        raw.writeMap(fields);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void readPortable(PortableReader reader) throws PortableException {
+        PortableRawReader raw = reader.rawReader();
+
+        typeName = raw.readString();
+        affKeyFieldName = raw.readString();
+        fields = raw.readMap();
+    }
+
+    /** {@inheritDoc} */
+    @Override public String toString() {
+        return S.toString(PortableMetaDataImpl.class, this);
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableObjectArrayLazyValue.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableObjectArrayLazyValue.java b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableObjectArrayLazyValue.java
new file mode 100644
index 0000000..16038d9
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableObjectArrayLazyValue.java
@@ -0,0 +1,89 @@
+/*
+ * 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.portable;
+
+import org.apache.ignite.internal.util.typedef.internal.*;
+import org.apache.ignite.portable.*;
+
+/**
+ *
+ */
+class PortableObjectArrayLazyValue extends PortableAbstractLazyValue {
+    /** */
+    private Object[] lazyValsArr;
+
+    /** */
+    private int compTypeId;
+
+    /** */
+    private String clsName;
+
+    /**
+     * @param reader Reader.
+     */
+    protected PortableObjectArrayLazyValue(PortableBuilderReader reader) {
+        super(reader, reader.position() - 1);
+
+        int typeId = reader.readInt();
+
+        if (typeId == GridPortableMarshaller.UNREGISTERED_TYPE_ID) {
+            clsName = reader.readString();
+
+            Class cls;
+
+            try {
+                // TODO: IGNITE-1272 - Is class loader needed here?
+                cls = U.forName(reader.readString(), null);
+            }
+            catch (ClassNotFoundException e) {
+                throw new PortableInvalidClassException("Failed to load the class: " + clsName, e);
+            }
+
+            compTypeId = reader.portableContext().descriptorForClass(cls).typeId();
+        }
+        else {
+            compTypeId = typeId;
+            clsName = null;
+        }
+
+        int size = reader.readInt();
+
+        lazyValsArr = new Object[size];
+
+        for (int i = 0; i < size; i++)
+            lazyValsArr[i] = reader.parseValue();
+    }
+
+    /** {@inheritDoc} */
+    @Override protected Object init() {
+        for (int i = 0; i < lazyValsArr.length; i++) {
+            if (lazyValsArr[i] instanceof PortableLazyValue)
+                lazyValsArr[i] = ((PortableLazyValue)lazyValsArr[i]).value();
+        }
+
+        return lazyValsArr;
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeTo(PortableWriterExImpl writer, PortableBuilderSerializer ctx) {
+        if (clsName == null)
+            ctx.writeArray(writer, GridPortableMarshaller.OBJ_ARR, lazyValsArr, compTypeId);
+        else
+            ctx.writeArray(writer, GridPortableMarshaller.OBJ_ARR, lazyValsArr, clsName);
+    }
+}


[45/59] [abbrv] ignite git commit: IGNITE-1306: Moved "AbstractTarget" which is a root class for all basic platform classes to Ignite.

Posted by vk...@apache.org.
IGNITE-1306: Moved "AbstractTarget" which is a root class for all basic platform classes to Ignite.


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

Branch: refs/heads/ignite-884
Commit: 0e81fd0cd578ecaa6c57625f75abafa1118eccef
Parents: 9382118
Author: vozerov-gridgain <vo...@gridgain.com>
Authored: Wed Aug 26 13:35:30 2015 +0300
Committer: vozerov-gridgain <vo...@gridgain.com>
Committed: Wed Aug 26 13:35:30 2015 +0300

----------------------------------------------------------------------
 .../platform/PlatformAbstractBootstrap.java     |   1 +
 .../platform/PlatformAbstractTarget.java        | 276 +++++++++++++++++++
 2 files changed, 277 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/0e81fd0c/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/PlatformAbstractBootstrap.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/PlatformAbstractBootstrap.java b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/PlatformAbstractBootstrap.java
index 4db3c1e..39af1fa 100644
--- a/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/PlatformAbstractBootstrap.java
+++ b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/PlatformAbstractBootstrap.java
@@ -14,6 +14,7 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+
 package org.apache.ignite.internal.processors.platform;
 
 import org.apache.ignite.*;

http://git-wip-us.apache.org/repos/asf/ignite/blob/0e81fd0c/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/PlatformAbstractTarget.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/PlatformAbstractTarget.java b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/PlatformAbstractTarget.java
new file mode 100644
index 0000000..ec728e4
--- /dev/null
+++ b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/PlatformAbstractTarget.java
@@ -0,0 +1,276 @@
+/*
+ * 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.platform;
+
+import org.apache.ignite.*;
+import org.apache.ignite.internal.portable.*;
+import org.apache.ignite.internal.processors.platform.memory.*;
+import org.apache.ignite.internal.processors.platform.utils.*;
+import org.apache.ignite.lang.*;
+import org.jetbrains.annotations.*;
+
+/**
+ * Abstract interop target.
+ */
+public abstract class PlatformAbstractTarget implements PlatformTarget {
+    /** Constant: TRUE.*/
+    protected static final int TRUE = 1;
+
+    /** Constant: FALSE. */
+    protected static final int FALSE = 0;
+
+    /** */
+    private static final int OP_META = -1;
+
+    /** Interop context. */
+    protected final PlatformContext interopCtx;
+
+    /** Logger. */
+    protected final IgniteLogger log;
+
+    /**
+     * Constructor.
+     *
+     * @param interopCtx Interop context.
+     */
+    protected PlatformAbstractTarget(PlatformContext interopCtx) {
+        this.interopCtx = interopCtx;
+
+        log = interopCtx.kernalContext().log(PlatformAbstractTarget.class);
+    }
+
+    /** {@inheritDoc} */
+    @Override public int inOp(int type, long memPtr) throws Exception {
+        try (PlatformMemory mem = interopCtx.memory().get(memPtr)) {
+            PortableRawReaderEx reader = interopCtx.reader(mem);
+
+            if (type == OP_META) {
+                interopCtx.processMetadata(reader);
+
+                return TRUE;
+            }
+            else
+                return processInOp(type, reader);
+        }
+        catch (Exception e) {
+            throw convertException(e);
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override public Object inOpObject(int type, long memPtr) throws Exception {
+        try (PlatformMemory mem = interopCtx.memory().get(memPtr)) {
+            PortableRawReaderEx reader = interopCtx.reader(mem);
+
+            return processInOpObject(type, reader);
+        }
+        catch (Exception e) {
+            throw convertException(e);
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override public void outOp(int type, long memPtr) throws Exception {
+        try (PlatformMemory mem = interopCtx.memory().get(memPtr)) {
+            PlatformOutputStream out = mem.output();
+
+            PortableRawWriterEx writer = interopCtx.writer(out);
+
+            processOutOp(type, writer);
+
+            out.synchronize();
+        }
+        catch (Exception e) {
+            throw convertException(e);
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override public void inOutOp(int type, long inMemPtr, long outMemPtr) throws Exception {
+        inOutOp(type, inMemPtr, outMemPtr, null);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void inOutOp(int type, long inMemPtr, long outMemPtr, Object arg) throws Exception {
+        try (PlatformMemory inMem = interopCtx.memory().get(inMemPtr)) {
+            PortableRawReaderEx reader = interopCtx.reader(inMem);
+
+            try (PlatformMemory outMem = interopCtx.memory().get(outMemPtr)) {
+                PlatformOutputStream out = outMem.output();
+
+                PortableRawWriterEx writer = interopCtx.writer(out);
+
+                processInOutOp(type, reader, writer, arg);
+
+                out.synchronize();
+            }
+        }
+        catch (Exception e) {
+            throw convertException(e);
+        }
+    }
+
+    /**
+     * Convert caught exception.
+     *
+     * @param e Exception to convert.
+     * @return Converted exception.
+     */
+    protected Exception convertException(Exception e) {
+        return e;
+    }
+
+    /**
+     * @return Interop context.
+     */
+    public PlatformContext interopContext() {
+        return interopCtx;
+    }
+
+    /**
+     * Start listening for the future.
+     *
+     * @param futId Future ID.
+     * @param typ Result type.
+     */
+    @SuppressWarnings("UnusedDeclaration")
+    public void listenFuture(final long futId, int typ) throws IgniteCheckedException {
+        PlatformFutureUtils.listen(interopCtx, currentFutureWrapped(), futId, typ, null);
+    }
+
+    /**
+     * Start listening for the future.
+     *
+     * @param futId Future ID.
+     * @param typ Result type.
+     * @param opId Operation ID required to pick correct result writer.
+     */
+    @SuppressWarnings("UnusedDeclaration")
+    public void listenFuture(final long futId, int typ, int opId) throws IgniteCheckedException {
+        PlatformFutureUtils.listen(interopCtx, currentFutureWrapped(), futId, typ, futureWriter(opId));
+    }
+
+    /**
+     * Get current future with proper exception conversions.
+     *
+     * @return Future.
+     * @throws org.apache.ignite.IgniteCheckedException If failed.
+     */
+    @SuppressWarnings({"ThrowableResultOfMethodCallIgnored", "unchecked"})
+    protected IgniteFuture currentFutureWrapped() throws IgniteCheckedException {
+        return currentFuture().chain(new IgniteClosure<IgniteFuture, Object>() {
+            @Override public Object apply(IgniteFuture o) {
+                try {
+                    return o.get();
+                }
+                catch (RuntimeException e) {
+                    Exception converted = convertException(e);
+
+                    if (converted instanceof RuntimeException)
+                        throw (RuntimeException)converted;
+                    else {
+                        log.error("Interop future result cannot be obtained due to exception.", converted);
+
+                        throw new IgniteException("Interop future result cannot be obtained due to exception " +
+                            "(see log for more details).");
+                    }
+                }
+            }
+        });
+    }
+
+    /**
+     * When overridden in a derived class, gets future for the current operation.
+     *
+     * @return current future.
+     * @throws org.apache.ignite.IgniteCheckedException
+     */
+    protected IgniteFuture currentFuture() throws IgniteCheckedException {
+        throw new IgniteCheckedException("Future listening is not supported in " + this.getClass());
+    }
+
+    /**
+     * When overridden in a derived class, gets a custom future writer.
+     *
+     * @param opId Operation id.
+     * @return A custom writer for given op id.
+     */
+    protected @Nullable PlatformFutureUtils.Writer futureWriter(int opId){
+        return null;
+    }
+
+    /**
+     * Process IN operation.
+     *
+     * @param type Type.
+     * @param reader Portable reader.
+     * @return Result.
+     * @throws org.apache.ignite.IgniteCheckedException In case of exception.
+     */
+    protected int processInOp(int type, PortableRawReaderEx reader) throws IgniteCheckedException {
+        return throwUnsupported(type);
+    }
+
+    /**
+     * Process IN operation with managed object as result.
+     *
+     * @param type Type.
+     * @param reader Portable reader.
+     * @return Result.
+     * @throws org.apache.ignite.IgniteCheckedException In case of exception.
+     */
+    protected Object processInOpObject(int type, PortableRawReaderEx reader) throws IgniteCheckedException {
+        return throwUnsupported(type);
+    }
+
+    /**
+     * Process OUT operation.
+     *
+     * @param type Type.
+     * @param writer Portable writer.
+     * @throws org.apache.ignite.IgniteCheckedException In case of exception.
+     */
+    protected void processOutOp(int type, PortableRawWriterEx writer) throws IgniteCheckedException {
+        throwUnsupported(type);
+    }
+
+    /**
+     * Process IN-OUT operation.
+     *
+     * @param type Type.
+     * @param reader Portable reader.
+     * @param writer Portable writer.
+     * @param arg Argument.
+     * @throws org.apache.ignite.IgniteCheckedException In case of exception.
+     */
+    protected void processInOutOp(int type, PortableRawReaderEx reader, PortableRawWriterEx writer,
+        @Nullable Object arg) throws IgniteCheckedException {
+        throwUnsupported(type);
+    }
+
+    /**
+     * Throw an exception rendering unsupported operation type.
+     *
+     * @param type Operation type.
+     * @return Dummy value which is never returned.
+     * @throws org.apache.ignite.IgniteCheckedException Exception to be thrown.
+     */
+    protected <T> T throwUnsupported(int type) throws IgniteCheckedException {
+        throw new IgniteCheckedException("Unsupported operation type: " + type);
+    }
+}


[07/59] [abbrv] ignite git commit: ignite-1258: portable objects API support in Ignite

Posted by vk...@apache.org.
http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/portable/IgnitePortablesImpl.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/portable/IgnitePortablesImpl.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/portable/IgnitePortablesImpl.java
new file mode 100644
index 0000000..d819a56
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/portable/IgnitePortablesImpl.java
@@ -0,0 +1,176 @@
+/*
+ * 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.portable;
+
+import org.apache.ignite.*;
+import org.apache.ignite.internal.*;
+import org.apache.ignite.internal.processors.cacheobject.*;
+import org.apache.ignite.portable.*;
+
+import org.jetbrains.annotations.*;
+
+import java.util.*;
+
+/**
+ * {@link IgnitePortables} implementation.
+ */
+public class IgnitePortablesImpl implements IgnitePortables {
+    /** */
+    private GridKernalContext ctx;
+
+    /** */
+    private CacheObjectPortableProcessor proc;
+
+    /**
+     * @param ctx Context.
+     */
+    public IgnitePortablesImpl(GridKernalContext ctx, CacheObjectPortableProcessor proc) {
+        this.ctx = ctx;
+
+        this.proc = proc;
+    }
+
+    /** {@inheritDoc} */
+    @Override public int typeId(String typeName) {
+        guard();
+
+        try {
+            return proc.typeId(typeName);
+        }
+        finally {
+            unguard();
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override public <T> T toPortable(@Nullable Object obj) throws PortableException {
+        guard();
+
+        try {
+            return (T)proc.marshalToPortable(obj);
+        }
+        finally {
+            unguard();
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override public PortableBuilder builder(int typeId) {
+        guard();
+
+        try {
+            return proc.builder(typeId);
+        }
+        finally {
+            unguard();
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override public PortableBuilder builder(String typeName) {
+        guard();
+
+        try {
+            return proc.builder(typeName);
+        }
+        finally {
+            unguard();
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override public PortableBuilder builder(PortableObject portableObj) {
+        guard();
+
+        try {
+            return proc.builder(portableObj);
+        }
+        finally {
+            unguard();
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Nullable @Override public PortableMetadata metadata(Class<?> cls) throws PortableException {
+        guard();
+
+        try {
+            return proc.metadata(proc.typeId(cls.getName()));
+        }
+        finally {
+            unguard();
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Nullable @Override public PortableMetadata metadata(String typeName) throws PortableException {
+        guard();
+
+        try {
+            return proc.metadata(proc.typeId(typeName));
+        }
+        finally {
+            unguard();
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Nullable @Override public PortableMetadata metadata(int typeId) throws PortableException {
+        guard();
+
+        try {
+            return proc.metadata(typeId);
+        }
+        finally {
+            unguard();
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override public Collection<PortableMetadata> metadata() throws PortableException {
+        guard();
+
+        try {
+            return proc.metadata();
+        }
+        finally {
+            unguard();
+        }
+    }
+
+    /**
+     * @return Portable processor.
+     */
+    public IgniteCacheObjectProcessor processor() {
+        return proc;
+    }
+
+    /**
+     * <tt>ctx.gateway().readLock()</tt>
+     */
+    private void guard() {
+        ctx.gateway().readLock();
+    }
+
+    /**
+     * <tt>ctx.gateway().readUnlock()</tt>
+     */
+    private void unguard() {
+        ctx.gateway().readUnlock();
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/portable/PortableMetaDataKey.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/portable/PortableMetaDataKey.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/portable/PortableMetaDataKey.java
new file mode 100644
index 0000000..d2d53cd
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/portable/PortableMetaDataKey.java
@@ -0,0 +1,80 @@
+/*
+ * 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.portable;
+
+import org.apache.ignite.internal.processors.cache.*;
+import org.apache.ignite.internal.util.typedef.internal.*;
+
+import java.io.*;
+
+/**
+ * Key for portable meta data.
+ */
+class PortableMetaDataKey extends GridCacheUtilityKey<PortableMetaDataKey> implements Externalizable {
+    /** */
+    private static final long serialVersionUID = 0L;
+
+    /** */
+    private int typeId;
+
+    /**
+     * For {@link Externalizable}.
+     */
+    public PortableMetaDataKey() {
+        // No-op.
+    }
+
+    /**
+     * @param typeId Type ID.
+     */
+    PortableMetaDataKey(int typeId) {
+        this.typeId = typeId;
+    }
+
+    /**
+     * @return Type id.
+     */
+    public int typeId() {
+        return typeId;
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeExternal(ObjectOutput out) throws IOException {
+        out.writeInt(typeId);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
+        typeId = in.readInt();
+    }
+
+    /** {@inheritDoc} */
+    @Override protected boolean equalsx(PortableMetaDataKey key) {
+        return typeId == key.typeId;
+    }
+
+    /** {@inheritDoc} */
+    @Override public int hashCode() {
+        return typeId;
+    }
+
+    /** {@inheritDoc} */
+    @Override public String toString() {
+        return S.toString(PortableMetaDataKey.class, this);
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/portable/package-info.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/portable/package-info.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/portable/package-info.java
new file mode 100644
index 0000000..6c30811
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/portable/package-info.java
@@ -0,0 +1,22 @@
+/*
+ * 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 description. -->
+ * Implementation of portable processor.
+ */
+package org.apache.ignite.internal.processors.cache.portable;
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/store/CacheOsStoreManager.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/store/CacheOsStoreManager.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/store/CacheOsStoreManager.java
index 02fe679..f11df41 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/store/CacheOsStoreManager.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/store/CacheOsStoreManager.java
@@ -19,6 +19,7 @@ package org.apache.ignite.internal.processors.cache.store;
 
 import org.apache.ignite.configuration.*;
 import org.apache.ignite.internal.*;
+import org.apache.ignite.marshaller.portable.*;
 
 /**
  * Default store manager implementation.
@@ -53,6 +54,6 @@ public class CacheOsStoreManager extends GridCacheStoreManagerAdapter {
 
     /** {@inheritDoc} */
     @Override protected boolean convertPortable() {
-        return true;
+        return !(cfg.isKeepPortableInStore() && ctx.config().getMarshaller() instanceof PortableMarshaller);
     }
 }

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/internal/processors/portable/GridPortableInputStream.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/portable/GridPortableInputStream.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/portable/GridPortableInputStream.java
deleted file mode 100644
index 501517b..0000000
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/portable/GridPortableInputStream.java
+++ /dev/null
@@ -1,168 +0,0 @@
-/*
- * 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.portable;
-
-/**
- * Portable input stream.
- */
-public interface GridPortableInputStream extends GridPortableStream {
-    /**
-     * Read byte value.
-     *
-     * @return Byte value.
-     */
-    public byte readByte();
-
-    /**
-     * Read byte array.
-     *
-     * @param cnt Expected item count.
-     * @return Byte array.
-     */
-    public byte[] readByteArray(int cnt);
-
-    /**
-     * Reads {@code cnt} of bytes into byte array.
-     *
-     * @param arr Expected item count.
-     * @param off offset
-     * @param cnt number of bytes to read.
-     * @return actual length read.
-     */
-    public int read(byte[] arr, int off, int cnt);
-
-    /**
-     * Read boolean value.
-     *
-     * @return Boolean value.
-     */
-    public boolean readBoolean();
-
-    /**
-     * Read boolean array.
-     *
-     * @param cnt Expected item count.
-     * @return Boolean array.
-     */
-    public boolean[] readBooleanArray(int cnt);
-
-    /**
-     * Read short value.
-     *
-     * @return Short value.
-     */
-    public short readShort();
-
-    /**
-     * Read short array.
-     *
-     * @param cnt Expected item count.
-     * @return Short array.
-     */
-    public short[] readShortArray(int cnt);
-
-    /**
-     * Read char value.
-     *
-     * @return Char value.
-     */
-    public char readChar();
-
-    /**
-     * Read char array.
-     *
-     * @param cnt Expected item count.
-     * @return Char array.
-     */
-    public char[] readCharArray(int cnt);
-
-    /**
-     * Read int value.
-     *
-     * @return Int value.
-     */
-    public int readInt();
-
-    /**
-     * Read int value at the given position.
-     *
-     * @param pos Position.
-     * @return Value.
-     */
-    public int readInt(int pos);
-
-    /**
-     * Read int array.
-     *
-     * @param cnt Expected item count.
-     * @return Int array.
-     */
-    public int[] readIntArray(int cnt);
-
-    /**
-     * Read float value.
-     *
-     * @return Float value.
-     */
-    public float readFloat();
-
-    /**
-     * Read float array.
-     *
-     * @param cnt Expected item count.
-     * @return Float array.
-     */
-    public float[] readFloatArray(int cnt);
-
-    /**
-     * Read long value.
-     *
-     * @return Long value.
-     */
-    public long readLong();
-
-    /**
-     * Read long array.
-     *
-     * @param cnt Expected item count.
-     * @return Long array.
-     */
-    public long[] readLongArray(int cnt);
-
-    /**
-     * Read double value.
-     *
-     * @return Double value.
-     */
-    public double readDouble();
-
-    /**
-     * Read double array.
-     *
-     * @param cnt Expected item count.
-     * @return Double array.
-     */
-    public double[] readDoubleArray(int cnt);
-
-    /**
-     * Gets amount of remaining data in bytes.
-     *
-     * @return Remaining data.
-     */
-    public int remaining();
-}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/internal/processors/portable/GridPortableOutputStream.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/portable/GridPortableOutputStream.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/portable/GridPortableOutputStream.java
deleted file mode 100644
index 4f23fd1..0000000
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/portable/GridPortableOutputStream.java
+++ /dev/null
@@ -1,165 +0,0 @@
-/*
- * 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.portable;
-
-/**
- * Portable output stream.
- */
-public interface GridPortableOutputStream extends GridPortableStream, AutoCloseable {
-    /**
-     * Write byte value.
-     *
-     * @param val Byte value.
-     */
-    public void writeByte(byte val);
-
-    /**
-     * Write byte array.
-     *
-     * @param val Byte array.
-     */
-    public void writeByteArray(byte[] val);
-
-    /**
-     * Write boolean value.
-     *
-     * @param val Boolean value.
-     */
-    public void writeBoolean(boolean val);
-
-    /**
-     * Write boolean array.
-     *
-     * @param val Boolean array.
-     */
-    public void writeBooleanArray(boolean[] val);
-
-    /**
-     * Write short value.
-     *
-     * @param val Short value.
-     */
-    public void writeShort(short val);
-
-    /**
-     * Write short array.
-     *
-     * @param val Short array.
-     */
-    public void writeShortArray(short[] val);
-
-    /**
-     * Write char value.
-     *
-     * @param val Char value.
-     */
-    public void writeChar(char val);
-
-    /**
-     * Write char array.
-     *
-     * @param val Char array.
-     */
-    public void writeCharArray(char[] val);
-
-    /**
-     * Write int value.
-     *
-     * @param val Int value.
-     */
-    public void writeInt(int val);
-
-    /**
-     * Write int value to the given position.
-     *
-     * @param pos Position.
-     * @param val Value.
-     */
-    public void writeInt(int pos, int val);
-
-    /**
-     * Write int array.
-     *
-     * @param val Int array.
-     */
-    public void writeIntArray(int[] val);
-
-    /**
-     * Write float value.
-     *
-     * @param val Float value.
-     */
-    public void writeFloat(float val);
-
-    /**
-     * Write float array.
-     *
-     * @param val Float array.
-     */
-    public void writeFloatArray(float[] val);
-
-    /**
-     * Write long value.
-     *
-     * @param val Long value.
-     */
-    public void writeLong(long val);
-
-    /**
-     * Write long array.
-     *
-     * @param val Long array.
-     */
-    public void writeLongArray(long[] val);
-
-    /**
-     * Write double value.
-     *
-     * @param val Double value.
-     */
-    public void writeDouble(double val);
-
-    /**
-     * Write double array.
-     *
-     * @param val Double array.
-     */
-    public void writeDoubleArray(double[] val);
-
-    /**
-     * Write byte array.
-     *
-     * @param arr Array.
-     * @param off Offset.
-     * @param len Length.
-     */
-    public void write(byte[] arr, int off, int len);
-
-    /**
-     * Write data from unmanaged memory.
-     *
-     * @param addr Address.
-     * @param cnt Count.
-     */
-    public void write(long addr, int cnt);
-
-    /**
-     * Close the stream releasing resources.
-     */
-    @Override public void close();
-}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/internal/processors/portable/GridPortableStream.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/portable/GridPortableStream.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/portable/GridPortableStream.java
deleted file mode 100644
index 2c3fc78..0000000
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/portable/GridPortableStream.java
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * 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.portable;
-
-/**
- * Portable stream.
- */
-public interface GridPortableStream {
-    /**
-     * @return Position.
-     */
-    public int position();
-
-    /**
-     * @param pos Position.
-     */
-    public void position(int pos);
-
-    /**
-     * @return Underlying array.
-     */
-    public byte[] array();
-
-    /**
-     * @return Copy of data in the stream.
-     */
-    public byte[] arrayCopy();
-
-    /**
-     * @return Offheap pointer if stream is offheap based, otherwise {@code 0}.
-     */
-    public long offheapPointer();
-
-    /**
-     * @return {@code True} is stream is array based.
-     */
-    public boolean hasArray();
-}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/internal/processors/portable/package-info.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/portable/package-info.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/portable/package-info.java
deleted file mode 100644
index c6e664c..0000000
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/portable/package-info.java
+++ /dev/null
@@ -1,22 +0,0 @@
-/*
- * 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 description. -->
- * Portable processor.
- */
-package org.apache.ignite.internal.processors.portable;
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/marshaller/portable/PortableMarshaller.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/marshaller/portable/PortableMarshaller.java b/modules/core/src/main/java/org/apache/ignite/marshaller/portable/PortableMarshaller.java
new file mode 100644
index 0000000..2a17363
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/marshaller/portable/PortableMarshaller.java
@@ -0,0 +1,347 @@
+/*
+ * 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.marshaller.portable;
+
+import org.apache.ignite.*;
+import org.apache.ignite.internal.portable.*;
+import org.apache.ignite.marshaller.*;
+import org.apache.ignite.portable.*;
+
+import org.jetbrains.annotations.*;
+
+import java.io.*;
+import java.sql.*;
+import java.util.*;
+
+/**
+ * Implementation of {@link org.apache.ignite.marshaller.Marshaller} that lets to serialize and deserialize all objects
+ * in the portable format.
+ * <p>
+ * {@code PortableMarshaller} is tested only on Java HotSpot VM on other VMs it could yield unexpected results.
+ * <p>
+ * <h1 class="header">Configuration</h1>
+ * <h2 class="header">Mandatory</h2>
+ * This marshaller has no mandatory configuration parameters.
+ * <h2 class="header">Java Example</h2>
+ * <pre name="code" class="java">
+ * PortableMarshaller marshaller = new PortableMarshaller();
+ *
+ * IgniteConfiguration cfg = new IgniteConfiguration();
+ *
+ * // Override marshaller.
+ * cfg.setMarshaller(marshaller);
+ *
+ * // Starts grid.
+ * G.start(cfg);
+ * </pre>
+ * <h2 class="header">Spring Example</h2>
+ * PortableMarshaller can be configured from Spring XML configuration file:
+ * <pre name="code" class="xml">
+ * &lt;bean id="grid.custom.cfg" class="org.apache.ignite.configuration.IgniteConfiguration" singleton="true"&gt;
+ *     ...
+ *     &lt;property name="marshaller"&gt;
+ *         &lt;bean class="org.apache.ignite.marshaller.portable.PortableMarshaller"&gt;
+ *            ...
+ *         &lt;/bean&gt;
+ *     &lt;/property&gt;
+ *     ...
+ * &lt;/bean&gt;
+ * </pre>
+ * <p>
+ * <img src="http://ignite.incubator.apache.org/images/spring-small.png">
+ * <br>
+ * For information about Spring framework visit <a href="http://www.springframework.org/">www.springframework.org</a>
+ */
+public class PortableMarshaller extends AbstractMarshaller {
+    /** Default portable protocol version. */
+    public static final PortableProtocolVersion DFLT_PORTABLE_PROTO_VER = PortableProtocolVersion.VER_1_4_0;
+
+    /** Class names. */
+    private Collection<String> clsNames;
+
+    /** ID mapper. */
+    private PortableIdMapper idMapper;
+
+    /** Serializer. */
+    private PortableSerializer serializer;
+
+    /** Types. */
+    private Collection<PortableTypeConfiguration> typeCfgs;
+
+    /** Use timestamp flag. */
+    private boolean useTs = true;
+
+    /** Whether to convert string to bytes using UTF-8 encoding. */
+    private boolean convertString = true;
+
+    /** Meta data enabled flag. */
+    private boolean metaDataEnabled = true;
+
+    /** Keep deserialized flag. */
+    private boolean keepDeserialized = true;
+
+    /** Protocol version. */
+    private PortableProtocolVersion protoVer = DFLT_PORTABLE_PROTO_VER;
+
+    /** */
+    private GridPortableMarshaller impl;
+
+    /**
+     * Gets class names.
+     *
+     * @return Class names.
+     */
+    public Collection<String> getClassNames() {
+        return clsNames;
+    }
+
+    /**
+     * Sets class names of portable objects explicitly.
+     *
+     * @param clsNames Class names.
+     */
+    public void setClassNames(Collection<String> clsNames) {
+        this.clsNames = new ArrayList<>(clsNames.size());
+
+        for (String clsName : clsNames)
+            this.clsNames.add(clsName.trim());
+    }
+
+    /**
+     * Gets ID mapper.
+     *
+     * @return ID mapper.
+     */
+    public PortableIdMapper getIdMapper() {
+        return idMapper;
+    }
+
+    /**
+     * Sets ID mapper.
+     *
+     * @param idMapper ID mapper.
+     */
+    public void setIdMapper(PortableIdMapper idMapper) {
+        this.idMapper = idMapper;
+    }
+
+    /**
+     * Gets serializer.
+     *
+     * @return Serializer.
+     */
+    public PortableSerializer getSerializer() {
+        return serializer;
+    }
+
+    /**
+     * Sets serializer.
+     *
+     * @param serializer Serializer.
+     */
+    public void setSerializer(PortableSerializer serializer) {
+        this.serializer = serializer;
+    }
+
+    /**
+     * Gets types configuration.
+     *
+     * @return Types configuration.
+     */
+    public Collection<PortableTypeConfiguration> getTypeConfigurations() {
+        return typeCfgs;
+    }
+
+    /**
+     * Sets type configurations.
+     *
+     * @param typeCfgs Type configurations.
+     */
+    public void setTypeConfigurations(Collection<PortableTypeConfiguration> typeCfgs) {
+        this.typeCfgs = typeCfgs;
+    }
+
+    /**
+     * If {@code true} then date values converted to {@link Timestamp} on deserialization.
+     * <p>
+     * Default value is {@code true}.
+     *
+     * @return Flag indicating whether date values converted to {@link Timestamp} during unmarshalling.
+     */
+    public boolean isUseTimestamp() {
+        return useTs;
+    }
+
+    /**
+     * @param useTs Flag indicating whether date values converted to {@link Timestamp} during unmarshalling.
+     */
+    public void setUseTimestamp(boolean useTs) {
+        this.useTs = useTs;
+    }
+
+    /**
+     * Gets strings must be converted to or from bytes using UTF-8 encoding.
+     * <p>
+     * Default value is {@code true}.
+     *
+     * @return Flag indicating whether string must be converted to byte array using UTF-8 encoding.
+     */
+    public boolean isConvertStringToBytes() {
+        return convertString;
+    }
+
+    /**
+     * Sets strings must be converted to or from bytes using UTF-8 encoding.
+     * <p>
+     * Default value is {@code true}.
+     *
+     * @param convertString Flag indicating whether string must be converted to byte array using UTF-8 encoding.
+     */
+    public void setConvertStringToBytes(boolean convertString) {
+        this.convertString = convertString;
+    }
+
+    /**
+     * If {@code true}, meta data will be collected or all types. If you need to override this behaviour for
+     * some specific type, use {@link PortableTypeConfiguration#setMetaDataEnabled(Boolean)} method.
+     * <p>
+     * Default value if {@code true}.
+     *
+     * @return Whether meta data is collected.
+     */
+    public boolean isMetaDataEnabled() {
+        return metaDataEnabled;
+    }
+
+    /**
+     * @param metaDataEnabled Whether meta data is collected.
+     */
+    public void setMetaDataEnabled(boolean metaDataEnabled) {
+        this.metaDataEnabled = metaDataEnabled;
+    }
+
+    /**
+     * If {@code true}, {@link PortableObject} will cache deserialized instance after
+     * {@link PortableObject#deserialize()} is called. All consequent calls of this
+     * method on the same instance of {@link PortableObject} will return that cached
+     * value without actually deserializing portable object. If you need to override this
+     * behaviour for some specific type, use {@link PortableTypeConfiguration#setKeepDeserialized(Boolean)}
+     * method.
+     * <p>
+     * Default value if {@code true}.
+     *
+     * @return Whether deserialized value is kept.
+     */
+    public boolean isKeepDeserialized() {
+        return keepDeserialized;
+    }
+
+    /**
+     * @param keepDeserialized Whether deserialized value is kept.
+     */
+    public void setKeepDeserialized(boolean keepDeserialized) {
+        this.keepDeserialized = keepDeserialized;
+    }
+
+    /**
+     * Gets portable protocol version.
+     * <p>
+     * Defaults to {@link #DFLT_PORTABLE_PROTO_VER}.
+     *
+     * @return Portable protocol version.
+     */
+    public PortableProtocolVersion getProtocolVersion() {
+        return protoVer;
+    }
+
+    /**
+     * Sets portable protocol version.
+     * <p>
+     * Defaults to {@link #DFLT_PORTABLE_PROTO_VER}.
+     *
+     * @param protoVer Portable protocol version.
+     */
+    public void setProtocolVersion(PortableProtocolVersion protoVer) {
+        this.protoVer = protoVer;
+    }
+
+    /**
+     * Returns currently set {@link MarshallerContext}.
+     *
+     * @return Marshaller context.
+     */
+    public MarshallerContext getContext() {
+        return ctx;
+    }
+
+    /**
+     * Sets {@link PortableContext}.
+     * <p/>
+     * @param ctx Portable context.
+     */
+    private void setPortableContext(PortableContext ctx) {
+        ctx.configure(this);
+
+        impl = new GridPortableMarshaller(ctx);
+    }
+
+    /** {@inheritDoc} */
+    @Override public byte[] marshal(@Nullable Object obj) throws IgniteCheckedException {
+        return impl.marshal(obj, 0);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void marshal(@Nullable Object obj, OutputStream out) throws IgniteCheckedException {
+        byte[] arr = marshal(obj);
+
+        try {
+            out.write(arr);
+        }
+        catch (IOException e) {
+            throw new PortableException("Failed to marshal the object: " + obj, e);
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override public <T> T unmarshal(byte[] bytes, @Nullable ClassLoader clsLdr) throws IgniteCheckedException {
+        return impl.deserialize(bytes, clsLdr);
+    }
+
+    /** {@inheritDoc} */
+    @Override public <T> T unmarshal(InputStream in, @Nullable ClassLoader clsLdr) throws IgniteCheckedException {
+        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
+
+        byte[] arr = new byte[4096];
+        int cnt;
+
+        // we have to fully read the InputStream because GridPortableMarshaller requires support of a method that
+        // returns number of bytes remaining.
+        try {
+            while ((cnt = in.read(arr)) != -1)
+                buffer.write(arr, 0, cnt);
+
+            buffer.flush();
+
+            return impl.deserialize(buffer.toByteArray(), clsLdr);
+        }
+        catch (IOException e) {
+            throw new PortableException("Failed to unmarshal the object from InputStream", e);
+        }
+    }
+}
+

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/marshaller/portable/package-info.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/marshaller/portable/package-info.java b/modules/core/src/main/java/org/apache/ignite/marshaller/portable/package-info.java
new file mode 100644
index 0000000..90cc5e6
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/marshaller/portable/package-info.java
@@ -0,0 +1,22 @@
+/*
+ * 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 description. -->
+ * Contains portable marshaller API classes.
+ */
+package org.apache.ignite.marshaller.portable;
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/portable/PortableBuilder.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/portable/PortableBuilder.java b/modules/core/src/main/java/org/apache/ignite/portable/PortableBuilder.java
new file mode 100644
index 0000000..a899c46
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/portable/PortableBuilder.java
@@ -0,0 +1,138 @@
+/*
+ * 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.portable;
+
+import org.apache.ignite.*;
+
+import org.jetbrains.annotations.*;
+
+/**
+ * Portable object builder. Provides ability to build portable objects dynamically without having class definitions.
+ * <p>
+ * Here is an example of how a portable object can be built dynamically:
+ * <pre name=code class=java>
+ * PortableBuilder builder = Ignition.ignite().portables().builder("org.project.MyObject");
+ *
+ * builder.setField("fieldA", "A");
+ * builder.setField("fieldB", "B");
+ *
+ * PortableObject portableObj = builder.build();
+ * </pre>
+ *
+ * <p>
+ * Also builder can be initialized by existing portable object. This allows changing some fields without affecting
+ * other fields.
+ * <pre name=code class=java>
+ * PortableBuilder builder = Ignition.ignite().portables().builder(person);
+ *
+ * builder.setField("name", "John");
+ *
+ * person = builder.build();
+ * </pre>
+ * </p>
+ *
+ * If you need to modify nested portable object you can get builder for nested object using
+ * {@link #getField(String)}, changes made on nested builder will affect parent object,
+ * for example:
+ *
+ * <pre name=code class=java>
+ * PortableBuilder personBuilder = grid.portables().createBuilder(personPortableObj);
+ * PortableBuilder addressBuilder = personBuilder.setField("address");
+ *
+ * addressBuilder.setField("city", "New York");
+ *
+ * personPortableObj = personBuilder.build();
+ *
+ * // Should be "New York".
+ * String city = personPortableObj.getField("address").getField("city");
+ * </pre>
+ *
+ * @see IgnitePortables#builder(int)
+ * @see IgnitePortables#builder(String)
+ * @see IgnitePortables#builder(PortableObject)
+ */
+public interface PortableBuilder {
+    /**
+     * Returns value assigned to the specified field.
+     * If the value is a portable object instance of {@code GridPortableBuilder} will be returned,
+     * which can be modified.
+     * <p>
+     * Collections and maps returned from this method are modifiable.
+     *
+     * @param name Field name.
+     * @return Filed value.
+     */
+    public <T> T getField(String name);
+
+    /**
+     * Sets field value.
+     *
+     * @param name Field name.
+     * @param val Field value (cannot be {@code null}).
+     * @see PortableObject#metaData()
+     */
+    public PortableBuilder setField(String name, Object val);
+
+    /**
+     * Sets field value with value type specification.
+     * <p>
+     * Field type is needed for proper metadata update.
+     *
+     * @param name Field name.
+     * @param val Field value.
+     * @param type Field type.
+     * @see PortableObject#metaData()
+     */
+    public <T> PortableBuilder setField(String name, @Nullable T val, Class<? super T> type);
+
+    /**
+     * Sets field value.
+     * <p>
+     * This method should be used if field is portable object.
+     *
+     * @param name Field name.
+     * @param builder Builder for object field.
+     */
+    public PortableBuilder setField(String name, @Nullable PortableBuilder builder);
+
+    /**
+     * Removes field from this builder.
+     *
+     * @param fieldName Field name.
+     * @return {@code this} instance for chaining.
+     */
+    public PortableBuilder removeField(String fieldName);
+
+    /**
+     * Sets hash code for resulting portable object returned by {@link #build()} method.
+     * <p>
+     * If not set {@code 0} is used.
+     *
+     * @param hashCode Hash code.
+     * @return {@code this} instance for chaining.
+     */
+    public PortableBuilder hashCode(int hashCode);
+
+    /**
+     * Builds portable object.
+     *
+     * @return Portable object.
+     * @throws PortableException In case of error.
+     */
+    public PortableObject build() throws PortableException;
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/portable/PortableException.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/portable/PortableException.java b/modules/core/src/main/java/org/apache/ignite/portable/PortableException.java
new file mode 100644
index 0000000..62ae901
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/portable/PortableException.java
@@ -0,0 +1,58 @@
+/*
+ * 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.portable;
+
+import org.apache.ignite.*;
+
+import org.jetbrains.annotations.*;
+
+/**
+ * Exception indicating portable object serialization error.
+ */
+public class PortableException extends IgniteException {
+    /** */
+    private static final long serialVersionUID = 0L;
+
+    /**
+     * Creates portable exception with error message.
+     *
+     * @param msg Error message.
+     */
+    public PortableException(String msg) {
+        super(msg);
+    }
+
+    /**
+     * Creates portable exception with {@link Throwable} as a cause.
+     *
+     * @param cause Cause.
+     */
+    public PortableException(Throwable cause) {
+        super(cause);
+    }
+
+    /**
+     * Creates portable exception with error message and {@link Throwable} as a cause.
+     *
+     * @param msg Error message.
+     * @param cause Cause.
+     */
+    public PortableException(String msg, @Nullable Throwable cause) {
+        super(msg, cause);
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/portable/PortableIdMapper.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/portable/PortableIdMapper.java b/modules/core/src/main/java/org/apache/ignite/portable/PortableIdMapper.java
new file mode 100644
index 0000000..9502a86
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/portable/PortableIdMapper.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.portable;
+
+import org.apache.ignite.marshaller.portable.*;
+
+/**
+ * Type and field ID mapper for portable objects. Ignite never writes full
+ * strings for field or type names. Instead, for performance reasons, Ignite
+ * writes integer hash codes for type and field names. It has been tested that
+ * hash code conflicts for the type names or the field names
+ * within the same type are virtually non-existent and, to gain performance, it is safe
+ * to work with hash codes. For the cases when hash codes for different types or fields
+ * actually do collide {@code PortableIdMapper} allows to override the automatically
+ * generated hash code IDs for the type and field names.
+ * <p>
+ * Portable ID mapper can be configured for all portable objects via {@link PortableMarshaller#getIdMapper()} method,
+ * or for a specific portable type via {@link PortableTypeConfiguration#getIdMapper()} method.
+ */
+public interface PortableIdMapper {
+    /**
+     * Gets type ID for provided class name.
+     * <p>
+     * If {@code 0} is returned, hash code of class simple name will be used.
+     *
+     * @param clsName Class name.
+     * @return Type ID.
+     */
+    public int typeId(String clsName);
+
+    /**
+     * Gets ID for provided field.
+     * <p>
+     * If {@code 0} is returned, hash code of field name will be used.
+     *
+     * @param typeId Type ID.
+     * @param fieldName Field name.
+     * @return Field ID.
+     */
+    public int fieldId(int typeId, String fieldName);
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/portable/PortableInvalidClassException.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/portable/PortableInvalidClassException.java b/modules/core/src/main/java/org/apache/ignite/portable/PortableInvalidClassException.java
new file mode 100644
index 0000000..533d453
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/portable/PortableInvalidClassException.java
@@ -0,0 +1,58 @@
+/*
+ * 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.portable;
+
+import org.jetbrains.annotations.*;
+
+/**
+ * Exception indicating that class needed for deserialization of portable object does not exist.
+ * <p>
+ * Thrown from {@link PortableObject#deserialize()} method.
+ */
+public class PortableInvalidClassException extends PortableException {
+    /** */
+    private static final long serialVersionUID = 0L;
+
+    /**
+     * Creates invalid class exception with error message.
+     *
+     * @param msg Error message.
+     */
+    public PortableInvalidClassException(String msg) {
+        super(msg);
+    }
+
+    /**
+     * Creates invalid class exception with {@link Throwable} as a cause.
+     *
+     * @param cause Cause.
+     */
+    public PortableInvalidClassException(Throwable cause) {
+        super(cause);
+    }
+
+    /**
+     * Creates invalid class exception with error message and {@link Throwable} as a cause.
+     *
+     * @param msg Error message.
+     * @param cause Cause.
+     */
+    public PortableInvalidClassException(String msg, @Nullable Throwable cause) {
+        super(msg, cause);
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/portable/PortableMarshalAware.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/portable/PortableMarshalAware.java b/modules/core/src/main/java/org/apache/ignite/portable/PortableMarshalAware.java
new file mode 100644
index 0000000..3ae2bd7
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/portable/PortableMarshalAware.java
@@ -0,0 +1,48 @@
+/*
+ * 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.portable;
+
+/**
+ * Interface that allows to implement custom serialization
+ * logic for portable objects. Portable objects are not required
+ * to implement this interface, in which case Ignite will automatically
+ * serialize portable objects using reflection.
+ * <p>
+ * This interface, in a way, is analogous to {@link java.io.Externalizable}
+ * interface, which allows users to override default serialization logic,
+ * usually for performance reasons. The only difference here is that portable
+ * serialization is already very fast and implementing custom serialization
+ * logic for portables does not provide significant performance gains.
+ */
+public interface PortableMarshalAware {
+    /**
+     * Writes fields to provided writer.
+     *
+     * @param writer Portable object writer.
+     * @throws PortableException In case of error.
+     */
+    public void writePortable(PortableWriter writer) throws PortableException;
+
+    /**
+     * Reads fields from provided reader.
+     *
+     * @param reader Portable object reader.
+     * @throws PortableException In case of error.
+     */
+    public void readPortable(PortableReader reader) throws PortableException;
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/portable/PortableMetadata.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/portable/PortableMetadata.java b/modules/core/src/main/java/org/apache/ignite/portable/PortableMetadata.java
new file mode 100644
index 0000000..7697299
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/portable/PortableMetadata.java
@@ -0,0 +1,63 @@
+/*
+ * 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.portable;
+
+import org.apache.ignite.*;
+
+import org.jetbrains.annotations.*;
+
+import java.util.*;
+
+/**
+ * Portable type meta data. Metadata for portable types can be accessed from any of the
+ * {@link IgnitePortables#metadata(String)} methods.
+ * Having metadata also allows for proper formatting of {@code PortableObject#toString()} method,
+ * even when portable objects are kept in binary format only, which may be necessary for audit reasons.
+ */
+public interface PortableMetadata {
+    /**
+     * Gets portable type name.
+     *
+     * @return Portable type name.
+     */
+    public String typeName();
+
+    /**
+     * Gets collection of all field names for this portable type.
+     *
+     * @return Collection of all field names for this portable type.
+     */
+    public Collection<String> fields();
+
+    /**
+     * Gets name of the field type for a given field.
+     *
+     * @param fieldName Field name.
+     * @return Field type name.
+     */
+    @Nullable public String fieldTypeName(String fieldName);
+
+    /**
+     * Portable objects can optionally specify custom key-affinity mapping in the
+     * configuration. This method returns the name of the field which should be
+     * used for the key-affinity mapping.
+     *
+     * @return Affinity key field name.
+     */
+    @Nullable public String affinityKeyFieldName();
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/portable/PortableObject.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/portable/PortableObject.java b/modules/core/src/main/java/org/apache/ignite/portable/PortableObject.java
new file mode 100644
index 0000000..c22892d
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/portable/PortableObject.java
@@ -0,0 +1,153 @@
+/*
+ * 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.portable;
+
+import org.apache.ignite.*;
+import org.apache.ignite.marshaller.portable.*;
+
+import org.jetbrains.annotations.*;
+
+import java.io.*;
+import java.util.*;
+
+/**
+ * Wrapper for portable object in portable binary format. Once an object is defined as portable,
+ * Ignite will always store it in memory in the portable (i.e. binary) format.
+ * User can choose to work either with the portable format or with the deserialized form
+ * (assuming that class definitions are present in the classpath).
+ * <p>
+ * <b>NOTE:</b> user does not need to (and should not) implement this interface directly.
+ * <p>
+ * To work with the portable format directly, user should create a cache projection
+ * over {@code PortableObject} class and then retrieve individual fields as needed:
+ * <pre name=code class=java>
+ * IgniteCache&lt;PortableObject, PortableObject&gt; prj = cache.withKeepPortable();
+ *
+ * // Convert instance of MyKey to portable format.
+ * // We could also use GridPortableBuilder to create the key in portable format directly.
+ * PortableObject key = grid.portables().toPortable(new MyKey());
+ *
+ * PortableObject val = prj.get(key);
+ *
+ * String field = val.field("myFieldName");
+ * </pre>
+ * Alternatively, if we have class definitions in the classpath, we may choose to work with deserialized
+ * typed objects at all times. In this case we do incur the deserialization cost. However, if
+ * {@link PortableMarshaller#isKeepDeserialized()} is {@code true} then Ignite will only deserialize on the first access
+ * and will cache the deserialized object, so it does not have to be deserialized again:
+ * <pre name=code class=java>
+ * IgniteCache&lt;MyKey.class, MyValue.class&gt; cache = grid.cache(null);
+ *
+ * MyValue val = cache.get(new MyKey());
+ *
+ * // Normal java getter.
+ * String fieldVal = val.getMyFieldName();
+ * </pre>
+ * <h1 class="header">Working With Maps and Collections</h1>
+ * All maps and collections in the portable objects are serialized automatically. When working
+ * with different platforms, e.g. C++ or .NET, Ignite will automatically pick the most
+ * adequate collection or map in either language. For example, {@link ArrayList} in Java will become
+ * {@code List} in C#, {@link LinkedList} in Java is {@link LinkedList} in C#, {@link HashMap}
+ * in Java is {@code Dictionary} in C#, and {@link TreeMap} in Java becomes {@code SortedDictionary}
+ * in C#, etc.
+ * <h1 class="header">Dynamic Structure Changes</h1>
+ * Since objects are always cached in the portable binary format, server does not need to
+ * be aware of the class definitions. Moreover, if class definitions are not present or not
+ * used on the server, then clients can continuously change the structure of the portable
+ * objects without having to restart the cluster. For example, if one client stores a
+ * certain class with fields A and B, and another client stores the same class with
+ * fields B and C, then the server-side portable object will have the fields A, B, and C.
+ * As the structure of a portable object changes, the new fields become available for SQL queries
+ * automatically.
+ * <h1 class="header">Building Portable Objects</h1>
+ * Ignite comes with {@link PortableBuilder} which allows to build portable objects dynamically:
+ * <pre name=code class=java>
+ * PortableBuilder builder = Ignition.ignite().portables().builder("org.project.MyObject");
+ *
+ * builder.setField("fieldA", "A");
+ * builder.setField("fieldB", "B");
+ *
+ * PortableObject portableObj = builder.build();
+ * </pre>
+ * For the cases when class definition is present
+ * in the class path, it is also possible to populate a standard POJO and then
+ * convert it to portable format, like so:
+ * <pre name=code class=java>
+ * MyObject obj = new MyObject();
+ *
+ * obj.setFieldA("A");
+ * obj.setFieldB(123);
+ *
+ * PortableObject portableObj = Ignition.ignite().portables().toPortable(obj);
+ * </pre>
+ * <h1 class="header">Portable Metadata</h1>
+ * Even though Ignite portable protocol only works with hash codes for type and field names
+ * to achieve better performance, Ignite provides metadata for all portable types which
+ * can be queried ar runtime via any of the {@link IgnitePortables#metadata(Class)}
+ * methods. Having metadata also allows for proper formatting of {@code PortableObject.toString()} method,
+ * even when portable objects are kept in binary format only, which may be necessary for audit reasons.
+ */
+public interface PortableObject extends Serializable, Cloneable {
+    /**
+     * Gets portable object type ID.
+     *
+     * @return Type ID.
+     */
+    public int typeId();
+
+    /**
+     * Gets meta data for this portable object.
+     *
+     * @return Meta data.
+     * @throws PortableException In case of error.
+     */
+    @Nullable public PortableMetadata metaData() throws PortableException;
+
+    /**
+     * Gets field value.
+     *
+     * @param fieldName Field name.
+     * @return Field value.
+     * @throws PortableException In case of any other error.
+     */
+    @Nullable public <F> F field(String fieldName) throws PortableException;
+
+    /**
+     * Checks whether field is set.
+     *
+     * @param fieldName Field name.
+     * @return {@code true} if field is set.
+     */
+    public boolean hasField(String fieldName);
+
+    /**
+     * Gets fully deserialized instance of portable object.
+     *
+     * @return Fully deserialized instance of portable object.
+     * @throws PortableInvalidClassException If class doesn't exist.
+     * @throws PortableException In case of any other error.
+     */
+    @Nullable public <T> T deserialize() throws PortableException;
+
+    /**
+     * Copies this portable object.
+     *
+     * @return Copy of this portable object.
+     */
+    public PortableObject clone() throws CloneNotSupportedException;
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/portable/PortableProtocolVersion.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/portable/PortableProtocolVersion.java b/modules/core/src/main/java/org/apache/ignite/portable/PortableProtocolVersion.java
new file mode 100644
index 0000000..5764560
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/portable/PortableProtocolVersion.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.portable;
+
+import org.jetbrains.annotations.*;
+
+/**
+ * Portable protocol version.
+ */
+public enum PortableProtocolVersion {
+    /** Ignite 1.4.0 release. */
+    VER_1_4_0;
+
+    /** Enumerated values. */
+    private static final PortableProtocolVersion[] VALS = values();
+
+    /**
+     * Efficiently gets enumerated value from its ordinal.
+     *
+     * @param ord Ordinal value.
+     * @return Enumerated value or {@code null} if ordinal out of range.
+     */
+    @Nullable public static PortableProtocolVersion fromOrdinal(int ord) {
+        return ord >= 0 && ord < VALS.length ? VALS[ord] : null;
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/portable/PortableRawReader.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/portable/PortableRawReader.java b/modules/core/src/main/java/org/apache/ignite/portable/PortableRawReader.java
new file mode 100644
index 0000000..a704570
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/portable/PortableRawReader.java
@@ -0,0 +1,233 @@
+/*
+ * 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.portable;
+
+import org.jetbrains.annotations.*;
+
+import java.math.*;
+import java.sql.*;
+import java.util.*;
+import java.util.Date;
+
+/**
+ * Raw reader for portable objects. Raw reader does not use field name hash codes, therefore,
+ * making the format even more compact. However, if the raw reader is used,
+ * dynamic structure changes to the portable objects are not supported.
+ */
+public interface PortableRawReader {
+    /**
+     * @return Byte value.
+     * @throws PortableException In case of error.
+     */
+    public byte readByte() throws PortableException;
+
+    /**
+     * @return Short value.
+     * @throws PortableException In case of error.
+     */
+    public short readShort() throws PortableException;
+
+    /**
+     * @return Integer value.
+     * @throws PortableException In case of error.
+     */
+    public int readInt() throws PortableException;
+
+    /**
+     * @return Long value.
+     * @throws PortableException In case of error.
+     */
+    public long readLong() throws PortableException;
+
+    /**
+     * @return Float value.
+     * @throws PortableException In case of error.
+     */
+    public float readFloat() throws PortableException;
+
+    /**
+     * @return Double value.
+     * @throws PortableException In case of error.
+     */
+    public double readDouble() throws PortableException;
+
+    /**
+     * @return Char value.
+     * @throws PortableException In case of error.
+     */
+    public char readChar() throws PortableException;
+
+    /**
+     * @return Boolean value.
+     * @throws PortableException In case of error.
+     */
+    public boolean readBoolean() throws PortableException;
+
+    /**
+     * @return Decimal value.
+     * @throws PortableException In case of error.
+     */
+    @Nullable public BigDecimal readDecimal() throws PortableException;
+
+    /**
+     * @return String value.
+     * @throws PortableException In case of error.
+     */
+    @Nullable public String readString() throws PortableException;
+
+    /**
+     * @return UUID.
+     * @throws PortableException In case of error.
+     */
+    @Nullable public UUID readUuid() throws PortableException;
+
+    /**
+     * @return Date.
+     * @throws PortableException In case of error.
+     */
+    @Nullable public Date readDate() throws PortableException;
+
+    /**
+     * @return Timestamp.
+     * @throws PortableException In case of error.
+     */
+    @Nullable public Timestamp readTimestamp() throws PortableException;
+
+    /**
+     * @return Object.
+     * @throws PortableException In case of error.
+     */
+    @Nullable public <T> T readObject() throws PortableException;
+
+    /**
+     * @return Byte array.
+     * @throws PortableException In case of error.
+     */
+    @Nullable public byte[] readByteArray() throws PortableException;
+
+    /**
+     * @return Short array.
+     * @throws PortableException In case of error.
+     */
+    @Nullable public short[] readShortArray() throws PortableException;
+
+    /**
+     * @return Integer array.
+     * @throws PortableException In case of error.
+     */
+    @Nullable public int[] readIntArray() throws PortableException;
+
+    /**
+     * @return Long array.
+     * @throws PortableException In case of error.
+     */
+    @Nullable public long[] readLongArray() throws PortableException;
+
+    /**
+     * @return Float array.
+     * @throws PortableException In case of error.
+     */
+    @Nullable public float[] readFloatArray() throws PortableException;
+
+    /**
+     * @return Byte array.
+     * @throws PortableException In case of error.
+     */
+    @Nullable public double[] readDoubleArray() throws PortableException;
+
+    /**
+     * @return Char array.
+     * @throws PortableException In case of error.
+     */
+    @Nullable public char[] readCharArray() throws PortableException;
+
+    /**
+     * @return Boolean array.
+     * @throws PortableException In case of error.
+     */
+    @Nullable public boolean[] readBooleanArray() throws PortableException;
+
+    /**
+     * @return Decimal array.
+     * @throws PortableException In case of error.
+     */
+    @Nullable public BigDecimal[] readDecimalArray() throws PortableException;
+
+    /**
+     * @return String array.
+     * @throws PortableException In case of error.
+     */
+    @Nullable public String[] readStringArray() throws PortableException;
+
+    /**
+     * @return UUID array.
+     * @throws PortableException In case of error.
+     */
+    @Nullable public UUID[] readUuidArray() throws PortableException;
+
+    /**
+     * @return Date array.
+     * @throws PortableException In case of error.
+     */
+    @Nullable public Date[] readDateArray() throws PortableException;
+
+    /**
+     * @return Object array.
+     * @throws PortableException In case of error.
+     */
+    @Nullable public Object[] readObjectArray() throws PortableException;
+
+    /**
+     * @return Collection.
+     * @throws PortableException In case of error.
+     */
+    @Nullable public <T> Collection<T> readCollection() throws PortableException;
+
+    /**
+     * @param colCls Collection class.
+     * @return Collection.
+     * @throws PortableException In case of error.
+     */
+    @Nullable public <T> Collection<T> readCollection(Class<? extends Collection<T>> colCls)
+        throws PortableException;
+
+    /**
+     * @return Map.
+     * @throws PortableException In case of error.
+     */
+    @Nullable public <K, V> Map<K, V> readMap() throws PortableException;
+
+    /**
+     * @param mapCls Map class.
+     * @return Map.
+     * @throws PortableException In case of error.
+     */
+    @Nullable public <K, V> Map<K, V> readMap(Class<? extends Map<K, V>> mapCls) throws PortableException;
+
+    /**
+     * @return Value.
+     * @throws PortableException In case of error.
+     */
+    @Nullable public <T extends Enum<?>> T readEnum() throws PortableException;
+
+    /**
+     * @return Value.
+     * @throws PortableException In case of error.
+     */
+    @Nullable public <T extends Enum<?>> T[] readEnumArray() throws PortableException;
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/portable/PortableRawWriter.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/portable/PortableRawWriter.java b/modules/core/src/main/java/org/apache/ignite/portable/PortableRawWriter.java
new file mode 100644
index 0000000..e6efee5
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/portable/PortableRawWriter.java
@@ -0,0 +1,218 @@
+/*
+ * 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.portable;
+
+import org.jetbrains.annotations.*;
+
+import java.math.*;
+import java.sql.*;
+import java.util.*;
+import java.util.Date;
+
+/**
+ * Raw writer for portable object. Raw writer does not write field name hash codes, therefore,
+ * making the format even more compact. However, if the raw writer is used,
+ * dynamic structure changes to the portable objects are not supported.
+ */
+public interface PortableRawWriter {
+    /**
+     * @param val Value to write.
+     * @throws PortableException In case of error.
+     */
+    public void writeByte(byte val) throws PortableException;
+
+    /**
+     * @param val Value to write.
+     * @throws PortableException In case of error.
+     */
+    public void writeShort(short val) throws PortableException;
+
+    /**
+     * @param val Value to write.
+     * @throws PortableException In case of error.
+     */
+    public void writeInt(int val) throws PortableException;
+
+    /**
+     * @param val Value to write.
+     * @throws PortableException In case of error.
+     */
+    public void writeLong(long val) throws PortableException;
+
+    /**
+     * @param val Value to write.
+     * @throws PortableException In case of error.
+     */
+    public void writeFloat(float val) throws PortableException;
+
+    /**
+     * @param val Value to write.
+     * @throws PortableException In case of error.
+     */
+    public void writeDouble(double val) throws PortableException;
+
+    /**
+     * @param val Value to write.
+     * @throws PortableException In case of error.
+     */
+    public void writeChar(char val) throws PortableException;
+
+    /**
+     * @param val Value to write.
+     * @throws PortableException In case of error.
+     */
+    public void writeBoolean(boolean val) throws PortableException;
+
+    /**
+     * @param val Value to write.
+     * @throws PortableException In case of error.
+     */
+    public void writeDecimal(@Nullable BigDecimal val) throws PortableException;
+
+    /**
+     * @param val Value to write.
+     * @throws PortableException In case of error.
+     */
+    public void writeString(@Nullable String val) throws PortableException;
+
+    /**
+     * @param val UUID to write.
+     * @throws PortableException In case of error.
+     */
+    public void writeUuid(@Nullable UUID val) throws PortableException;
+
+    /**
+     * @param val Date to write.
+     * @throws PortableException In case of error.
+     */
+    public void writeDate(@Nullable Date val) throws PortableException;
+
+    /**
+     * @param val Timestamp to write.
+     * @throws PortableException In case of error.
+     */
+    public void writeTimestamp(@Nullable Timestamp val) throws PortableException;
+
+    /**
+     * @param obj Value to write.
+     * @throws PortableException In case of error.
+     */
+    public void writeObject(@Nullable Object obj) throws PortableException;
+
+    /**
+     * @param val Value to write.
+     * @throws PortableException In case of error.
+     */
+    public void writeByteArray(@Nullable byte[] val) throws PortableException;
+
+    /**
+     * @param val Value to write.
+     * @throws PortableException In case of error.
+     */
+    public void writeShortArray(@Nullable short[] val) throws PortableException;
+
+    /**
+     * @param val Value to write.
+     * @throws PortableException In case of error.
+     */
+    public void writeIntArray(@Nullable int[] val) throws PortableException;
+
+    /**
+     * @param val Value to write.
+     * @throws PortableException In case of error.
+     */
+    public void writeLongArray(@Nullable long[] val) throws PortableException;
+
+    /**
+     * @param val Value to write.
+     * @throws PortableException In case of error.
+     */
+    public void writeFloatArray(@Nullable float[] val) throws PortableException;
+
+    /**
+     * @param val Value to write.
+     * @throws PortableException In case of error.
+     */
+    public void writeDoubleArray(@Nullable double[] val) throws PortableException;
+
+    /**
+     * @param val Value to write.
+     * @throws PortableException In case of error.
+     */
+    public void writeCharArray(@Nullable char[] val) throws PortableException;
+
+    /**
+     * @param val Value to write.
+     * @throws PortableException In case of error.
+     */
+    public void writeBooleanArray(@Nullable boolean[] val) throws PortableException;
+
+    /**
+     * @param val Value to write.
+     * @throws PortableException In case of error.
+     */
+    public void writeDecimalArray(@Nullable BigDecimal[] val) throws PortableException;
+
+    /**
+     * @param val Value to write.
+     * @throws PortableException In case of error.
+     */
+    public void writeStringArray(@Nullable String[] val) throws PortableException;
+
+    /**
+     * @param val Value to write.
+     * @throws PortableException In case of error.
+     */
+    public void writeUuidArray(@Nullable UUID[] val) throws PortableException;
+
+    /**
+     * @param val Value to write.
+     * @throws PortableException In case of error.
+     */
+    public void writeDateArray(@Nullable Date[] val) throws PortableException;
+
+    /**
+     * @param val Value to write.
+     * @throws PortableException In case of error.
+     */
+    public void writeObjectArray(@Nullable Object[] val) throws PortableException;
+
+    /**
+     * @param col Collection to write.
+     * @throws PortableException In case of error.
+     */
+    public <T> void writeCollection(@Nullable Collection<T> col) throws PortableException;
+
+    /**
+     * @param map Map to write.
+     * @throws PortableException In case of error.
+     */
+    public <K, V> void writeMap(@Nullable Map<K, V> map) throws PortableException;
+
+    /**
+     * @param val Value to write.
+     * @throws PortableException In case of error.
+     */
+    public <T extends Enum<?>> void writeEnum(T val) throws PortableException;
+
+    /**
+     * @param val Value to write.
+     * @throws PortableException In case of error.
+     */
+    public <T extends Enum<?>> void writeEnumArray(T[] val) throws PortableException;
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/portable/PortableReader.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/portable/PortableReader.java b/modules/core/src/main/java/org/apache/ignite/portable/PortableReader.java
new file mode 100644
index 0000000..82dca0c
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/portable/PortableReader.java
@@ -0,0 +1,283 @@
+/*
+ * 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.portable;
+
+import org.jetbrains.annotations.*;
+
+import java.math.*;
+import java.sql.*;
+import java.util.*;
+import java.util.Date;
+
+/**
+ * Reader for portable objects used in {@link PortableMarshalAware} implementations.
+ * Useful for the cases when user wants a fine-grained control over serialization.
+ * <p>
+ * Note that Ignite never writes full strings for field or type names. Instead,
+ * for performance reasons, Ignite writes integer hash codes for type and field names.
+ * It has been tested that hash code conflicts for the type names or the field names
+ * within the same type are virtually non-existent and, to gain performance, it is safe
+ * to work with hash codes. For the cases when hash codes for different types or fields
+ * actually do collide, Ignite provides {@link PortableIdMapper} which
+ * allows to override the automatically generated hash code IDs for the type and field names.
+ */
+public interface PortableReader {
+    /**
+     * @param fieldName Field name.
+     * @return Byte value.
+     * @throws PortableException In case of error.
+     */
+    public byte readByte(String fieldName) throws PortableException;
+
+    /**
+     * @param fieldName Field name.
+     * @return Short value.
+     * @throws PortableException In case of error.
+     */
+    public short readShort(String fieldName) throws PortableException;
+
+    /**
+     * @param fieldName Field name.
+     * @return Integer value.
+     * @throws PortableException In case of error.
+     */
+    public int readInt(String fieldName) throws PortableException;
+
+    /**
+     * @param fieldName Field name.
+     * @return Long value.
+     * @throws PortableException In case of error.
+     */
+    public long readLong(String fieldName) throws PortableException;
+
+    /**
+     * @param fieldName Field name.
+     * @throws PortableException In case of error.
+     * @return Float value.
+     */
+    public float readFloat(String fieldName) throws PortableException;
+
+    /**
+     * @param fieldName Field name.
+     * @return Double value.
+     * @throws PortableException In case of error.
+     */
+    public double readDouble(String fieldName) throws PortableException;
+
+    /**
+     * @param fieldName Field name.
+     * @return Char value.
+     * @throws PortableException In case of error.
+     */
+    public char readChar(String fieldName) throws PortableException;
+
+    /**
+     * @param fieldName Field name.
+     * @return Boolean value.
+     * @throws PortableException In case of error.
+     */
+    public boolean readBoolean(String fieldName) throws PortableException;
+
+    /**
+     * @param fieldName Field name.
+     * @return Decimal value.
+     * @throws PortableException In case of error.
+     */
+    @Nullable public BigDecimal readDecimal(String fieldName) throws PortableException;
+
+    /**
+     * @param fieldName Field name.
+     * @return String value.
+     * @throws PortableException In case of error.
+     */
+    @Nullable public String readString(String fieldName) throws PortableException;
+
+    /**
+     * @param fieldName Field name.
+     * @return UUID.
+     * @throws PortableException In case of error.
+     */
+    @Nullable public UUID readUuid(String fieldName) throws PortableException;
+
+    /**
+     * @param fieldName Field name.
+     * @return Date.
+     * @throws PortableException In case of error.
+     */
+    @Nullable public Date readDate(String fieldName) throws PortableException;
+
+    /**
+     * @param fieldName Field name.
+     * @return Timestamp.
+     * @throws PortableException In case of error.
+     */
+    @Nullable public Timestamp readTimestamp(String fieldName) throws PortableException;
+
+    /**
+     * @param fieldName Field name.
+     * @return Object.
+     * @throws PortableException In case of error.
+     */
+    @Nullable public <T> T readObject(String fieldName) throws PortableException;
+
+    /**
+     * @param fieldName Field name.
+     * @return Byte array.
+     * @throws PortableException In case of error.
+     */
+    @Nullable public byte[] readByteArray(String fieldName) throws PortableException;
+
+    /**
+     * @param fieldName Field name.
+     * @return Short array.
+     * @throws PortableException In case of error.
+     */
+    @Nullable public short[] readShortArray(String fieldName) throws PortableException;
+
+    /**
+     * @param fieldName Field name.
+     * @return Integer array.
+     * @throws PortableException In case of error.
+     */
+    @Nullable public int[] readIntArray(String fieldName) throws PortableException;
+
+    /**
+     * @param fieldName Field name.
+     * @return Long array.
+     * @throws PortableException In case of error.
+     */
+    @Nullable public long[] readLongArray(String fieldName) throws PortableException;
+
+    /**
+     * @param fieldName Field name.
+     * @return Float array.
+     * @throws PortableException In case of error.
+     */
+    @Nullable public float[] readFloatArray(String fieldName) throws PortableException;
+
+    /**
+     * @param fieldName Field name.
+     * @return Byte array.
+     * @throws PortableException In case of error.
+     */
+    @Nullable public double[] readDoubleArray(String fieldName) throws PortableException;
+
+    /**
+     * @param fieldName Field name.
+     * @return Char array.
+     * @throws PortableException In case of error.
+     */
+    @Nullable public char[] readCharArray(String fieldName) throws PortableException;
+
+    /**
+     * @param fieldName Field name.
+     * @return Boolean array.
+     * @throws PortableException In case of error.
+     */
+    @Nullable public boolean[] readBooleanArray(String fieldName) throws PortableException;
+
+    /**
+     * @param fieldName Field name.
+     * @return Decimal array.
+     * @throws PortableException In case of error.
+     */
+    @Nullable public BigDecimal[] readDecimalArray(String fieldName) throws PortableException;
+
+    /**
+     * @param fieldName Field name.
+     * @return String array.
+     * @throws PortableException In case of error.
+     */
+    @Nullable public String[] readStringArray(String fieldName) throws PortableException;
+
+    /**
+     * @param fieldName Field name.
+     * @return UUID array.
+     * @throws PortableException In case of error.
+     */
+    @Nullable public UUID[] readUuidArray(String fieldName) throws PortableException;
+
+    /**
+     * @param fieldName Field name.
+     * @return Date array.
+     * @throws PortableException In case of error.
+     */
+    @Nullable public Date[] readDateArray(String fieldName) throws PortableException;
+
+    /**
+     * @param fieldName Field name.
+     * @return Object array.
+     * @throws PortableException In case of error.
+     */
+    @Nullable public Object[] readObjectArray(String fieldName) throws PortableException;
+
+    /**
+     * @param fieldName Field name.
+     * @return Collection.
+     * @throws PortableException In case of error.
+     */
+    @Nullable public <T> Collection<T> readCollection(String fieldName) throws PortableException;
+
+    /**
+     * @param fieldName Field name.
+     * @param colCls Collection class.
+     * @return Collection.
+     * @throws PortableException In case of error.
+     */
+    @Nullable public <T> Collection<T> readCollection(String fieldName, Class<? extends Collection<T>> colCls)
+        throws PortableException;
+
+    /**
+     * @param fieldName Field name.
+     * @return Map.
+     * @throws PortableException In case of error.
+     */
+    @Nullable public <K, V> Map<K, V> readMap(String fieldName) throws PortableException;
+
+    /**
+     * @param fieldName Field name.
+     * @param mapCls Map class.
+     * @return Map.
+     * @throws PortableException In case of error.
+     */
+    @Nullable public <K, V> Map<K, V> readMap(String fieldName, Class<? extends Map<K, V>> mapCls)
+        throws PortableException;
+
+    /**
+     * @param fieldName Field name.
+     * @return Value.
+     * @throws PortableException In case of error.
+     */
+    @Nullable public <T extends Enum<?>> T readEnum(String fieldName) throws PortableException;
+
+    /**
+     * @param fieldName Field name.
+     * @return Value.
+     * @throws PortableException In case of error.
+     */
+    @Nullable public <T extends Enum<?>> T[] readEnumArray(String fieldName) throws PortableException;
+
+    /**
+     * Gets raw reader. Raw reader does not use field name hash codes, therefore,
+     * making the format even more compact. However, if the raw reader is used,
+     * dynamic structure changes to the portable objects are not supported.
+     *
+     * @return Raw reader.
+     */
+    public PortableRawReader rawReader();
+}


[46/59] [abbrv] ignite git commit: Moved platform lifecycle bean to Ignite.

Posted by vk...@apache.org.
Moved platform lifecycle bean to Ignite.


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

Branch: refs/heads/ignite-884
Commit: 6c46e47b3c04cdf03946168cfff28b759dd44348
Parents: 0e81fd0
Author: vozerov-gridgain <vo...@gridgain.com>
Authored: Wed Aug 26 13:43:18 2015 +0300
Committer: vozerov-gridgain <vo...@gridgain.com>
Committed: Wed Aug 26 13:43:18 2015 +0300

----------------------------------------------------------------------
 .../lifecycle/PlatformLifecycleBean.java        | 72 ++++++++++++++++++++
 1 file changed, 72 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/6c46e47b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/lifecycle/PlatformLifecycleBean.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/lifecycle/PlatformLifecycleBean.java b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/lifecycle/PlatformLifecycleBean.java
new file mode 100644
index 0000000..c6a83e6
--- /dev/null
+++ b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/lifecycle/PlatformLifecycleBean.java
@@ -0,0 +1,72 @@
+/*
+ * 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.platform.lifecycle;
+
+import org.apache.ignite.*;
+import org.apache.ignite.internal.processors.platform.callback.*;
+import org.apache.ignite.lifecycle.*;
+
+/**
+ * Lifecycle aware bean for interop.
+ */
+public class PlatformLifecycleBean implements LifecycleBean {
+    /** Native gateway. */
+    public PlatformCallbackGateway gate;
+
+    /** Holder pointer. */
+    public long ptr;
+
+    /**
+     * Constructor.
+     */
+    protected PlatformLifecycleBean() {
+        // No-op.
+    }
+
+    /**
+     * Constructor.
+     *
+     * @param gate Native gateway.
+     * @param ptr Holder pointer.
+     */
+    public PlatformLifecycleBean(PlatformCallbackGateway gate, long ptr) {
+        initialize(gate, ptr);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void onLifecycleEvent(LifecycleEventType evt) {
+        if (gate == null)
+            throw new IgniteException("Interop lifecycle bean can only be used in interop mode (did " +
+                    "you start the node with native platform bootstrapper?");
+
+        assert ptr != 0;
+
+        gate.lifecycleEvent(ptr, evt.ordinal());
+    }
+
+    /**
+     * Set pointers.
+     *
+     * @param gate Native gateway.
+     * @param ptr Target pointer.
+     */
+    public void initialize(PlatformCallbackGateway gate, long ptr) {
+        this.gate = gate;
+        this.ptr = ptr;
+    }
+}


[53/59] [abbrv] ignite git commit: Platforms: minor refactoring: interopCtx -> platformCtx.

Posted by vk...@apache.org.
Platforms: minor refactoring: interopCtx -> platformCtx.


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

Branch: refs/heads/ignite-884
Commit: d9a13974b6e7c5fdd2b533e806e928fcca33bbaa
Parents: 8df6b93
Author: vozerov-gridgain <vo...@gridgain.com>
Authored: Wed Aug 26 16:03:25 2015 +0300
Committer: vozerov-gridgain <vo...@gridgain.com>
Committed: Wed Aug 26 16:03:25 2015 +0300

----------------------------------------------------------------------
 .../platform/PlatformAbstractTarget.java        | 44 ++++++++++----------
 .../query/PlatformAbstractQueryCursor.java      |  6 +--
 .../cache/query/PlatformFieldsQueryCursor.java  |  6 +--
 .../cache/query/PlatformQueryCursor.java        |  6 +--
 .../transactions/PlatformTransactions.java      | 12 +++---
 .../platform/utils/PlatformFutureUtils.java     | 12 +++---
 .../platform/utils/PlatformUtils.java           |  4 +-
 7 files changed, 45 insertions(+), 45 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/d9a13974/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/PlatformAbstractTarget.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/PlatformAbstractTarget.java b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/PlatformAbstractTarget.java
index ec728e4..b68b16e 100644
--- a/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/PlatformAbstractTarget.java
+++ b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/PlatformAbstractTarget.java
@@ -37,8 +37,8 @@ public abstract class PlatformAbstractTarget implements PlatformTarget {
     /** */
     private static final int OP_META = -1;
 
-    /** Interop context. */
-    protected final PlatformContext interopCtx;
+    /** Context. */
+    protected final PlatformContext platformCtx;
 
     /** Logger. */
     protected final IgniteLogger log;
@@ -46,21 +46,21 @@ public abstract class PlatformAbstractTarget implements PlatformTarget {
     /**
      * Constructor.
      *
-     * @param interopCtx Interop context.
+     * @param platformCtx Context.
      */
-    protected PlatformAbstractTarget(PlatformContext interopCtx) {
-        this.interopCtx = interopCtx;
+    protected PlatformAbstractTarget(PlatformContext platformCtx) {
+        this.platformCtx = platformCtx;
 
-        log = interopCtx.kernalContext().log(PlatformAbstractTarget.class);
+        log = platformCtx.kernalContext().log(PlatformAbstractTarget.class);
     }
 
     /** {@inheritDoc} */
     @Override public int inOp(int type, long memPtr) throws Exception {
-        try (PlatformMemory mem = interopCtx.memory().get(memPtr)) {
-            PortableRawReaderEx reader = interopCtx.reader(mem);
+        try (PlatformMemory mem = platformCtx.memory().get(memPtr)) {
+            PortableRawReaderEx reader = platformCtx.reader(mem);
 
             if (type == OP_META) {
-                interopCtx.processMetadata(reader);
+                platformCtx.processMetadata(reader);
 
                 return TRUE;
             }
@@ -74,8 +74,8 @@ public abstract class PlatformAbstractTarget implements PlatformTarget {
 
     /** {@inheritDoc} */
     @Override public Object inOpObject(int type, long memPtr) throws Exception {
-        try (PlatformMemory mem = interopCtx.memory().get(memPtr)) {
-            PortableRawReaderEx reader = interopCtx.reader(mem);
+        try (PlatformMemory mem = platformCtx.memory().get(memPtr)) {
+            PortableRawReaderEx reader = platformCtx.reader(mem);
 
             return processInOpObject(type, reader);
         }
@@ -86,10 +86,10 @@ public abstract class PlatformAbstractTarget implements PlatformTarget {
 
     /** {@inheritDoc} */
     @Override public void outOp(int type, long memPtr) throws Exception {
-        try (PlatformMemory mem = interopCtx.memory().get(memPtr)) {
+        try (PlatformMemory mem = platformCtx.memory().get(memPtr)) {
             PlatformOutputStream out = mem.output();
 
-            PortableRawWriterEx writer = interopCtx.writer(out);
+            PortableRawWriterEx writer = platformCtx.writer(out);
 
             processOutOp(type, writer);
 
@@ -107,13 +107,13 @@ public abstract class PlatformAbstractTarget implements PlatformTarget {
 
     /** {@inheritDoc} */
     @Override public void inOutOp(int type, long inMemPtr, long outMemPtr, Object arg) throws Exception {
-        try (PlatformMemory inMem = interopCtx.memory().get(inMemPtr)) {
-            PortableRawReaderEx reader = interopCtx.reader(inMem);
+        try (PlatformMemory inMem = platformCtx.memory().get(inMemPtr)) {
+            PortableRawReaderEx reader = platformCtx.reader(inMem);
 
-            try (PlatformMemory outMem = interopCtx.memory().get(outMemPtr)) {
+            try (PlatformMemory outMem = platformCtx.memory().get(outMemPtr)) {
                 PlatformOutputStream out = outMem.output();
 
-                PortableRawWriterEx writer = interopCtx.writer(out);
+                PortableRawWriterEx writer = platformCtx.writer(out);
 
                 processInOutOp(type, reader, writer, arg);
 
@@ -136,10 +136,10 @@ public abstract class PlatformAbstractTarget implements PlatformTarget {
     }
 
     /**
-     * @return Interop context.
+     * @return Context.
      */
-    public PlatformContext interopContext() {
-        return interopCtx;
+    public PlatformContext platformContext() {
+        return platformCtx;
     }
 
     /**
@@ -150,7 +150,7 @@ public abstract class PlatformAbstractTarget implements PlatformTarget {
      */
     @SuppressWarnings("UnusedDeclaration")
     public void listenFuture(final long futId, int typ) throws IgniteCheckedException {
-        PlatformFutureUtils.listen(interopCtx, currentFutureWrapped(), futId, typ, null);
+        PlatformFutureUtils.listen(platformCtx, currentFutureWrapped(), futId, typ, null);
     }
 
     /**
@@ -162,7 +162,7 @@ public abstract class PlatformAbstractTarget implements PlatformTarget {
      */
     @SuppressWarnings("UnusedDeclaration")
     public void listenFuture(final long futId, int typ, int opId) throws IgniteCheckedException {
-        PlatformFutureUtils.listen(interopCtx, currentFutureWrapped(), futId, typ, futureWriter(opId));
+        PlatformFutureUtils.listen(platformCtx, currentFutureWrapped(), futId, typ, futureWriter(opId));
     }
 
     /**

http://git-wip-us.apache.org/repos/asf/ignite/blob/d9a13974/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/cache/query/PlatformAbstractQueryCursor.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/cache/query/PlatformAbstractQueryCursor.java b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/cache/query/PlatformAbstractQueryCursor.java
index cdd29fd..c01da0e 100644
--- a/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/cache/query/PlatformAbstractQueryCursor.java
+++ b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/cache/query/PlatformAbstractQueryCursor.java
@@ -50,12 +50,12 @@ public abstract class PlatformAbstractQueryCursor<T> extends PlatformAbstractTar
     /**
      * Constructor.
      *
-     * @param interopCtx Interop context.
+     * @param platformCtx Context.
      * @param cursor Underlying cursor.
      * @param batchSize Batch size.
      */
-    public PlatformAbstractQueryCursor(PlatformContext interopCtx, QueryCursorEx<T> cursor, int batchSize) {
-        super(interopCtx);
+    public PlatformAbstractQueryCursor(PlatformContext platformCtx, QueryCursorEx<T> cursor, int batchSize) {
+        super(platformCtx);
 
         this.cursor = cursor;
         this.batchSize = batchSize;

http://git-wip-us.apache.org/repos/asf/ignite/blob/d9a13974/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/cache/query/PlatformFieldsQueryCursor.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/cache/query/PlatformFieldsQueryCursor.java b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/cache/query/PlatformFieldsQueryCursor.java
index f18a79a..6b2902c 100644
--- a/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/cache/query/PlatformFieldsQueryCursor.java
+++ b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/cache/query/PlatformFieldsQueryCursor.java
@@ -30,12 +30,12 @@ public class PlatformFieldsQueryCursor extends PlatformAbstractQueryCursor<List<
     /**
      * Constructor.
      *
-     * @param interopCtx Interop context.
+     * @param platformCtx Platform context.
      * @param cursor Backing cursor.
      * @param batchSize Batch size.
      */
-    public PlatformFieldsQueryCursor(PlatformContext interopCtx, QueryCursorEx<List<?>> cursor, int batchSize) {
-        super(interopCtx, cursor, batchSize);
+    public PlatformFieldsQueryCursor(PlatformContext platformCtx, QueryCursorEx<List<?>> cursor, int batchSize) {
+        super(platformCtx, cursor, batchSize);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/d9a13974/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/cache/query/PlatformQueryCursor.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/cache/query/PlatformQueryCursor.java b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/cache/query/PlatformQueryCursor.java
index cc96d6f..0d323a3 100644
--- a/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/cache/query/PlatformQueryCursor.java
+++ b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/cache/query/PlatformQueryCursor.java
@@ -30,12 +30,12 @@ public class PlatformQueryCursor extends PlatformAbstractQueryCursor<Cache.Entry
     /**
      * Constructor.
      *
-     * @param interopCtx Interop context.
+     * @param platformCtx Context.
      * @param cursor Backing cursor.
      * @param batchSize Batch size.
      */
-    public PlatformQueryCursor(PlatformContext interopCtx, QueryCursorEx<Cache.Entry> cursor, int batchSize) {
-        super(interopCtx, cursor, batchSize);
+    public PlatformQueryCursor(PlatformContext platformCtx, QueryCursorEx<Cache.Entry> cursor, int batchSize) {
+        super(platformCtx, cursor, batchSize);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/d9a13974/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/transactions/PlatformTransactions.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/transactions/PlatformTransactions.java b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/transactions/PlatformTransactions.java
index fa63840..aedc380 100644
--- a/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/transactions/PlatformTransactions.java
+++ b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/transactions/PlatformTransactions.java
@@ -54,12 +54,12 @@ public class PlatformTransactions extends PlatformAbstractTarget {
     /**
      * Constructor.
      *
-     * @param interopCtx Interop context.
+     * @param platformCtx Context.
      */
-    public PlatformTransactions(PlatformContext interopCtx) {
-        super(interopCtx);
+    public PlatformTransactions(PlatformContext platformCtx) {
+        super(platformCtx);
 
-        txs = interopCtx.kernalContext().grid().transactions();
+        txs = platformCtx.kernalContext().grid().transactions();
     }
 
     /**
@@ -175,7 +175,7 @@ public class PlatformTransactions extends PlatformAbstractTarget {
             }
         });
 
-        PlatformFutureUtils.listen(interopCtx, fut, futId, PlatformFutureUtils.TYP_OBJ);
+        PlatformFutureUtils.listen(platformCtx, fut, futId, PlatformFutureUtils.TYP_OBJ);
     }
 
     /**
@@ -230,7 +230,7 @@ public class PlatformTransactions extends PlatformAbstractTarget {
     @Override protected void processOutOp(int type, PortableRawWriterEx writer) throws IgniteCheckedException {
         switch (type) {
             case OP_CACHE_CONFIG_PARAMETERS:
-                TransactionConfiguration txCfg = interopCtx.kernalContext().config().getTransactionConfiguration();
+                TransactionConfiguration txCfg = platformCtx.kernalContext().config().getTransactionConfiguration();
 
                 writer.writeEnum(txCfg.getDefaultTxConcurrency());
                 writer.writeEnum(txCfg.getDefaultTxIsolation());

http://git-wip-us.apache.org/repos/asf/ignite/blob/d9a13974/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/utils/PlatformFutureUtils.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/utils/PlatformFutureUtils.java b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/utils/PlatformFutureUtils.java
index fa986fe..677cb1c 100644
--- a/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/utils/PlatformFutureUtils.java
+++ b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/utils/PlatformFutureUtils.java
@@ -58,7 +58,7 @@ public class PlatformFutureUtils {
     /**
      * Listen future.
      *
-     * @param ctx Interop context.
+     * @param ctx Context.
      * @param fut Java future.
      * @param futPtr Native future pointer.
      * @param typ Expected return type.
@@ -70,7 +70,7 @@ public class PlatformFutureUtils {
     /**
      * Listen future.
      *
-     * @param ctx Interop context.
+     * @param ctx Context.
      * @param fut Java future.
      * @param futPtr Native future pointer.
      * @param typ Expected return type.
@@ -84,7 +84,7 @@ public class PlatformFutureUtils {
     /**
      * Listen future.
      *
-     * @param ctx Interop context.
+     * @param ctx Context.
      * @param fut Java future.
      * @param futPtr Native future pointer.
      * @param writer Writer.
@@ -96,7 +96,7 @@ public class PlatformFutureUtils {
     /**
      * Listen future.
      *
-     * @param ctx Interop context.
+     * @param ctx Context.
      * @param listenable Listenable entry.
      * @param futPtr Native future pointer.
      * @param typ Expected return type.
@@ -200,7 +200,7 @@ public class PlatformFutureUtils {
     /**
      * Write future error.
      *
-     * @param ctx Interop context.
+     * @param ctx Context.
      * @param futPtr Future pointer.
      * @param err Error.
      */
@@ -226,7 +226,7 @@ public class PlatformFutureUtils {
      *
      * @param obj Object to write.
      * @param err Error to write.
-     * @param ctx Interop context.
+     * @param ctx Context.
      * @param writer Writer.
      * @param futPtr Future pointer.
      * @return Value indicating whether custom write was performed. When false, default write will be used.

http://git-wip-us.apache.org/repos/asf/ignite/blob/d9a13974/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/utils/PlatformUtils.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/utils/PlatformUtils.java b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/utils/PlatformUtils.java
index 614346a..66e87e2 100644
--- a/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/utils/PlatformUtils.java
+++ b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/utils/PlatformUtils.java
@@ -434,7 +434,7 @@ public class PlatformUtils {
     /**
      * Apply continuous query events to listener.
      *
-     * @param ctx Interop context.
+     * @param ctx Context.
      * @param lsnrPtr Listener pointer.
      * @param evts Events.
      * @throws javax.cache.event.CacheEntryListenerException In case of failure.
@@ -473,7 +473,7 @@ public class PlatformUtils {
     /**
      * Evaluate the filter.
      *
-     * @param ctx Interop context.
+     * @param ctx Context.
      * @param filterPtr Native filter pointer.
      * @param evt Event.
      * @return Result.


[58/59] [abbrv] ignite git commit: Merge remote-tracking branch 'apache/master' into ignite-884

Posted by vk...@apache.org.
Merge remote-tracking branch 'apache/master' into ignite-884

# Conflicts:
#	modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheProcessor.java


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

Branch: refs/heads/ignite-884
Commit: e34872d3f687c61eee5c10062a2425477b205841
Parents: 3b20010 e428206
Author: Valentin Kulichenko <va...@gmail.com>
Authored: Wed Aug 26 17:10:25 2015 -0700
Committer: Valentin Kulichenko <va...@gmail.com>
Committed: Wed Aug 26 17:10:25 2015 -0700

----------------------------------------------------------------------
 assembly/dependencies-hadoop.xml                |    1 +
 .../examples/igfs/IgfsMapReduceExample.java     |    3 +
 .../examples/servicegrid/ServicesExample.java   |   13 +-
 .../ignite/codegen/MessageCodeGenerator.java    |   30 +-
 modules/core/pom.xml                            |   21 +
 .../src/main/java/org/apache/ignite/Ignite.java |    7 +
 .../java/org/apache/ignite/IgniteCache.java     |   41 +
 .../java/org/apache/ignite/IgnitePortables.java |  362 ++
 .../configuration/CacheConfiguration.java       |   40 +
 .../configuration/IgniteConfiguration.java      |   22 +
 .../configuration/PlatformConfiguration.java    |   25 +
 .../internal/GridEventConsumeHandler.java       |   14 +-
 .../ignite/internal/GridJobCancelRequest.java   |    2 +-
 .../ignite/internal/GridJobExecuteRequest.java  |    2 +-
 .../ignite/internal/GridJobExecuteResponse.java |    2 +-
 .../ignite/internal/GridJobSiblingsRequest.java |    2 +-
 .../internal/GridJobSiblingsResponse.java       |    2 +-
 .../ignite/internal/GridKernalContext.java      |    6 +
 .../ignite/internal/GridKernalContextImpl.java  |   15 +-
 .../ignite/internal/GridTaskCancelRequest.java  |    2 +-
 .../ignite/internal/GridTaskSessionRequest.java |    2 +-
 .../org/apache/ignite/internal/IgniteEx.java    |    1 +
 .../apache/ignite/internal/IgniteKernal.java    |   13 +-
 .../internal/direct/DirectByteBufferStream.java |    2 +-
 .../internal/direct/DirectMessageReader.java    |    6 +
 .../interop/InteropAwareEventFilter.java        |   37 -
 .../internal/interop/InteropBootstrap.java      |   35 -
 .../interop/InteropBootstrapFactory.java        |   39 -
 .../internal/interop/InteropException.java      |   71 -
 .../internal/interop/InteropIgnition.java       |  186 -
 .../interop/InteropLocalEventListener.java      |   28 -
 .../interop/InteropNoCallbackException.java     |   50 -
 .../internal/interop/InteropProcessor.java      |   39 -
 .../checkpoint/GridCheckpointRequest.java       |    2 +-
 .../managers/communication/GridIoManager.java   |    2 +-
 .../managers/communication/GridIoMessage.java   |    8 +-
 .../communication/GridIoMessageFactory.java     |    6 +
 .../communication/GridIoUserMessage.java        |    2 +-
 .../deployment/GridDeploymentInfoBean.java      |    2 +-
 .../deployment/GridDeploymentRequest.java       |    2 +-
 .../deployment/GridDeploymentResponse.java      |    2 +-
 .../eventstorage/GridEventStorageManager.java   |   10 +-
 .../eventstorage/GridEventStorageMessage.java   |    2 +-
 .../portable/GridPortableMarshaller.java        |  304 ++
 .../portable/PortableAbstractLazyValue.java     |   57 +
 .../internal/portable/PortableBuilderEnum.java  |  114 +
 .../internal/portable/PortableBuilderImpl.java  |  519 +++
 .../portable/PortableBuilderReader.java         |  775 ++++
 .../PortableBuilderSerializationAware.java      |   29 +
 .../portable/PortableBuilderSerializer.java     |  210 +
 .../portable/PortableClassDescriptor.java       | 1344 +++++++
 .../internal/portable/PortableContext.java      | 1088 ++++++
 .../portable/PortableEnumArrayLazyValue.java    |  111 +
 .../portable/PortableLazyArrayList.java         |  156 +
 .../portable/PortableLazyLinkedList.java        |  210 +
 .../internal/portable/PortableLazyMap.java      |  214 +
 .../internal/portable/PortableLazyMapEntry.java |   66 +
 .../internal/portable/PortableLazySet.java      |   89 +
 .../internal/portable/PortableLazyValue.java    |   28 +
 .../portable/PortableMetaDataCollector.java     |  253 ++
 .../portable/PortableMetaDataHandler.java       |   43 +
 .../internal/portable/PortableMetaDataImpl.java |  140 +
 .../portable/PortableObjectArrayLazyValue.java  |   89 +
 .../internal/portable/PortableObjectEx.java     |  213 +
 .../internal/portable/PortableObjectImpl.java   |  383 ++
 .../portable/PortableObjectOffheapImpl.java     |  238 ++
 .../portable/PortablePlainLazyValue.java        |   47 +
 .../portable/PortablePlainPortableObject.java   |   50 +
 .../internal/portable/PortablePrimitives.java   |  773 ++++
 .../internal/portable/PortableRawReaderEx.java  |   33 +
 .../internal/portable/PortableRawWriterEx.java  |   60 +
 .../portable/PortableReaderContext.java         |   83 +
 .../internal/portable/PortableReaderExImpl.java | 2949 ++++++++++++++
 .../PortableThreadLocalMemoryAllocator.java     |  163 +
 .../ignite/internal/portable/PortableUtils.java |  419 ++
 .../portable/PortableValueWithType.java         |   74 +
 .../internal/portable/PortableWriterExImpl.java | 1759 +++++++++
 .../ignite/internal/portable/package-info.java  |   22 +
 .../streams/PortableAbstractInputStream.java    |  343 ++
 .../streams/PortableAbstractOutputStream.java   |  323 ++
 .../streams/PortableAbstractStream.java         |   82 +
 .../streams/PortableHeapInputStream.java        |  134 +
 .../streams/PortableHeapOutputStream.java       |  155 +
 .../portable/streams/PortableInputStream.java   |  168 +
 .../streams/PortableMemoryAllocator.java        |   76 +
 .../streams/PortableOffheapInputStream.java     |  129 +
 .../streams/PortableOffheapOutputStream.java    |  169 +
 .../portable/streams/PortableOutputStream.java  |  165 +
 .../streams/PortableSimpleMemoryAllocator.java  |   67 +
 .../portable/streams/PortableStream.java        |   53 +
 .../internal/portable/streams/package-info.java |   22 +
 .../affinity/AffinityTopologyVersion.java       |    2 +-
 .../cache/CacheEntryInfoCollection.java         |    2 +-
 .../cache/CacheEntryPredicateAdapter.java       |    2 +-
 .../cache/CacheEntryPredicateContainsValue.java |    2 +-
 .../cache/CacheEntrySerializablePredicate.java  |    2 +-
 .../processors/cache/CacheEvictionEntry.java    |    2 +-
 .../cache/CacheInvokeDirectResult.java          |    2 +-
 .../processors/cache/CacheObjectAdapter.java    |    2 +-
 .../cache/CacheObjectByteArrayImpl.java         |    2 +-
 .../processors/cache/GridCacheEntryInfo.java    |    2 +-
 .../cache/GridCacheEvictionRequest.java         |    2 +-
 .../cache/GridCacheEvictionResponse.java        |    2 +-
 .../processors/cache/GridCacheMessage.java      |    2 +-
 .../processors/cache/GridCacheProcessor.java    |   69 +-
 .../processors/cache/GridCacheReturn.java       |    2 +-
 .../processors/cache/IgniteCacheProxy.java      |    5 +
 .../distributed/GridCacheTtlUpdateRequest.java  |    3 +-
 .../distributed/GridCacheTxRecoveryRequest.java |    2 +-
 .../GridCacheTxRecoveryResponse.java            |    2 +-
 .../distributed/GridDistributedBaseMessage.java |    2 +-
 .../distributed/GridDistributedLockRequest.java |    2 +-
 .../GridDistributedLockResponse.java            |    2 +-
 .../GridDistributedTxFinishRequest.java         |    8 +-
 .../GridDistributedTxFinishResponse.java        |    2 +-
 .../GridDistributedTxPrepareRequest.java        |    8 +-
 .../GridDistributedTxPrepareResponse.java       |    2 +-
 .../GridDistributedUnlockRequest.java           |    2 +-
 .../dht/GridDhtAffinityAssignmentRequest.java   |    2 +-
 .../dht/GridDhtAffinityAssignmentResponse.java  |    2 +-
 .../distributed/dht/GridDhtLockRequest.java     |    6 +-
 .../distributed/dht/GridDhtLockResponse.java    |    2 +-
 .../distributed/dht/GridDhtTxFinishRequest.java |    2 +-
 .../dht/GridDhtTxFinishResponse.java            |    2 +-
 .../dht/GridDhtTxPrepareRequest.java            |    2 +-
 .../dht/GridDhtTxPrepareResponse.java           |    2 +-
 .../distributed/dht/GridDhtUnlockRequest.java   |    2 +-
 .../GridDhtAtomicDeferredUpdateResponse.java    |    2 +-
 .../dht/atomic/GridDhtAtomicUpdateRequest.java  |    2 +-
 .../dht/atomic/GridDhtAtomicUpdateResponse.java |    2 +-
 .../dht/atomic/GridNearAtomicUpdateRequest.java |    2 +-
 .../atomic/GridNearAtomicUpdateResponse.java    |    2 +-
 .../dht/preloader/GridDhtForceKeysRequest.java  |    3 +-
 .../dht/preloader/GridDhtForceKeysResponse.java |    4 +-
 .../GridDhtPartitionDemandMessage.java          |    2 +-
 .../preloader/GridDhtPartitionExchangeId.java   |    2 +-
 .../GridDhtPartitionSupplyMessage.java          |    2 +-
 .../GridDhtPartitionsAbstractMessage.java       |    2 +-
 .../preloader/GridDhtPartitionsFullMessage.java |    2 +-
 .../GridDhtPartitionsSingleMessage.java         |    2 +-
 .../GridDhtPartitionsSingleRequest.java         |    2 +-
 .../distributed/near/CacheVersionedValue.java   |    2 +-
 .../distributed/near/GridNearGetRequest.java    |    2 +-
 .../distributed/near/GridNearGetResponse.java   |    2 +-
 .../distributed/near/GridNearLockRequest.java   |    2 +-
 .../distributed/near/GridNearLockResponse.java  |    2 +-
 .../near/GridNearTxFinishRequest.java           |    2 +-
 .../near/GridNearTxFinishResponse.java          |    2 +-
 .../near/GridNearTxPrepareRequest.java          |    2 +-
 .../near/GridNearTxPrepareResponse.java         |    2 +-
 .../distributed/near/GridNearUnlockRequest.java |    2 +-
 .../CacheDefaultPortableAffinityKeyMapper.java  |   51 +
 .../portable/CacheObjectPortableContext.java    |  187 +
 .../portable/CacheObjectPortableProcessor.java  |  101 +
 .../CacheObjectPortableProcessorImpl.java       |  957 +++++
 .../cache/portable/IgnitePortablesImpl.java     |  176 +
 .../cache/portable/PortableMetaDataKey.java     |   80 +
 .../processors/cache/portable/package-info.java |   22 +
 .../cache/query/GridCacheQueryRequest.java      |    2 +-
 .../cache/query/GridCacheQueryResponse.java     |    2 +-
 .../cache/query/GridCacheSqlQuery.java          |    9 +-
 .../continuous/CacheContinuousQueryEntry.java   |    2 +-
 .../cache/store/CacheOsStoreManager.java        |    3 +-
 .../cache/transactions/IgniteTxEntry.java       |    2 +-
 .../cache/transactions/IgniteTxKey.java         |    2 +-
 .../cache/transactions/TxEntryValueHolder.java  |    2 +-
 .../version/GridCacheRawVersionedEntry.java     |    2 +-
 .../cache/version/GridCacheVersion.java         |    2 +-
 .../cache/version/GridCacheVersionEx.java       |    2 +-
 .../cacheobject/IgniteCacheObjectProcessor.java |    2 +-
 .../IgniteCacheObjectProcessorImpl.java         |    2 +-
 .../clock/GridClockDeltaSnapshotMessage.java    |    2 +-
 .../processors/clock/GridClockDeltaVersion.java |    2 +-
 .../continuous/GridContinuousMessage.java       |    2 +-
 .../datastreamer/DataStreamerEntry.java         |    2 +-
 .../datastreamer/DataStreamerRequest.java       |    2 +-
 .../datastreamer/DataStreamerResponse.java      |    2 +-
 .../processors/igfs/IgfsAckMessage.java         |    2 +-
 .../internal/processors/igfs/IgfsBlockKey.java  |    2 +-
 .../processors/igfs/IgfsBlocksMessage.java      |    2 +-
 .../igfs/IgfsCommunicationMessage.java          |    2 +-
 .../processors/igfs/IgfsDeleteMessage.java      |    2 +-
 .../processors/igfs/IgfsFileAffinityRange.java  |    9 +-
 .../igfs/IgfsFragmentizerRequest.java           |    2 +-
 .../igfs/IgfsFragmentizerResponse.java          |    2 +-
 .../internal/processors/igfs/IgfsProcessor.java |    8 -
 .../processors/igfs/IgfsSyncMessage.java        |    2 +-
 .../platform/PlatformAwareEventFilter.java      |   37 +
 .../platform/PlatformLocalEventListener.java    |   28 +
 .../platform/PlatformNoopProcessor.java         |   41 +
 .../processors/platform/PlatformProcessor.java  |   40 +
 .../portable/GridPortableInputStream.java       |  168 -
 .../portable/GridPortableOutputStream.java      |  165 -
 .../processors/portable/GridPortableStream.java |   53 -
 .../processors/portable/package-info.java       |   22 -
 .../processors/query/GridQueryProcessor.java    |    2 +-
 .../messages/GridQueryCancelRequest.java        |    2 +-
 .../twostep/messages/GridQueryFailResponse.java |    2 +-
 .../messages/GridQueryNextPageRequest.java      |    2 +-
 .../messages/GridQueryNextPageResponse.java     |    3 +-
 .../h2/twostep/messages/GridQueryRequest.java   |    5 +-
 .../handlers/task/GridTaskResultRequest.java    |    2 +-
 .../handlers/task/GridTaskResultResponse.java   |    2 +-
 .../ignite/internal/util/GridByteArrayList.java |    2 +-
 .../ignite/internal/util/GridLongList.java      |    2 +-
 .../internal/util/nio/GridDirectParser.java     |    2 +-
 .../visor/cache/VisorCacheClearTask.java        |   11 +-
 .../marshaller/portable/PortableMarshaller.java |  347 ++
 .../marshaller/portable/package-info.java       |   22 +
 .../communication/MessageFormatter.java         |    3 +-
 .../extensions/communication/MessageReader.java |   13 +
 .../apache/ignite/portable/PortableBuilder.java |  138 +
 .../ignite/portable/PortableException.java      |   58 +
 .../ignite/portable/PortableIdMapper.java       |   56 +
 .../portable/PortableInvalidClassException.java |   58 +
 .../ignite/portable/PortableMarshalAware.java   |   48 +
 .../ignite/portable/PortableMetadata.java       |   63 +
 .../apache/ignite/portable/PortableObject.java  |  153 +
 .../portable/PortableProtocolVersion.java       |   41 +
 .../ignite/portable/PortableRawReader.java      |  233 ++
 .../ignite/portable/PortableRawWriter.java      |  218 ++
 .../apache/ignite/portable/PortableReader.java  |  283 ++
 .../ignite/portable/PortableSerializer.java     |   49 +
 .../portable/PortableTypeConfiguration.java     |  197 +
 .../apache/ignite/portable/PortableWriter.java  |  265 ++
 .../apache/ignite/portable/package-info.java    |   22 +
 .../org/apache/ignite/spi/IgniteSpiAdapter.java |    2 +-
 .../jobstealing/JobStealingRequest.java         |    2 +-
 .../communication/tcp/TcpCommunicationSpi.java  |    8 +-
 .../spi/discovery/tcp/TcpDiscoverySpi.java      |    9 +-
 .../resources/META-INF/classnames.properties    |  287 +-
 .../GridPortableAffinityKeySelfTest.java        |  215 +
 .../GridPortableBuilderAdditionalSelfTest.java  | 1001 +++++
 .../portable/GridPortableBuilderSelfTest.java   | 1007 +++++
 ...eBuilderStringAsCharsAdditionalSelfTest.java |   28 +
 ...ridPortableBuilderStringAsCharsSelfTest.java |   28 +
 ...idPortableMarshallerCtxDisabledSelfTest.java |  128 +
 .../GridPortableMarshallerSelfTest.java         | 3691 ++++++++++++++++++
 .../GridPortableMetaDataDisabledSelfTest.java   |  218 ++
 .../portable/GridPortableMetaDataSelfTest.java  |  343 ++
 .../portable/GridPortableWildcardsSelfTest.java |  480 +++
 .../GridPortableMarshalerAwareTestClass.java    |   62 +
 .../mutabletest/GridPortableTestClasses.java    |  425 ++
 .../portable/mutabletest/package-info.java      |   22 +
 .../ignite/internal/portable/package-info.java  |   22 +
 .../portable/test/GridPortableTestClass1.java   |   28 +
 .../portable/test/GridPortableTestClass2.java   |   24 +
 .../internal/portable/test/package-info.java    |   22 +
 .../test/subpackage/GridPortableTestClass3.java |   24 +
 .../portable/test/subpackage/package-info.java  |   22 +
 .../GridCacheDaemonNodeAbstractSelfTest.java    |    9 +-
 .../IgniteCacheManyAsyncOperationsTest.java     |  107 +
 .../near/IgniteCacheNearOnlyTxTest.java         |   82 +-
 .../local/GridCacheDaemonNodeLocalSelfTest.java |   30 -
 ...ClientNodePortableMetadataMultinodeTest.java |  277 ++
 ...GridCacheClientNodePortableMetadataTest.java |  280 ++
 ...ableObjectsAbstractDataStreamerSelfTest.java |  183 +
 ...bleObjectsAbstractMultiThreadedSelfTest.java |  222 ++
 ...ridCachePortableObjectsAbstractSelfTest.java |  958 +++++
 .../GridCachePortableStoreAbstractSelfTest.java |  294 ++
 .../GridCachePortableStoreObjectsSelfTest.java  |   55 +
 ...GridCachePortableStorePortablesSelfTest.java |   67 +
 ...ridPortableCacheEntryMemorySizeSelfTest.java |   52 +
 ...leDuplicateIndexObjectsAbstractSelfTest.java |  153 +
 .../DataStreamProcessorPortableSelfTest.java    |   67 +
 .../GridDataStreamerImplSelfTest.java           |  338 ++
 ...ridCacheAffinityRoutingPortableSelfTest.java |   48 +
 ...lyPortableDataStreamerMultiNodeSelfTest.java |   29 +
 ...rtableDataStreamerMultithreadedSelfTest.java |   46 +
 ...artitionedOnlyPortableMultiNodeSelfTest.java |   28 +
 ...tionedOnlyPortableMultithreadedSelfTest.java |   46 +
 .../GridCacheMemoryModePortableSelfTest.java    |   36 +
 ...acheOffHeapTieredAtomicPortableSelfTest.java |   48 +
 ...eapTieredEvictionAtomicPortableSelfTest.java |   96 +
 ...heOffHeapTieredEvictionPortableSelfTest.java |   96 +
 .../GridCacheOffHeapTieredPortableSelfTest.java |   48 +
 ...ateIndexObjectPartitionedAtomicSelfTest.java |   37 +
 ...xObjectPartitionedTransactionalSelfTest.java |   40 +
 ...AtomicNearDisabledOffheapTieredSelfTest.java |   29 +
 ...rtableObjectsAtomicNearDisabledSelfTest.java |   50 +
 ...tableObjectsAtomicOffheapTieredSelfTest.java |   29 +
 .../GridCachePortableObjectsAtomicSelfTest.java |   50 +
 ...tionedNearDisabledOffheapTieredSelfTest.java |   30 +
 ...eObjectsPartitionedNearDisabledSelfTest.java |   50 +
 ...ObjectsPartitionedOffheapTieredSelfTest.java |   30 +
 ...CachePortableObjectsPartitionedSelfTest.java |   50 +
 ...sNearPartitionedByteArrayValuesSelfTest.java |   41 +
 ...sPartitionedOnlyByteArrayValuesSelfTest.java |   42 +
 ...dCachePortableObjectsReplicatedSelfTest.java |   50 +
 ...CachePortableObjectsAtomicLocalSelfTest.java |   32 +
 ...rtableObjectsLocalOffheapTieredSelfTest.java |   29 +
 .../GridCachePortableObjectsLocalSelfTest.java  |   50 +
 .../processors/igfs/IgfsAbstractSelfTest.java   |   34 +-
 .../igfs/IgfsBackupFailoverSelfTest.java        |  488 +++
 .../igfs/IgfsBackupsDualAsyncSelfTest.java      |   40 +
 .../igfs/IgfsBackupsDualSyncSelfTest.java       |   40 +
 .../igfs/IgfsBackupsPrimarySelfTest.java        |   40 +
 .../tcp/TcpDiscoverySpiStartStopSelfTest.java   |    2 +-
 .../testframework/GridSpiTestContext.java       |    2 +-
 .../ignite/testframework/junits/IgniteMock.java |    5 +
 .../multijvm/IgniteCacheProcessProxy.java       |    5 +
 .../junits/multijvm/IgniteProcessProxy.java     |    5 +
 .../ignite/testsuites/IgniteCacheTestSuite.java |    1 +
 .../ignite/testsuites/IgniteIgfsTestSuite.java  |    7 +
 .../IgnitePortableCacheFullApiTestSuite.java    |   38 +
 .../IgnitePortableCacheTestSuite.java           |   86 +
 .../IgnitePortableObjectsTestSuite.java         |   74 +
 .../ignite/portable/test1/1.1/test1-1.1.jar     |  Bin 0 -> 2548 bytes
 .../ignite/portable/test1/1.1/test1-1.1.pom     |    9 +
 .../portable/test1/maven-metadata-local.xml     |   12 +
 .../ignite/portable/test2/1.1/test2-1.1.jar     |  Bin 0 -> 1361 bytes
 .../ignite/portable/test2/1.1/test2-1.1.pom     |    9 +
 .../portable/test2/maven-metadata-local.xml     |   12 +
 .../IgnitePortableCacheQueryTestSuite.java      |   95 +
 modules/platform/pom.xml                        |   65 +
 .../Apache.Ignite.Core.csproj                   |   97 +
 .../Common/AsyncSupportedAttribute.cs           |   33 +
 .../Apache.Ignite.Core/Common/IAsyncSupport.cs  |   52 +
 .../dotnet/Apache.Ignite.Core/Common/IFuture.cs |  115 +
 .../Common/IgniteException.cs                   |   66 +
 .../main/dotnet/Apache.Ignite.Core/Ignition.cs  |   23 +
 .../Impl/Collections/CollectionExtensions.cs    |   45 +
 .../Impl/Collections/MultiValueDictionary.cs    |  143 +
 .../Impl/Collections/ReadOnlyCollection.cs      |  102 +
 .../Impl/Collections/ReadOnlyDictionary.cs      |  149 +
 .../Impl/Common/AsyncResult.cs                  |   71 +
 .../Impl/Common/CompletedAsyncResult.cs         |   70 +
 .../Common/CopyOnWriteConcurrentDictionary.cs   |   70 +
 .../Impl/Common/DelegateConverter.cs            |  253 ++
 .../Apache.Ignite.Core/Impl/Common/Future.cs    |  286 ++
 .../Impl/Common/FutureType.cs                   |   52 +
 .../Impl/Common/GridArgumentCheck.cs            |   76 +
 .../Impl/Common/IFutureConverter.cs             |   32 +
 .../Impl/Common/IFutureInternal.cs              |   45 +
 .../Impl/Common/LoadedAssembliesResolver.cs     |   96 +
 .../Impl/Common/TypeCaster.cs                   |   72 +
 .../Apache.Ignite.Core/Impl/Handle/Handle.cs    |   69 +
 .../Impl/Handle/HandleRegistry.cs               |  340 ++
 .../Apache.Ignite.Core/Impl/Handle/IHandle.cs   |   35 +
 .../Impl/Memory/IPlatformMemory.cs              |   62 +
 .../Memory/PlatformBigEndianMemoryStream.cs     |  483 +++
 .../Impl/Memory/PlatformMemory.cs               |   77 +
 .../Impl/Memory/PlatformMemoryManager.cs        |  106 +
 .../Impl/Memory/PlatformMemoryPool.cs           |  105 +
 .../Impl/Memory/PlatformMemoryStream.cs         |  676 ++++
 .../Impl/Memory/PlatformMemoryUtils.cs          |  462 +++
 .../Impl/Memory/PlatformPooledMemory.cs         |   70 +
 .../Impl/Memory/PlatformRawMemory.cs            |   88 +
 .../Impl/Memory/PlatformUnpooledMemory.cs       |   52 +
 .../Impl/Portable/Io/IPortableStream.cs         |  320 ++
 .../Properties/AssemblyInfo.cs                  |   45 +
 .../platform/src/main/dotnet/Apache.Ignite.sln  |   35 +
 .../main/dotnet/Apache.Ignite.sln.DotSettings   |    4 +
 .../platform/PlatformAbstractBootstrap.java     |   48 +
 .../platform/PlatformAbstractTarget.java        |  276 ++
 .../processors/platform/PlatformBootstrap.java  |   36 +
 .../platform/PlatformBootstrapFactory.java      |   37 +
 .../processors/platform/PlatformContext.java    |  114 +
 .../processors/platform/PlatformException.java  |   71 +
 .../platform/PlatformExtendedException.java     |   39 +
 .../processors/platform/PlatformIgnition.java   |  186 +
 .../platform/PlatformNoCallbackException.java   |   50 +
 .../processors/platform/PlatformTarget.java     |   76 +
 .../cache/affinity/PlatformAffinity.java        |  293 ++
 .../query/PlatformAbstractQueryCursor.java      |  192 +
 .../cache/query/PlatformFieldsQueryCursor.java  |   50 +
 .../cache/query/PlatformQueryCursor.java        |   46 +
 .../cache/store/PlatformCacheStore.java         |   25 +
 .../cache/store/PlatformCacheStoreCallback.java |   61 +
 .../callback/PlatformCallbackGateway.java       |  869 +++++
 .../callback/PlatformCallbackUtils.java         |  468 +++
 .../lifecycle/PlatformLifecycleBean.java        |   72 +
 .../platform/memory/PlatformAbstractMemory.java |  121 +
 .../PlatformBigEndianInputStreamImpl.java       |  126 +
 .../PlatformBigEndianOutputStreamImpl.java      |  162 +
 .../platform/memory/PlatformExternalMemory.java |   55 +
 .../platform/memory/PlatformInputStream.java    |   30 +
 .../memory/PlatformInputStreamImpl.java         |  323 ++
 .../platform/memory/PlatformMemory.java         |   77 +
 .../platform/memory/PlatformMemoryManager.java  |   46 +
 .../memory/PlatformMemoryManagerImpl.java       |   83 +
 .../platform/memory/PlatformMemoryPool.java     |  133 +
 .../platform/memory/PlatformMemoryUtils.java    |  468 +++
 .../platform/memory/PlatformOutputStream.java   |   30 +
 .../memory/PlatformOutputStreamImpl.java        |  259 ++
 .../platform/memory/PlatformPooledMemory.java   |   63 +
 .../platform/memory/PlatformUnpooledMemory.java |   51 +
 .../transactions/PlatformTransactions.java      |  255 ++
 .../platform/utils/PlatformFutureUtils.java     |  326 ++
 .../platform/utils/PlatformReaderBiClosure.java |   34 +
 .../platform/utils/PlatformReaderClosure.java   |   34 +
 .../platform/utils/PlatformUtils.java           |  585 +++
 .../platform/utils/PlatformWriterBiClosure.java |   34 +
 .../platform/utils/PlatformWriterClosure.java   |   33 +
 .../Apache.Ignite.Core.Tests.csproj             |   65 +
 .../Apache.Ignite.Core.Tests/IgnitionTest.cs    |   30 +
 .../Memory/InteropMemoryTest.cs                 |  213 +
 .../Properties/AssemblyInfo.cs                  |   35 +
 .../Apache.Ignite.Core.Tests/TestRunner.cs      |   70 +
 .../org/apache/ignite/IgniteSpringBean.java     |    7 +
 parent/pom.xml                                  |   13 +
 pom.xml                                         |    7 +-
 scripts/apply-pull-request.sh                   |  141 +
 403 files changed, 44935 insertions(+), 1332 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/e34872d3/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheProcessor.java
----------------------------------------------------------------------
diff --cc modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheProcessor.java
index 641acf0,dd4d30b..02411b1
--- 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
@@@ -55,9 -55,9 +55,10 @@@ import org.apache.ignite.lang.*
  import org.apache.ignite.lifecycle.*;
  import org.apache.ignite.marshaller.*;
  import org.apache.ignite.marshaller.jdk.*;
+ import org.apache.ignite.marshaller.portable.*;
  import org.apache.ignite.spi.*;
  import org.jetbrains.annotations.*;
 +import org.jsr166.*;
  
  import javax.cache.configuration.*;
  import javax.cache.integration.*;


[09/59] [abbrv] ignite git commit: ignite-1258: portable objects API support in Ignite

Posted by vk...@apache.org.
http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableUtils.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableUtils.java b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableUtils.java
new file mode 100644
index 0000000..72e80ec
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableUtils.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.portable;
+
+import org.apache.ignite.internal.util.typedef.internal.*;
+import org.apache.ignite.portable.*;
+
+import org.jetbrains.annotations.*;
+import org.jsr166.*;
+
+import java.math.*;
+import java.sql.*;
+import java.util.*;
+import java.util.Date;
+import java.util.concurrent.*;
+
+import static org.apache.ignite.internal.portable.GridPortableMarshaller.*;
+
+/**
+ *
+ */
+public class PortableUtils {
+    /** */
+    public static final Map<Class<?>, Byte> PLAIN_CLASS_TO_FLAG = new HashMap<>();
+
+    /** */
+    public static final Map<Byte, Class<?>> FLAG_TO_CLASS = new HashMap<>();
+
+    /** {@code true} if serialized value of this type cannot contain references to objects. */
+    private static final boolean[] PLAIN_TYPE_FLAG = new boolean[102];
+
+    /** Portable classes. */
+    private static final Collection<Class<?>> PORTABLE_CLS = new HashSet<>();
+
+    /**
+     *
+     */
+    static {
+        PORTABLE_CLS.add(Byte.class);
+        PORTABLE_CLS.add(Short.class);
+        PORTABLE_CLS.add(Integer.class);
+        PORTABLE_CLS.add(Long.class);
+        PORTABLE_CLS.add(Float.class);
+        PORTABLE_CLS.add(Double.class);
+        PORTABLE_CLS.add(Character.class);
+        PORTABLE_CLS.add(Boolean.class);
+        PORTABLE_CLS.add(String.class);
+        PORTABLE_CLS.add(UUID.class);
+        PORTABLE_CLS.add(Date.class);
+        PORTABLE_CLS.add(Timestamp.class);
+        PORTABLE_CLS.add(BigDecimal.class);
+        PORTABLE_CLS.add(byte[].class);
+        PORTABLE_CLS.add(short[].class);
+        PORTABLE_CLS.add(int[].class);
+        PORTABLE_CLS.add(long[].class);
+        PORTABLE_CLS.add(float[].class);
+        PORTABLE_CLS.add(double[].class);
+        PORTABLE_CLS.add(char[].class);
+        PORTABLE_CLS.add(boolean[].class);
+        PORTABLE_CLS.add(String[].class);
+        PORTABLE_CLS.add(UUID[].class);
+        PORTABLE_CLS.add(Date[].class);
+        PORTABLE_CLS.add(Timestamp[].class);
+        PORTABLE_CLS.add(BigDecimal[].class);
+    }
+
+    /**
+     *
+     */
+    static {
+        PLAIN_CLASS_TO_FLAG.put(Byte.class, GridPortableMarshaller.BYTE);
+        PLAIN_CLASS_TO_FLAG.put(Short.class, GridPortableMarshaller.SHORT);
+        PLAIN_CLASS_TO_FLAG.put(Integer.class, GridPortableMarshaller.INT);
+        PLAIN_CLASS_TO_FLAG.put(Long.class, GridPortableMarshaller.LONG);
+        PLAIN_CLASS_TO_FLAG.put(Float.class, GridPortableMarshaller.FLOAT);
+        PLAIN_CLASS_TO_FLAG.put(Double.class, GridPortableMarshaller.DOUBLE);
+        PLAIN_CLASS_TO_FLAG.put(Character.class, GridPortableMarshaller.CHAR);
+        PLAIN_CLASS_TO_FLAG.put(Boolean.class, GridPortableMarshaller.BOOLEAN);
+        PLAIN_CLASS_TO_FLAG.put(BigDecimal.class, GridPortableMarshaller.DECIMAL);
+        PLAIN_CLASS_TO_FLAG.put(String.class, GridPortableMarshaller.STRING);
+        PLAIN_CLASS_TO_FLAG.put(UUID.class, GridPortableMarshaller.UUID);
+        PLAIN_CLASS_TO_FLAG.put(Date.class, GridPortableMarshaller.DATE);
+
+        PLAIN_CLASS_TO_FLAG.put(byte[].class, GridPortableMarshaller.BYTE_ARR);
+        PLAIN_CLASS_TO_FLAG.put(short[].class, GridPortableMarshaller.SHORT_ARR);
+        PLAIN_CLASS_TO_FLAG.put(int[].class, GridPortableMarshaller.INT_ARR);
+        PLAIN_CLASS_TO_FLAG.put(long[].class, GridPortableMarshaller.LONG_ARR);
+        PLAIN_CLASS_TO_FLAG.put(float[].class, GridPortableMarshaller.FLOAT_ARR);
+        PLAIN_CLASS_TO_FLAG.put(double[].class, GridPortableMarshaller.DOUBLE_ARR);
+        PLAIN_CLASS_TO_FLAG.put(char[].class, GridPortableMarshaller.CHAR_ARR);
+        PLAIN_CLASS_TO_FLAG.put(boolean[].class, GridPortableMarshaller.BOOLEAN_ARR);
+        PLAIN_CLASS_TO_FLAG.put(BigDecimal[].class, GridPortableMarshaller.DECIMAL_ARR);
+        PLAIN_CLASS_TO_FLAG.put(String[].class, GridPortableMarshaller.STRING_ARR);
+        PLAIN_CLASS_TO_FLAG.put(UUID[].class, GridPortableMarshaller.UUID_ARR);
+        PLAIN_CLASS_TO_FLAG.put(Date[].class, GridPortableMarshaller.DATE_ARR);
+
+        for (Map.Entry<Class<?>, Byte> entry : PLAIN_CLASS_TO_FLAG.entrySet())
+            FLAG_TO_CLASS.put(entry.getValue(), entry.getKey());
+
+        PLAIN_CLASS_TO_FLAG.put(byte.class, GridPortableMarshaller.BYTE);
+        PLAIN_CLASS_TO_FLAG.put(short.class, GridPortableMarshaller.SHORT);
+        PLAIN_CLASS_TO_FLAG.put(int.class, GridPortableMarshaller.INT);
+        PLAIN_CLASS_TO_FLAG.put(long.class, GridPortableMarshaller.LONG);
+        PLAIN_CLASS_TO_FLAG.put(float.class, GridPortableMarshaller.FLOAT);
+        PLAIN_CLASS_TO_FLAG.put(double.class, GridPortableMarshaller.DOUBLE);
+        PLAIN_CLASS_TO_FLAG.put(char.class, GridPortableMarshaller.CHAR);
+        PLAIN_CLASS_TO_FLAG.put(boolean.class, GridPortableMarshaller.BOOLEAN);
+
+        for (byte b : new byte[] {
+            BYTE, SHORT, INT, LONG, FLOAT, DOUBLE,
+            CHAR, BOOLEAN, DECIMAL, STRING, UUID, DATE,
+            BYTE_ARR, SHORT_ARR, INT_ARR, LONG_ARR, FLOAT_ARR, DOUBLE_ARR,
+            CHAR_ARR, BOOLEAN_ARR, DECIMAL_ARR, STRING_ARR, UUID_ARR, DATE_ARR,
+            ENUM, ENUM_ARR, NULL}) {
+
+            PLAIN_TYPE_FLAG[b] = true;
+        }
+    }
+
+    /**
+     * Write value with flag. e.g. writePlainObject(writer, (byte)77) will write two byte: {BYTE, 77}.
+     *
+     * @param writer W
+     * @param val Value.
+     */
+    public static void writePlainObject(PortableWriterExImpl writer, Object val) {
+        Byte flag = PLAIN_CLASS_TO_FLAG.get(val.getClass());
+
+        if (flag == null)
+            throw new IllegalArgumentException("Can't write object with type: " + val.getClass());
+
+        switch (flag) {
+            case BYTE:
+                writer.writeByte(flag);
+                writer.writeByte((Byte)val);
+
+                break;
+
+            case SHORT:
+                writer.writeByte(flag);
+                writer.writeShort((Short)val);
+
+                break;
+
+            case INT:
+                writer.writeByte(flag);
+                writer.writeInt((Integer)val);
+
+                break;
+
+            case LONG:
+                writer.writeByte(flag);
+                writer.writeLong((Long)val);
+
+                break;
+
+            case FLOAT:
+                writer.writeByte(flag);
+                writer.writeFloat((Float)val);
+
+                break;
+
+            case DOUBLE:
+                writer.writeByte(flag);
+                writer.writeDouble((Double)val);
+
+                break;
+
+            case CHAR:
+                writer.writeByte(flag);
+                writer.writeChar((Character)val);
+
+                break;
+
+            case BOOLEAN:
+                writer.writeByte(flag);
+                writer.writeBoolean((Boolean)val);
+
+                break;
+
+            case DECIMAL:
+                writer.doWriteDecimal((BigDecimal)val);
+
+                break;
+
+            case STRING:
+                writer.doWriteString((String)val);
+
+                break;
+
+            case UUID:
+                writer.doWriteUuid((UUID)val);
+
+                break;
+
+            case DATE:
+                if (val instanceof Timestamp)
+                    writer.doWriteTimestamp((Timestamp)val);
+                else
+                    writer.doWriteDate((Date)val);
+
+                break;
+
+            case BYTE_ARR:
+                writer.doWriteByteArray((byte[])val);
+
+                break;
+
+            case SHORT_ARR:
+                writer.doWriteShortArray((short[])val);
+
+                break;
+
+            case INT_ARR:
+                writer.doWriteIntArray((int[])val);
+
+                break;
+
+            case LONG_ARR:
+                writer.doWriteLongArray((long[])val);
+
+                break;
+
+            case FLOAT_ARR:
+                writer.doWriteFloatArray((float[])val);
+
+                break;
+
+            case DOUBLE_ARR:
+                writer.doWriteDoubleArray((double[])val);
+
+                break;
+
+            case CHAR_ARR:
+                writer.doWriteCharArray((char[])val);
+
+                break;
+
+            case BOOLEAN_ARR:
+                writer.doWriteBooleanArray((boolean[])val);
+
+                break;
+
+            case DECIMAL_ARR:
+                writer.doWriteDecimalArray((BigDecimal[])val);
+
+                break;
+
+            case STRING_ARR:
+                writer.doWriteStringArray((String[])val);
+
+                break;
+
+            case UUID_ARR:
+                writer.doWriteUuidArray((UUID[])val);
+
+                break;
+
+            case DATE_ARR:
+                writer.doWriteDateArray((Date[])val);
+
+                break;
+
+            default:
+                throw new IllegalArgumentException("Can't write object with type: " + val.getClass());
+        }
+    }
+
+    /**
+     * @param obj Value to unwrap.
+     * @return Unwrapped value.
+     */
+    public static Object unwrapLazy(@Nullable Object obj) {
+        if (obj instanceof PortableLazyValue)
+            return ((PortableLazyValue)obj).value();
+
+        return obj;
+    }
+
+    /**
+     * @param delegate Iterator to delegate.
+     * @return New iterator.
+     */
+    public static Iterator<Object> unwrapLazyIterator(final Iterator<Object> delegate) {
+        return new Iterator<Object>() {
+            @Override public boolean hasNext() {
+                return delegate.hasNext();
+            }
+
+            @Override public Object next() {
+                return unwrapLazy(delegate.next());
+            }
+
+            @Override public void remove() {
+                delegate.remove();
+            }
+        };
+    }
+
+    /**
+     * @return {@code true} if content of serialized value cannot contain references to other object.
+     */
+    public static boolean isPlainType(int type) {
+        return type > 0 && type < PLAIN_TYPE_FLAG.length && PLAIN_TYPE_FLAG[type];
+    }
+
+    /**
+     * @param cls Class.
+     * @return Portable field type.
+     */
+    public static byte typeByClass(Class<?> cls) {
+        if (Date.class.isAssignableFrom(cls))
+            return DATE;
+
+        Byte type = PLAIN_CLASS_TO_FLAG.get(cls);
+
+        if (type != null)
+            return type;
+
+        if (cls.isEnum())
+            return ENUM;
+
+        if (cls.isArray())
+            return cls.getComponentType().isEnum() || cls.getComponentType() == Enum.class ? ENUM_ARR : OBJ_ARR;
+
+        if (Collection.class.isAssignableFrom(cls))
+            return COL;
+
+        if (Map.class.isAssignableFrom(cls))
+            return MAP;
+
+        if (Map.Entry.class.isAssignableFrom(cls))
+            return MAP;
+
+        return OBJ;
+    }
+
+    /**
+     * Tells whether provided type is portable or a collection.
+     *
+     * @param cls Class to check.
+     * @return Whether type is portable or a collection.
+     */
+    public static boolean isPortableOrCollectionType(Class<?> cls) {
+        assert cls != null;
+
+        return isPortableType(cls) ||
+            cls == Object[].class ||
+            Collection.class.isAssignableFrom(cls) ||
+            Map.class.isAssignableFrom(cls) ||
+            Map.Entry.class.isAssignableFrom(cls);
+    }
+
+    /**
+     * Tells whether provided type is portable.
+     *
+     * @param cls Class to check.
+     * @return Whether type is portable.
+     */
+    public static boolean isPortableType(Class<?> cls) {
+        assert cls != null;
+
+        return PortableObject.class.isAssignableFrom(cls) ||
+            PORTABLE_CLS.contains(cls) ||
+            cls.isEnum() ||
+            (cls.isArray() && cls.getComponentType().isEnum());
+    }
+
+    /**
+     * Attempts to create a new map of the same type as {@code map} has. Otherwise returns new {@code HashMap} instance.
+     *
+     * @param map Original map.
+     * @return New map.
+     */
+    public static <K, V> Map<K, V> newMap(Map<K, V> map) {
+        if (map instanceof LinkedHashMap)
+            return U.newLinkedHashMap(map.size());
+        else if (map instanceof TreeMap)
+            return new TreeMap<>(((TreeMap<Object, Object>)map).comparator());
+        else if (map instanceof ConcurrentHashMap8)
+            return new ConcurrentHashMap8<>(U.capacity(map.size()));
+        else if (map instanceof ConcurrentHashMap)
+            return new ConcurrentHashMap<>(U.capacity(map.size()));
+
+        return U.newHashMap(map.size());
+    }
+
+    /**
+     * Attempts to create a new set of the same type as {@code set} has. Otherwise returns new {@code HashSet} instance.
+     *
+     * @param set Original set.
+     * @return New set.
+     */
+    public static <V> Set<V> newSet(Set<V> set) {
+        if (set instanceof LinkedHashSet)
+            return U.newLinkedHashSet(set.size());
+        else if (set instanceof TreeSet)
+            return new TreeSet<>(((TreeSet<Object>)set).comparator());
+        else if (set instanceof ConcurrentSkipListSet)
+            return new ConcurrentSkipListSet<>(((ConcurrentSkipListSet<Object>)set).comparator());
+
+        return U.newHashSet(set.size());
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableValueWithType.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableValueWithType.java b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableValueWithType.java
new file mode 100644
index 0000000..52f1dcc
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableValueWithType.java
@@ -0,0 +1,74 @@
+/*
+ * 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.portable;
+
+import org.apache.ignite.internal.processors.cache.portable.*;
+import org.apache.ignite.internal.util.typedef.internal.*;
+
+/**
+ *
+ */
+class PortableValueWithType implements PortableLazyValue {
+    /** */
+    private byte type;
+
+    /** */
+    private Object val;
+
+    /**
+     * @param type Type
+     * @param val Value.
+     */
+    PortableValueWithType(byte type, Object val) {
+        this.type = type;
+        this.val = val;
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeTo(PortableWriterExImpl writer, PortableBuilderSerializer ctx) {
+        if (val instanceof PortableBuilderSerializationAware)
+            ((PortableBuilderSerializationAware)val).writeTo(writer, ctx);
+        else
+            ctx.writeValue(writer, val);
+    }
+
+    /** {@inheritDoc} */
+    public String typeName() {
+        return CacheObjectPortableProcessorImpl.fieldTypeName(type);
+    }
+
+    /** {@inheritDoc} */
+    @Override public Object value() {
+        if (val instanceof PortableLazyValue)
+            return ((PortableLazyValue)val).value();
+
+        return val;
+    }
+
+    /**
+     * @param val New value.
+     */
+    public void value(Object val) {
+        this.val = val;
+    }
+
+    /** {@inheritDoc} */
+    @Override public String toString() {
+        return S.toString(PortableValueWithType.class, this);
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableWriterExImpl.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableWriterExImpl.java b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableWriterExImpl.java
new file mode 100644
index 0000000..f801632
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableWriterExImpl.java
@@ -0,0 +1,1769 @@
+/*
+ * 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.portable;
+
+import org.apache.ignite.*;
+import org.apache.ignite.internal.portable.streams.*;
+import org.apache.ignite.internal.util.typedef.internal.*;
+import org.apache.ignite.portable.*;
+
+import org.jetbrains.annotations.*;
+
+import java.io.*;
+import java.lang.reflect.*;
+import java.math.*;
+import java.sql.*;
+import java.util.*;
+import java.util.Date;
+import java.util.concurrent.*;
+
+import static java.nio.charset.StandardCharsets.*;
+import static org.apache.ignite.internal.portable.GridPortableMarshaller.*;
+
+ /**
+ * Portable writer implementation.
+ */
+public class PortableWriterExImpl implements PortableWriter, PortableRawWriterEx, ObjectOutput {
+    /** Length: integer. */
+    private static final int LEN_INT = 4;
+
+    /** */
+    private static final int INIT_CAP = 1024;
+
+    /** */
+    private static final ConcurrentHashMap<Class<?>, Boolean> useOptMarshCache = new ConcurrentHashMap<>();
+
+    /** */
+    private final PortableContext ctx;
+
+    /** */
+    private final WriterContext wCtx;
+
+    /** */
+    private final int start;
+
+    /** */
+    private int mark;
+
+    /** */
+    private Class<?> cls;
+
+    /** */
+    private int typeId;
+
+    /** */
+    private boolean allowFields = true;
+
+    /** */
+    private boolean metaEnabled;
+
+    /** */
+    private int metaHashSum;
+
+    /**
+     * @param ctx Context.
+     * @param off Start offset.
+     */
+    PortableWriterExImpl(PortableContext ctx, int off) {
+        this.ctx = ctx;
+
+        PortableOutputStream out = new PortableHeapOutputStream(off + INIT_CAP);
+
+        out.position(off);
+
+        wCtx = new WriterContext(out, null);
+
+        start = off;
+    }
+
+    /**
+     * @param ctx Context.
+     * @param out Output stream.
+     * @param off Start offset.
+     */
+    PortableWriterExImpl(PortableContext ctx, PortableOutputStream out, int off) {
+        this.ctx = ctx;
+
+        wCtx = new WriterContext(out, null);
+
+        start = off;
+    }
+
+    /**
+     * @param ctx Context.
+     * @param off Start offset.
+     * @param typeId Type ID.
+     */
+    PortableWriterExImpl(PortableContext ctx, int off, int typeId, boolean metaEnabled) {
+        this(ctx, off);
+
+        this.typeId = typeId;
+
+        this.metaEnabled = metaEnabled;
+    }
+
+    /**
+     * @param ctx Context.
+     * @param wCtx Writer context.
+     */
+    private PortableWriterExImpl(PortableContext ctx, WriterContext wCtx) {
+        this.ctx = ctx;
+        this.wCtx = wCtx;
+
+        start = wCtx.out.position();
+    }
+
+    /**
+     * Close the writer releasing resources if necessary.
+     */
+    @Override public void close() {
+        wCtx.out.close();
+    }
+
+    /**
+     * @return Meta data hash sum or {@code null} if meta data is disabled.
+     */
+    @Nullable Integer metaDataHashSum() {
+        return metaEnabled ? metaHashSum : null;
+    }
+
+    /**
+     * @param obj Object.
+     * @param detached Detached or not.
+     * @throws PortableException In case of error.
+     */
+    void marshal(Object obj, boolean detached) throws PortableException {
+        assert obj != null;
+
+        if (useOptimizedMarshaller(obj)) {
+            writeByte(OPTM_MARSH);
+
+            try {
+                byte[] arr = ctx.optimizedMarsh().marshal(obj);
+
+                writeInt(arr.length);
+
+                write(arr);
+            }
+            catch (IgniteCheckedException e) {
+                throw new PortableException("Failed to marshal object with optimized marshaller: " + obj, e);
+            }
+
+            return;
+        }
+
+        cls = obj.getClass();
+
+        PortableClassDescriptor desc = ctx.descriptorForClass(cls);
+
+        if (desc == null)
+            throw new PortableException("Object is not portable: [class=" + cls + ']');
+
+        if (desc.excluded()) {
+            doWriteByte(NULL);
+            return;
+        }
+
+        if (desc.getWriteReplaceMethod() != null) {
+            Object replace;
+
+            try {
+                replace = desc.getWriteReplaceMethod().invoke(obj);
+            }
+            catch (IllegalAccessException e) {
+                throw new RuntimeException(e);
+            }
+            catch (InvocationTargetException e) {
+                if (e.getTargetException() instanceof PortableException)
+                    throw (PortableException)e.getTargetException();
+
+                throw new PortableException("Failed to execute writeReplace() method on " + obj, e);
+            }
+
+            if (replace == null) {
+                doWriteByte(NULL);
+                return;
+            }
+
+            if (cls != replace.getClass()) {
+                cls = replace.getClass();
+
+                desc = ctx.descriptorForClass(cls);
+
+                if (desc == null)
+                    throw new PortableException("Object is not portable: [class=" + cls + ']');
+            }
+
+            obj = replace;
+        }
+
+        typeId = desc.typeId();
+
+        metaEnabled = ctx.isMetaDataEnabled(typeId);
+
+        if (detached)
+            wCtx.resetHandles();
+
+        desc.write(obj, this);
+    }
+
+     /**
+      * Determines whether to use {@link org.apache.ignite.marshaller.optimized.OptimizedMarshaller} for serialization
+      * or not.
+      *
+      * @param obj Object to serialize.
+      * @return {@code true} if to use, {@code false} otherwise.
+      */
+     private boolean useOptimizedMarshaller(Object obj) {
+         Class<?> cls = obj.getClass();
+
+         Boolean use = useOptMarshCache.get(cls);
+
+         if (use != null)
+             return use;
+
+         if (ctx.isPredefinedClass(cls))
+             use = false;
+         else {
+             try {
+                 Method writeObj = cls.getDeclaredMethod("writeObject", ObjectOutputStream.class);
+                 Method readObj = cls.getDeclaredMethod("readObject", ObjectInputStream.class);
+
+                 if (!Modifier.isStatic(writeObj.getModifiers()) && !Modifier.isStatic(readObj.getModifiers()) &&
+                     writeObj.getReturnType() == void.class && readObj.getReturnType() == void.class)
+                     use = true;
+                 else
+                     use = false;
+
+             } catch (NoSuchMethodException e) {
+                 use = false;
+             }
+         }
+
+         useOptMarshCache.putIfAbsent(cls, use);
+
+         return use;
+     }
+
+    /**
+     * @param obj Object.
+     * @return Handle.
+     */
+    int handle(Object obj) {
+        assert obj != null;
+
+        return wCtx.handle(obj);
+    }
+
+    /**
+     * @return Array.
+     */
+    byte[] array() {
+        return wCtx.out.arrayCopy();
+    }
+
+    /**
+     * @return Output stream.
+     */
+    PortableOutputStream outputStream() {
+        return wCtx.out;
+    }
+
+    /**
+     * @return Stream current position.
+     */
+    int position() {
+        return wCtx.out.position();
+    }
+
+    /**
+     * Sets new position.
+     *
+     * @param pos Position.
+     */
+    void position(int pos) {
+        wCtx.out.position(pos);
+    }
+
+     /**
+     * @param bytes Number of bytes to reserve.
+     * @return Offset.
+     */
+    int reserve(int bytes) {
+        int pos = wCtx.out.position();
+
+        wCtx.out.position(pos + bytes);
+
+        return pos;
+    }
+
+    /**
+     * @param bytes Number of bytes to reserve.
+     * @return Offset.
+     */
+    int reserveAndMark(int bytes) {
+        int off0 = reserve(bytes);
+
+        mark = wCtx.out.position();
+
+        return off0;
+    }
+
+    /**
+     * @param off Offset.
+     */
+    void writeDelta(int off) {
+        wCtx.out.writeInt(off, wCtx.out.position() - mark);
+    }
+
+    /**
+     *
+     */
+    void writeLength() {
+        wCtx.out.writeInt(start + TOTAL_LEN_POS, wCtx.out.position() - start);
+    }
+
+    /**
+     *
+     */
+    void writeRawOffsetIfNeeded() {
+        if (allowFields)
+            wCtx.out.writeInt(start + RAW_DATA_OFF_POS, wCtx.out.position() - start);
+    }
+
+    /**
+     * @param val Byte array.
+     */
+    public void write(byte[] val) {
+        assert val != null;
+
+        wCtx.out.writeByteArray(val);
+    }
+
+    /**
+     * @param val Byte array.
+     * @param off Offset.
+     * @param len Length.
+     */
+    public void write(byte[] val, int off, int len) {
+        assert val != null;
+
+        wCtx.out.write(val, off, len);
+    }
+
+    /**
+     * @param val Value.
+     */
+    void doWriteByte(byte val) {
+        wCtx.out.writeByte(val);
+    }
+
+    /**
+     * @param val Value.
+     */
+    void doWriteShort(short val) {
+        wCtx.out.writeShort(val);
+    }
+
+    /**
+     * @param val Value.
+     */
+    void doWriteInt(int val) {
+        wCtx.out.writeInt(val);
+    }
+
+    /**
+     * @param val Value.
+     */
+    void doWriteLong(long val) {
+        wCtx.out.writeLong(val);
+    }
+
+    /**
+     * @param val Value.
+     */
+    void doWriteFloat(float val) {
+        wCtx.out.writeFloat(val);
+    }
+
+    /**
+     * @param val Value.
+     */
+    void doWriteDouble(double val) {
+        wCtx.out.writeDouble(val);
+    }
+
+    /**
+     * @param val Value.
+     */
+    void doWriteChar(char val) {
+        wCtx.out.writeChar(val);
+    }
+
+    /**
+     * @param val Value.
+     */
+    void doWriteBoolean(boolean val) {
+        wCtx.out.writeBoolean(val);
+    }
+
+    /**
+     * @param val String value.
+     */
+    void doWriteDecimal(@Nullable BigDecimal val) {
+        if (val == null)
+            doWriteByte(NULL);
+        else {
+            doWriteByte(DECIMAL);
+
+            BigInteger intVal = val.unscaledValue();
+
+            if (intVal.signum() == -1) {
+                intVal = intVal.negate();
+
+                wCtx.out.writeInt(val.scale() | 0x80000000);
+            }
+            else
+                wCtx.out.writeInt(val.scale());
+
+            byte[] vals = intVal.toByteArray();
+
+            wCtx.out.writeInt(vals.length);
+            wCtx.out.writeByteArray(vals);
+        }
+    }
+
+    /**
+     * @param val String value.
+     */
+    void doWriteString(@Nullable String val) {
+        if (val == null)
+            doWriteByte(NULL);
+        else {
+            doWriteByte(STRING);
+
+            if (ctx.isConvertString()) {
+                doWriteBoolean(true);
+
+                byte[] strArr = val.getBytes(UTF_8);
+
+                doWriteInt(strArr.length);
+
+                wCtx.out.writeByteArray(strArr);
+            }
+            else {
+                doWriteBoolean(false);
+
+                char[] strArr = val.toCharArray();
+
+                doWriteInt(strArr.length);
+
+                wCtx.out.writeCharArray(strArr);
+            }
+        }
+    }
+
+    /**
+     * @param uuid UUID.
+     */
+    void doWriteUuid(@Nullable UUID uuid) {
+        if (uuid == null)
+            doWriteByte(NULL);
+        else {
+            doWriteByte(UUID);
+            doWriteLong(uuid.getMostSignificantBits());
+            doWriteLong(uuid.getLeastSignificantBits());
+        }
+    }
+
+    /**
+     * @param date Date.
+     */
+    void doWriteDate(@Nullable Date date) {
+        if (date == null)
+            doWriteByte(NULL);
+        else {
+            doWriteByte(DATE);
+            doWriteLong(date.getTime());
+            doWriteInt(0);
+        }
+    }
+
+    /**
+     * @param ts Timestamp.
+     */
+    void doWriteTimestamp(@Nullable Timestamp ts) {
+        if (ts == null)
+            doWriteByte(NULL);
+        else {
+            doWriteByte(DATE);
+            doWriteLong(ts.getTime());
+            doWriteInt(ts.getNanos() % 1000000);
+        }
+    }
+
+    /**
+     * @param obj Object.
+     * @param detached Detached or not.
+     * @throws PortableException In case of error.
+     */
+    void doWriteObject(@Nullable Object obj, boolean detached) throws PortableException {
+        if (obj == null)
+            doWriteByte(NULL);
+        else {
+            WriterContext wCtx = detached ? new WriterContext(this.wCtx.out, this.wCtx.handles) : this.wCtx;
+
+            PortableWriterExImpl writer = new PortableWriterExImpl(ctx, wCtx);
+
+            writer.marshal(obj, detached);
+
+            if (detached)
+                this.wCtx.out = wCtx.out;
+        }
+    }
+
+    /**
+     * @param val Byte array.
+     */
+    void doWriteByteArray(@Nullable byte[] val) {
+        if (val == null)
+            doWriteByte(NULL);
+        else {
+            doWriteByte(BYTE_ARR);
+            doWriteInt(val.length);
+
+            wCtx.out.writeByteArray(val);
+        }
+    }
+
+    /**
+     * @param val Short array.
+     */
+    void doWriteShortArray(@Nullable short[] val) {
+        if (val == null)
+            doWriteByte(NULL);
+        else {
+            doWriteByte(SHORT_ARR);
+            doWriteInt(val.length);
+
+            wCtx.out.writeShortArray(val);
+        }
+    }
+
+    /**
+     * @param val Integer array.
+     */
+    void doWriteIntArray(@Nullable int[] val) {
+        if (val == null)
+            doWriteByte(NULL);
+        else {
+            doWriteByte(INT_ARR);
+            doWriteInt(val.length);
+
+            wCtx.out.writeIntArray(val);
+        }
+    }
+
+    /**
+     * @param val Long array.
+     */
+    void doWriteLongArray(@Nullable long[] val) {
+        if (val == null)
+            doWriteByte(NULL);
+        else {
+            doWriteByte(LONG_ARR);
+            doWriteInt(val.length);
+
+            wCtx.out.writeLongArray(val);
+        }
+    }
+
+    /**
+     * @param val Float array.
+     */
+    void doWriteFloatArray(@Nullable float[] val) {
+        if (val == null)
+            doWriteByte(NULL);
+        else {
+            doWriteByte(FLOAT_ARR);
+            doWriteInt(val.length);
+
+            wCtx.out.writeFloatArray(val);
+        }
+    }
+
+    /**
+     * @param val Double array.
+     */
+    void doWriteDoubleArray(@Nullable double[] val) {
+        if (val == null)
+            doWriteByte(NULL);
+        else {
+            doWriteByte(DOUBLE_ARR);
+            doWriteInt(val.length);
+
+            wCtx.out.writeDoubleArray(val);
+        }
+    }
+
+    /**
+     * @param val Char array.
+     */
+    void doWriteCharArray(@Nullable char[] val) {
+        if (val == null)
+            doWriteByte(NULL);
+        else {
+            doWriteByte(CHAR_ARR);
+            doWriteInt(val.length);
+
+            wCtx.out.writeCharArray(val);
+        }
+    }
+
+    /**
+     * @param val Boolean array.
+     */
+    void doWriteBooleanArray(@Nullable boolean[] val) {
+        if (val == null)
+            doWriteByte(NULL);
+        else {
+            doWriteByte(BOOLEAN_ARR);
+            doWriteInt(val.length);
+
+            wCtx.out.writeBooleanArray(val);
+        }
+    }
+
+    /**
+     * @param val Array of strings.
+     */
+    void doWriteDecimalArray(@Nullable BigDecimal[] val) {
+        if (val == null)
+            doWriteByte(NULL);
+        else {
+            doWriteByte(DECIMAL_ARR);
+            doWriteInt(val.length);
+
+            for (BigDecimal str : val)
+                doWriteDecimal(str);
+        }
+    }
+
+    /**
+     * @param val Array of strings.
+     */
+    void doWriteStringArray(@Nullable String[] val) {
+        if (val == null)
+            doWriteByte(NULL);
+        else {
+            doWriteByte(STRING_ARR);
+            doWriteInt(val.length);
+
+            for (String str : val)
+                doWriteString(str);
+        }
+    }
+
+    /**
+     * @param val Array of UUIDs.
+     */
+    void doWriteUuidArray(@Nullable UUID[] val) {
+        if (val == null)
+            doWriteByte(NULL);
+        else {
+            doWriteByte(UUID_ARR);
+            doWriteInt(val.length);
+
+            for (UUID uuid : val)
+                doWriteUuid(uuid);
+        }
+    }
+
+    /**
+     * @param val Array of dates.
+     */
+    void doWriteDateArray(@Nullable Date[] val) {
+        if (val == null)
+            doWriteByte(NULL);
+        else {
+            doWriteByte(DATE_ARR);
+            doWriteInt(val.length);
+
+            for (Date date : val)
+                doWriteDate(date);
+        }
+    }
+
+    /**
+     * @param val Array of objects.
+     * @throws PortableException In case of error.
+     */
+    void doWriteObjectArray(@Nullable Object[] val) throws PortableException {
+        if (val == null)
+            doWriteByte(NULL);
+        else {
+            PortableContext.Type type = ctx.typeId(val.getClass().getComponentType());
+
+            doWriteByte(OBJ_ARR);
+
+            if (type.registered())
+                doWriteInt(type.id());
+            else {
+                doWriteInt(UNREGISTERED_TYPE_ID);
+                doWriteString(val.getClass().getComponentType().getName());
+            }
+
+            doWriteInt(val.length);
+
+            for (Object obj : val)
+                doWriteObject(obj, false);
+        }
+    }
+
+    /**
+     * @param col Collection.
+     * @throws PortableException In case of error.
+     */
+    void doWriteCollection(@Nullable Collection<?> col) throws PortableException {
+        if (col == null)
+            doWriteByte(NULL);
+        else {
+            doWriteByte(COL);
+            doWriteInt(col.size());
+            doWriteByte(ctx.collectionType(col.getClass()));
+
+            for (Object obj : col)
+                doWriteObject(obj, false);
+        }
+    }
+
+    /**
+     * @param map Map.
+     * @throws PortableException In case of error.
+     */
+    void doWriteMap(@Nullable Map<?, ?> map) throws PortableException {
+        if (map == null)
+            doWriteByte(NULL);
+        else {
+            doWriteByte(MAP);
+            doWriteInt(map.size());
+            doWriteByte(ctx.mapType(map.getClass()));
+
+            for (Map.Entry<?, ?> e : map.entrySet()) {
+                doWriteObject(e.getKey(), false);
+                doWriteObject(e.getValue(), false);
+            }
+        }
+    }
+
+    /**
+     * @param e Map entry.
+     * @throws PortableException In case of error.
+     */
+    void doWriteMapEntry(@Nullable Map.Entry<?, ?> e) throws PortableException {
+        if (e == null)
+            doWriteByte(NULL);
+        else {
+            doWriteByte(MAP_ENTRY);
+            doWriteObject(e.getKey(), false);
+            doWriteObject(e.getValue(), false);
+        }
+    }
+
+    /**
+     * @param val Value.
+     */
+    void doWriteEnum(@Nullable Enum<?> val) {
+        if (val == null)
+            doWriteByte(NULL);
+        else {
+            PortableContext.Type type = ctx.typeId(val.getClass());
+
+            doWriteByte(ENUM);
+
+            if (type.registered())
+                doWriteInt(type.id());
+            else {
+                doWriteInt(UNREGISTERED_TYPE_ID);
+                doWriteString(val.getClass().getName());
+            }
+
+            doWriteInt(val.ordinal());
+        }
+    }
+
+    /**
+     * @param val Array.
+     */
+    void doWriteEnumArray(@Nullable Object[] val) {
+        assert val == null || val.getClass().getComponentType().isEnum();
+
+        if (val == null)
+            doWriteByte(NULL);
+        else {
+            PortableContext.Type type = ctx.typeId(val.getClass().getComponentType());
+
+            doWriteByte(ENUM_ARR);
+
+            if (type.registered())
+                doWriteInt(type.id());
+            else {
+                doWriteInt(UNREGISTERED_TYPE_ID);
+                doWriteString(val.getClass().getComponentType().getName());
+            }
+
+            doWriteInt(val.length);
+
+            // TODO: Denis: Redundant data for each element of the array.
+            for (Object o : val)
+                doWriteEnum((Enum<?>)o);
+        }
+    }
+
+    /**
+     * @param val Class.
+     */
+    void doWriteClass(@Nullable Class val) {
+        if (val == null)
+            doWriteByte(NULL);
+        else {
+            PortableContext.Type type = ctx.typeId(val);
+
+            doWriteByte(CLASS);
+
+            if (type.registered())
+                doWriteInt(type.id());
+            else {
+                doWriteInt(UNREGISTERED_TYPE_ID);
+                doWriteString(val.getClass().getName());
+            }
+        }
+    }
+
+    /**
+     * @param po Portable object.
+     */
+    void doWritePortableObject(@Nullable PortableObjectImpl po) {
+        if (po == null)
+            doWriteByte(NULL);
+        else {
+            doWriteByte(PORTABLE_OBJ);
+
+            byte[] poArr = po.array();
+
+            doWriteInt(poArr.length);
+
+            wCtx.out.writeByteArray(poArr);
+
+            doWriteInt(po.start());
+        }
+    }
+
+    /**
+     * @param val Value.
+     */
+    void writeByteField(@Nullable Byte val) {
+        doWriteInt(val != null ? 2 : 1);
+
+        if (val == null)
+            doWriteByte(NULL);
+        else {
+            doWriteByte(BYTE);
+            doWriteByte(val);
+        }
+    }
+
+    /**
+     * @param val Class.
+     */
+    void writeClassField(@Nullable Class val) {
+        int lenPos = reserveAndMark(4);
+
+        doWriteClass(val);
+
+        writeDelta(lenPos);
+    }
+
+    /**
+     * @param val Value.
+     */
+    void writeShortField(@Nullable Short val) {
+        doWriteInt(val != null ? 3 : 1);
+
+        if (val == null)
+            doWriteByte(NULL);
+        else {
+            doWriteByte(SHORT);
+            doWriteShort(val);
+        }
+    }
+
+    /**
+     * @param val Value.
+     */
+    void writeIntField(@Nullable Integer val) {
+        doWriteInt(val != null ? 5 : 1);
+
+        if (val == null)
+            doWriteByte(NULL);
+        else {
+            doWriteByte(INT);
+            doWriteInt(val);
+        }
+    }
+
+    /**
+     * @param val Value.
+     */
+    void writeLongField(@Nullable Long val) {
+        doWriteInt(val != null ? 9 : 1);
+
+        if (val == null)
+            doWriteByte(NULL);
+        else {
+            doWriteByte(LONG);
+            doWriteLong(val);
+        }
+    }
+
+    /**
+     * @param val Value.
+     */
+    void writeFloatField(@Nullable Float val) {
+        doWriteInt(val != null ? 5 : 1);
+
+        if (val == null)
+            doWriteByte(NULL);
+        else {
+            doWriteByte(FLOAT);
+            doWriteFloat(val);
+        }
+    }
+
+    /**
+     * @param val Value.
+     */
+    void writeDoubleField(@Nullable Double val) {
+        doWriteInt(val != null ? 9 : 1);
+
+        if (val == null)
+            doWriteByte(NULL);
+        else {
+            doWriteByte(DOUBLE);
+            doWriteDouble(val);
+        }
+    }
+
+    /**
+     * @param val Value.
+     */
+    void writeCharField(@Nullable Character val) {
+        doWriteInt(val != null ? 3 : 1);
+
+        if (val == null)
+            doWriteByte(NULL);
+        else {
+            doWriteByte(CHAR);
+            doWriteChar(val);
+        }
+    }
+
+    /**
+     * @param val Value.
+     */
+    void writeBooleanField(@Nullable Boolean val) {
+        doWriteInt(val != null ? 2 : 1);
+
+        if (val == null)
+            doWriteByte(NULL);
+        else {
+            doWriteByte(BOOLEAN);
+            doWriteBoolean(val);
+        }
+    }
+
+    /**
+     * @param val Value.
+     */
+    void writeDecimalField(@Nullable BigDecimal val) {
+        int lenPos = reserveAndMark(4);
+
+        doWriteDecimal(val);
+
+        writeDelta(lenPos);
+    }
+
+    /**
+     * @param val Value.
+     */
+    void writeStringField(@Nullable String val) {
+        int lenPos = reserveAndMark(4);
+
+        doWriteString(val);
+
+        writeDelta(lenPos);
+    }
+
+    /**
+     * @param val Value.
+     */
+    void writeUuidField(@Nullable UUID val) {
+        doWriteInt(val != null ? 17 : 1);
+        doWriteUuid(val);
+    }
+
+    /**
+     * @param val Value.
+     */
+    void writeDateField(@Nullable Date val) {
+        doWriteInt(val != null ? 13 : 1);
+        doWriteDate(val);
+    }
+
+    /**
+     * @param val Value.
+     */
+    void writeTimestampField(@Nullable Timestamp val) {
+        doWriteInt(val != null ? 13 : 1);
+        doWriteTimestamp(val);
+    }
+
+    /**
+     * @param obj Object.
+     * @throws PortableException In case of error.
+     */
+    void writeObjectField(@Nullable Object obj) throws PortableException {
+        int lenPos = reserveAndMark(4);
+
+        doWriteObject(obj, false);
+
+        writeDelta(lenPos);
+    }
+
+    /**
+     * @param val Value.
+     */
+    void writeByteArrayField(@Nullable byte[] val) {
+        doWriteInt(val != null ? 5 + val.length : 1);
+        doWriteByteArray(val);
+    }
+
+    /**
+     * @param val Value.
+     */
+    void writeShortArrayField(@Nullable short[] val) {
+        doWriteInt(val != null ? 5 + (val.length << 1) : 1);
+        doWriteShortArray(val);
+    }
+
+    /**
+     * @param val Value.
+     */
+    void writeIntArrayField(@Nullable int[] val) {
+        doWriteInt(val != null ? 5 + (val.length << 2) : 1);
+        doWriteIntArray(val);
+    }
+
+    /**
+     * @param val Value.
+     */
+    void writeLongArrayField(@Nullable long[] val) {
+        doWriteInt(val != null ? 5 + (val.length << 3) : 1);
+        doWriteLongArray(val);
+    }
+
+    /**
+     * @param val Value.
+     */
+    void writeFloatArrayField(@Nullable float[] val) {
+        doWriteInt(val != null ? 5 + (val.length << 2) : 1);
+        doWriteFloatArray(val);
+    }
+
+    /**
+     * @param val Value.
+     */
+    void writeDoubleArrayField(@Nullable double[] val) {
+        doWriteInt(val != null ? 5 + (val.length << 3) : 1);
+        doWriteDoubleArray(val);
+    }
+
+    /**
+     * @param val Value.
+     */
+    void writeCharArrayField(@Nullable char[] val) {
+        doWriteInt(val != null ? 5 + (val.length << 1) : 1);
+        doWriteCharArray(val);
+    }
+
+    /**
+     * @param val Value.
+     */
+    void writeBooleanArrayField(@Nullable boolean[] val) {
+        doWriteInt(val != null ? 5 + val.length : 1);
+        doWriteBooleanArray(val);
+    }
+
+    /**
+     * @param val Value.
+     */
+    void writeDecimalArrayField(@Nullable BigDecimal[] val) {
+        int lenPos = reserveAndMark(4);
+
+        doWriteDecimalArray(val);
+
+        writeDelta(lenPos);
+    }
+
+    /**
+     * @param val Value.
+     */
+    void writeStringArrayField(@Nullable String[] val) {
+        int lenPos = reserveAndMark(4);
+
+        doWriteStringArray(val);
+
+        writeDelta(lenPos);
+    }
+
+    /**
+     * @param val Value.
+     */
+    void writeUuidArrayField(@Nullable UUID[] val) {
+        int lenPos = reserveAndMark(4);
+
+        doWriteUuidArray(val);
+
+        writeDelta(lenPos);
+    }
+
+    /**
+     * @param val Value.
+     */
+    void writeDateArrayField(@Nullable Date[] val) {
+        int lenPos = reserveAndMark(4);
+
+        doWriteDateArray(val);
+
+        writeDelta(lenPos);
+    }
+
+    /**
+     * @param val Value.
+     * @throws PortableException In case of error.
+     */
+    void writeObjectArrayField(@Nullable Object[] val) throws PortableException {
+        int lenPos = reserveAndMark(4);
+
+        doWriteObjectArray(val);
+
+        writeDelta(lenPos);
+    }
+
+    /**
+     * @param col Collection.
+     * @throws PortableException In case of error.
+     */
+    void writeCollectionField(@Nullable Collection<?> col) throws PortableException {
+        int lenPos = reserveAndMark(4);
+
+        doWriteCollection(col);
+
+        writeDelta(lenPos);
+    }
+
+    /**
+     * @param map Map.
+     * @throws PortableException In case of error.
+     */
+    void writeMapField(@Nullable Map<?, ?> map) throws PortableException {
+        int lenPos = reserveAndMark(4);
+
+        doWriteMap(map);
+
+        writeDelta(lenPos);
+    }
+
+    /**
+     * @param e Map entry.
+     * @throws PortableException In case of error.
+     */
+    void writeMapEntryField(@Nullable Map.Entry<?, ?> e) throws PortableException {
+        int lenPos = reserveAndMark(4);
+
+        doWriteMapEntry(e);
+
+        writeDelta(lenPos);
+    }
+
+    /**
+     * @param val Value.
+     */
+    void writeEnumField(@Nullable Enum<?> val) {
+        int lenPos = reserveAndMark(4);
+
+        doWriteEnum(val);
+
+        writeDelta(lenPos);
+    }
+
+    /**
+     * @param val Value.
+     */
+    void writeEnumArrayField(@Nullable Object[] val) {
+        int lenPos = reserveAndMark(4);
+
+        doWriteEnumArray(val);
+
+        writeDelta(lenPos);
+    }
+
+    /**
+     * @param po Portable object.
+     * @throws PortableException In case of error.
+     */
+    void writePortableObjectField(@Nullable PortableObjectImpl po) throws PortableException {
+        int lenPos = reserveAndMark(4);
+
+        doWritePortableObject(po);
+
+        writeDelta(lenPos);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeByte(String fieldName, byte val) throws PortableException {
+        writeFieldId(fieldName, BYTE);
+        writeByteField(val);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeByte(byte val) throws PortableException {
+        doWriteByte(val);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeShort(String fieldName, short val) throws PortableException {
+        writeFieldId(fieldName, SHORT);
+        writeShortField(val);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeShort(short val) throws PortableException {
+        doWriteShort(val);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeInt(String fieldName, int val) throws PortableException {
+        writeFieldId(fieldName, INT);
+        writeIntField(val);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeInt(int val) throws PortableException {
+        doWriteInt(val);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeLong(String fieldName, long val) throws PortableException {
+        writeFieldId(fieldName, LONG);
+        writeLongField(val);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeLong(long val) throws PortableException {
+        doWriteLong(val);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeFloat(String fieldName, float val) throws PortableException {
+        writeFieldId(fieldName, FLOAT);
+        writeFloatField(val);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeFloat(float val) throws PortableException {
+        doWriteFloat(val);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeDouble(String fieldName, double val) throws PortableException {
+        writeFieldId(fieldName, DOUBLE);
+        writeDoubleField(val);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeDouble(double val) throws PortableException {
+        doWriteDouble(val);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeChar(String fieldName, char val) throws PortableException {
+        writeFieldId(fieldName, CHAR);
+        writeCharField(val);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeChar(char val) throws PortableException {
+        doWriteChar(val);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeBoolean(String fieldName, boolean val) throws PortableException {
+        writeFieldId(fieldName, BOOLEAN);
+        writeBooleanField(val);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeBoolean(boolean val) throws PortableException {
+        doWriteBoolean(val);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeDecimal(String fieldName, @Nullable BigDecimal val) throws PortableException {
+        writeFieldId(fieldName, DECIMAL);
+        writeDecimalField(val);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeDecimal(@Nullable BigDecimal val) throws PortableException {
+        doWriteDecimal(val);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeString(String fieldName, @Nullable String val) throws PortableException {
+        writeFieldId(fieldName, STRING);
+        writeStringField(val);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeString(@Nullable String val) throws PortableException {
+        doWriteString(val);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeUuid(String fieldName, @Nullable UUID val) throws PortableException {
+        writeFieldId(fieldName, UUID);
+        writeUuidField(val);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeUuid(@Nullable UUID val) throws PortableException {
+        doWriteUuid(val);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeDate(String fieldName, @Nullable Date val) throws PortableException {
+        writeFieldId(fieldName, DATE);
+        writeDateField(val);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeDate(@Nullable Date val) throws PortableException {
+        doWriteDate(val);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeTimestamp(String fieldName, @Nullable Timestamp val) throws PortableException {
+        writeFieldId(fieldName, DATE);
+        writeTimestampField(val);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeTimestamp(@Nullable Timestamp val) throws PortableException {
+        doWriteTimestamp(val);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeObject(String fieldName, @Nullable Object obj) throws PortableException {
+        writeFieldId(fieldName, OBJ);
+        writeObjectField(obj);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeObject(@Nullable Object obj) throws PortableException {
+        doWriteObject(obj, false);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeObjectDetached(@Nullable Object obj) throws PortableException {
+        doWriteObject(obj, true);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeByteArray(String fieldName, @Nullable byte[] val) throws PortableException {
+        writeFieldId(fieldName, BYTE_ARR);
+        writeByteArrayField(val);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeByteArray(@Nullable byte[] val) throws PortableException {
+        doWriteByteArray(val);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeShortArray(String fieldName, @Nullable short[] val) throws PortableException {
+        writeFieldId(fieldName, SHORT_ARR);
+        writeShortArrayField(val);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeShortArray(@Nullable short[] val) throws PortableException {
+        doWriteShortArray(val);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeIntArray(String fieldName, @Nullable int[] val) throws PortableException {
+        writeFieldId(fieldName, INT_ARR);
+        writeIntArrayField(val);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeIntArray(@Nullable int[] val) throws PortableException {
+        doWriteIntArray(val);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeLongArray(String fieldName, @Nullable long[] val) throws PortableException {
+        writeFieldId(fieldName, LONG_ARR);
+        writeLongArrayField(val);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeLongArray(@Nullable long[] val) throws PortableException {
+        doWriteLongArray(val);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeFloatArray(String fieldName, @Nullable float[] val) throws PortableException {
+        writeFieldId(fieldName, FLOAT_ARR);
+        writeFloatArrayField(val);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeFloatArray(@Nullable float[] val) throws PortableException {
+        doWriteFloatArray(val);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeDoubleArray(String fieldName, @Nullable double[] val)
+        throws PortableException {
+        writeFieldId(fieldName, DOUBLE_ARR);
+        writeDoubleArrayField(val);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeDoubleArray(@Nullable double[] val) throws PortableException {
+        doWriteDoubleArray(val);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeCharArray(String fieldName, @Nullable char[] val) throws PortableException {
+        writeFieldId(fieldName, CHAR_ARR);
+        writeCharArrayField(val);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeCharArray(@Nullable char[] val) throws PortableException {
+        doWriteCharArray(val);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeBooleanArray(String fieldName, @Nullable boolean[] val)
+        throws PortableException {
+        writeFieldId(fieldName, BOOLEAN_ARR);
+        writeBooleanArrayField(val);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeBooleanArray(@Nullable boolean[] val) throws PortableException {
+        doWriteBooleanArray(val);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeDecimalArray(String fieldName, @Nullable BigDecimal[] val)
+        throws PortableException {
+        writeFieldId(fieldName, DECIMAL_ARR);
+        writeDecimalArrayField(val);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeDecimalArray(@Nullable BigDecimal[] val) throws PortableException {
+        doWriteDecimalArray(val);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeStringArray(String fieldName, @Nullable String[] val)
+        throws PortableException {
+        writeFieldId(fieldName, STRING_ARR);
+        writeStringArrayField(val);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeStringArray(@Nullable String[] val) throws PortableException {
+        doWriteStringArray(val);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeUuidArray(String fieldName, @Nullable UUID[] val) throws PortableException {
+        writeFieldId(fieldName, UUID_ARR);
+        writeUuidArrayField(val);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeUuidArray(@Nullable UUID[] val) throws PortableException {
+        doWriteUuidArray(val);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeDateArray(String fieldName, @Nullable Date[] val) throws PortableException {
+        writeFieldId(fieldName, DATE_ARR);
+        writeDateArrayField(val);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeDateArray(@Nullable Date[] val) throws PortableException {
+        doWriteDateArray(val);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeObjectArray(String fieldName, @Nullable Object[] val) throws PortableException {
+        writeFieldId(fieldName, OBJ_ARR);
+        writeObjectArrayField(val);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeObjectArray(@Nullable Object[] val) throws PortableException {
+        doWriteObjectArray(val);
+    }
+
+    /** {@inheritDoc} */
+    @Override public <T> void writeCollection(String fieldName, @Nullable Collection<T> col)
+        throws PortableException {
+        writeFieldId(fieldName, COL);
+        writeCollectionField(col);
+    }
+
+    /** {@inheritDoc} */
+    @Override public <T> void writeCollection(@Nullable Collection<T> col) throws PortableException {
+        doWriteCollection(col);
+    }
+
+    /** {@inheritDoc} */
+    @Override public <K, V> void writeMap(String fieldName, @Nullable Map<K, V> map)
+        throws PortableException {
+        writeFieldId(fieldName, MAP);
+        writeMapField(map);
+    }
+
+    /** {@inheritDoc} */
+    @Override public <K, V> void writeMap(@Nullable Map<K, V> map) throws PortableException {
+        doWriteMap(map);
+    }
+
+    /** {@inheritDoc} */
+    @Override public <T extends Enum<?>> void writeEnum(String fieldName, T val) throws PortableException {
+        writeFieldId(fieldName, ENUM);
+        writeEnumField(val);
+    }
+
+    /** {@inheritDoc} */
+    @Override public <T extends Enum<?>> void writeEnum(T val) throws PortableException {
+        doWriteEnum(val);
+    }
+
+    /** {@inheritDoc} */
+    @Override public <T extends Enum<?>> void writeEnumArray(String fieldName, T[] val) throws PortableException {
+        writeFieldId(fieldName, ENUM_ARR);
+        writeEnumArrayField(val);
+    }
+
+    /** {@inheritDoc} */
+    @Override public <T extends Enum<?>> void writeEnumArray(T[] val) throws PortableException {
+        doWriteEnumArray(val);
+    }
+
+    /** {@inheritDoc} */
+    @Override public PortableRawWriter rawWriter() {
+        if (allowFields) {
+            wCtx.out.writeInt(start + RAW_DATA_OFF_POS, wCtx.out.position() - start);
+
+            allowFields = false;
+        }
+
+        return this;
+    }
+
+    /** {@inheritDoc} */
+    @Override public PortableOutputStream out() {
+        return wCtx.out;
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeBytes(String s) throws IOException {
+        int len = s.length();
+
+        writeInt(len);
+
+        for (int i = 0; i < len; i++)
+            writeByte(s.charAt(i));
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeChars(String s) throws IOException {
+        int len = s.length();
+
+        writeInt(len);
+
+        for (int i = 0; i < len; i++)
+            writeChar(s.charAt(i));
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeUTF(String s) throws IOException {
+        writeString(s);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeByte(int v) throws IOException {
+        doWriteByte((byte)v);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeShort(int v) throws IOException {
+        doWriteShort((short)v);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeChar(int v) throws IOException {
+        doWriteChar((char)v);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void write(int b) throws IOException {
+        doWriteByte((byte)b);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void flush() throws IOException {
+        // No-op.
+    }
+
+    /**
+     * Reserve a room for an integer.
+     *
+     * @return Position in the stream where value is to be written.
+     */
+    public int reserveInt() {
+        return reserve(LEN_INT);
+    }
+
+    /**
+     * Write int value at the specific position.
+     *
+     * @param pos Position.
+     * @param val Value.
+     * @throws PortableException If failed.
+     */
+    public void writeInt(int pos, int val) throws PortableException {
+        wCtx.out.writeInt(pos, val);
+    }
+
+    /**
+     * @param fieldName Field name.
+     * @throws PortableException If fields are not allowed.
+     */
+    private void writeFieldId(String fieldName, byte fieldType) throws PortableException {
+        A.notNull(fieldName, "fieldName");
+
+        if (!allowFields)
+            throw new PortableException("Individual field can't be written after raw writer is acquired " +
+                "via rawWriter() method. Consider fixing serialization logic for class: " + cls.getName());
+
+        int id = ctx.fieldId(typeId, fieldName);
+
+        if (metaEnabled)
+            metaHashSum = 31 * metaHashSum + (id + fieldType);
+
+        doWriteInt(id);
+    }
+
+    /**
+     * Create new writer with same context.
+     * @param typeId type
+     * @return New writer.
+     */
+    PortableWriterExImpl newWriter(int typeId) {
+        PortableWriterExImpl res = new PortableWriterExImpl(ctx, wCtx);
+
+        res.typeId = typeId;
+
+        return res;
+    }
+
+    /**
+     * @return Portable context.
+     */
+    PortableContext context() {
+        return ctx;
+    }
+
+    /** */
+    private static class WriterContext {
+        /** */
+        private Map<Object, Integer> handles = new IdentityHashMap<>();
+
+        /** Output stream. */
+        private PortableOutputStream out;
+
+        /**
+         * Constructor.
+         *
+         * @param out Output stream.
+         * @param handles Handles.
+         */
+        private WriterContext(PortableOutputStream out, Map<Object, Integer> handles) {
+            this.out = out;
+            this.handles = handles == null ? new IdentityHashMap<Object, Integer>() : handles;
+        }
+
+        /**
+         * @param obj Object.
+         * @return Handle.
+         */
+        private int handle(Object obj) {
+            assert obj != null;
+
+            Integer h = handles.get(obj);
+
+            if (h != null)
+                return out.position() - h;
+            else {
+                handles.put(obj, out.position());
+
+                return -1;
+            }
+        }
+
+        /**
+         *
+         */
+        private void resetHandles() {
+            handles = new IdentityHashMap<>();
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/internal/portable/package-info.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/portable/package-info.java b/modules/core/src/main/java/org/apache/ignite/internal/portable/package-info.java
new file mode 100644
index 0000000..ccf9fad
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/package-info.java
@@ -0,0 +1,22 @@
+/*
+ * 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 description. -->
+ * Contains portable APIs internal implementation.
+ */
+package org.apache.ignite.internal.portable;
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/internal/portable/streams/PortableAbstractInputStream.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/portable/streams/PortableAbstractInputStream.java b/modules/core/src/main/java/org/apache/ignite/internal/portable/streams/PortableAbstractInputStream.java
new file mode 100644
index 0000000..9f0b1db
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/streams/PortableAbstractInputStream.java
@@ -0,0 +1,343 @@
+/*
+ * 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.portable.streams;
+
+import org.apache.ignite.portable.*;
+
+/**
+ * Portable abstract input stream.
+ */
+public abstract class PortableAbstractInputStream extends PortableAbstractStream
+    implements PortableInputStream {
+    /** Length of data inside array. */
+    protected int len;
+
+    /** {@inheritDoc} */
+    @Override public byte readByte() {
+        ensureEnoughData(1);
+
+        return readByteAndShift();
+    }
+
+    /** {@inheritDoc} */
+    @Override public byte[] readByteArray(int cnt) {
+        ensureEnoughData(cnt);
+
+        byte[] res = new byte[cnt];
+
+        copyAndShift(res, BYTE_ARR_OFF, cnt);
+
+        return res;
+    }
+
+    /** {@inheritDoc} */
+    @Override public boolean readBoolean() {
+        return readByte() == BYTE_ONE;
+    }
+
+    /** {@inheritDoc} */
+    @Override public boolean[] readBooleanArray(int cnt) {
+        ensureEnoughData(cnt);
+
+        boolean[] res = new boolean[cnt];
+
+        copyAndShift(res, BOOLEAN_ARR_OFF, cnt);
+
+        return res;
+    }
+
+    /** {@inheritDoc} */
+    @Override public short readShort() {
+        ensureEnoughData(2);
+
+        short res = readShortFast();
+
+        shift(2);
+
+        if (!LITTLE_ENDIAN)
+            res = Short.reverseBytes(res);
+
+        return res;
+    }
+
+    /** {@inheritDoc} */
+    @Override public short[] readShortArray(int cnt) {
+        int len = cnt << 1;
+
+        ensureEnoughData(len);
+
+        short[] res = new short[cnt];
+
+        copyAndShift(res, SHORT_ARR_OFF, len);
+
+        if (!LITTLE_ENDIAN) {
+            for (int i = 0; i < res.length; i++)
+                res[i] = Short.reverseBytes(res[i]);
+        }
+
+        return res;
+    }
+
+    /** {@inheritDoc} */
+    @Override public char readChar() {
+        ensureEnoughData(2);
+
+        char res = readCharFast();
+
+        shift(2);
+
+        if (!LITTLE_ENDIAN)
+            res = Character.reverseBytes(res);
+
+        return res;
+    }
+
+    /** {@inheritDoc} */
+    @Override public char[] readCharArray(int cnt) {
+        int len = cnt << 1;
+
+        ensureEnoughData(len);
+
+        char[] res = new char[cnt];
+
+        copyAndShift(res, CHAR_ARR_OFF, len);
+
+        if (!LITTLE_ENDIAN) {
+            for (int i = 0; i < res.length; i++)
+                res[i] = Character.reverseBytes(res[i]);
+        }
+
+        return res;
+    }
+
+    /** {@inheritDoc} */
+    @Override public int readInt() {
+        ensureEnoughData(4);
+
+        int res = readIntFast();
+
+        shift(4);
+
+        if (!LITTLE_ENDIAN)
+            res = Integer.reverseBytes(res);
+
+        return res;
+    }
+
+    /** {@inheritDoc} */
+    @Override public int[] readIntArray(int cnt) {
+        int len = cnt << 2;
+
+        ensureEnoughData(len);
+
+        int[] res = new int[cnt];
+
+        copyAndShift(res, INT_ARR_OFF, len);
+
+        if (!LITTLE_ENDIAN) {
+            for (int i = 0; i < res.length; i++)
+                res[i] = Integer.reverseBytes(res[i]);
+        }
+
+        return res;
+    }
+
+    /** {@inheritDoc} */
+    @Override public int readInt(int pos) {
+        int delta = pos + 4 - this.pos;
+
+        if (delta > 0)
+            ensureEnoughData(delta);
+
+        return readIntPositioned(pos);
+    }
+
+    /** {@inheritDoc} */
+    @Override public float readFloat() {
+        return Float.intBitsToFloat(readInt());
+    }
+
+    /** {@inheritDoc} */
+    @Override public float[] readFloatArray(int cnt) {
+        int len = cnt << 2;
+
+        ensureEnoughData(len);
+
+        float[] res = new float[cnt];
+
+        if (LITTLE_ENDIAN)
+            copyAndShift(res, FLOAT_ARR_OFF, len);
+        else {
+            for (int i = 0; i < res.length; i++) {
+                int x = readIntFast();
+
+                shift(4);
+
+                res[i] = Float.intBitsToFloat(Integer.reverseBytes(x));
+            }
+        }
+
+        return res;
+    }
+
+    /** {@inheritDoc} */
+    @Override public long readLong() {
+        ensureEnoughData(8);
+
+        long res = readLongFast();
+
+        shift(8);
+
+        if (!LITTLE_ENDIAN)
+            res = Long.reverseBytes(res);
+
+        return res;
+    }
+
+    /** {@inheritDoc} */
+    @Override public long[] readLongArray(int cnt) {
+        int len = cnt << 3;
+
+        ensureEnoughData(len);
+
+        long[] res = new long[cnt];
+
+        copyAndShift(res, LONG_ARR_OFF, len);
+
+        if (!LITTLE_ENDIAN) {
+            for (int i = 0; i < res.length; i++)
+                res[i] = Long.reverseBytes(res[i]);
+        }
+
+        return res;
+    }
+
+    /** {@inheritDoc} */
+    @Override public double readDouble() {
+        return Double.longBitsToDouble(readLong());
+    }
+
+    /** {@inheritDoc} */
+    @Override public double[] readDoubleArray(int cnt) {
+        int len = cnt << 3;
+
+        ensureEnoughData(len);
+
+        double[] res = new double[cnt];
+
+        if (LITTLE_ENDIAN)
+            copyAndShift(res, DOUBLE_ARR_OFF, len);
+        else {
+            for (int i = 0; i < res.length; i++) {
+                long x = readLongFast();
+
+                shift(8);
+
+                res[i] = Double.longBitsToDouble(Long.reverseBytes(x));
+            }
+        }
+
+        return res;
+    }
+
+    /** {@inheritDoc} */
+    @Override public int read(byte[] arr, int off, int len) {
+        if (len > remaining())
+            len = remaining();
+
+        copyAndShift(arr, BYTE_ARR_OFF + off, len);
+
+        return len;
+    }
+
+    /** {@inheritDoc} */
+    @Override public void position(int pos) {
+        if (remaining() + this.pos < pos)
+            throw new PortableException("Position is out of bounds: " + pos);
+        else
+            this.pos = pos;
+    }
+
+    /** {@inheritDoc} */
+    @Override public long offheapPointer() {
+        return 0;
+    }
+
+    /**
+     * Ensure that there is enough data.
+     *
+     * @param cnt Length.
+     */
+    protected void ensureEnoughData(int cnt) {
+        if (remaining() < cnt)
+            throw new PortableException("Not enough data to read the value [position=" + pos +
+                ", requiredBytes=" + cnt + ", remainingBytes=" + remaining() + ']');
+    }
+
+    /**
+     * Read next byte from the stream and perform shift.
+     *
+     * @return Next byte.
+     */
+    protected abstract byte readByteAndShift();
+
+    /**
+     * Copy data to target object shift position afterwards.
+     *
+     * @param target Target.
+     * @param off Offset.
+     * @param len Length.
+     */
+    protected abstract void copyAndShift(Object target, long off, int len);
+
+    /**
+     * Read short value (fast path).
+     *
+     * @return Short value.
+     */
+    protected abstract short readShortFast();
+
+    /**
+     * Read char value (fast path).
+     *
+     * @return Char value.
+     */
+    protected abstract char readCharFast();
+
+    /**
+     * Read int value (fast path).
+     *
+     * @return Int value.
+     */
+    protected abstract int readIntFast();
+
+    /**
+     * Read long value (fast path).
+     *
+     * @return Long value.
+     */
+    protected abstract long readLongFast();
+
+    /**
+     * Internal routine for positioned int value read.
+     *
+     * @param pos Position.
+     * @return Int value.
+     */
+    protected abstract int readIntPositioned(int pos);
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/internal/portable/streams/PortableAbstractOutputStream.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/portable/streams/PortableAbstractOutputStream.java b/modules/core/src/main/java/org/apache/ignite/internal/portable/streams/PortableAbstractOutputStream.java
new file mode 100644
index 0000000..2c3179a
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/streams/PortableAbstractOutputStream.java
@@ -0,0 +1,323 @@
+/*
+ * 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.portable.streams;
+
+/**
+ * Base portable output stream.
+ */
+public abstract class PortableAbstractOutputStream extends PortableAbstractStream
+    implements PortableOutputStream {
+    /** Minimal capacity when it is reasonable to start doubling resize. */
+    private static final int MIN_CAP = 256;
+
+    /** {@inheritDoc} */
+    @Override public void writeByte(byte val) {
+        ensureCapacity(pos + 1);
+
+        writeByteAndShift(val);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeByteArray(byte[] val) {
+        ensureCapacity(pos + val.length);
+
+        copyAndShift(val, BYTE_ARR_OFF, val.length);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeBoolean(boolean val) {
+        writeByte(val ? BYTE_ONE : BYTE_ZERO);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeBooleanArray(boolean[] val) {
+        ensureCapacity(pos + val.length);
+
+        copyAndShift(val, BOOLEAN_ARR_OFF, val.length);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeShort(short val) {
+        ensureCapacity(pos + 2);
+
+        if (!LITTLE_ENDIAN)
+            val = Short.reverseBytes(val);
+
+        writeShortFast(val);
+
+        shift(2);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeShortArray(short[] val) {
+        int cnt = val.length << 1;
+
+        ensureCapacity(pos + cnt);
+
+        if (LITTLE_ENDIAN)
+            copyAndShift(val, SHORT_ARR_OFF, cnt);
+        else {
+            for (short item : val)
+                writeShortFast(Short.reverseBytes(item));
+
+            shift(cnt);
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeChar(char val) {
+        ensureCapacity(pos + 2);
+
+        if (!LITTLE_ENDIAN)
+            val = Character.reverseBytes(val);
+
+        writeCharFast(val);
+
+        shift(2);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeCharArray(char[] val) {
+        int cnt = val.length << 1;
+
+        ensureCapacity(pos + cnt);
+
+        if (LITTLE_ENDIAN)
+            copyAndShift(val, CHAR_ARR_OFF, cnt);
+        else {
+            for (char item : val)
+                writeCharFast(Character.reverseBytes(item));
+
+            shift(cnt);
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeInt(int val) {
+        ensureCapacity(pos + 4);
+
+        if (!LITTLE_ENDIAN)
+            val = Integer.reverseBytes(val);
+
+        writeIntFast(val);
+
+        shift(4);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeInt(int pos, int val) {
+        ensureCapacity(pos + 4);
+
+        writeIntPositioned(pos, val);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeIntArray(int[] val) {
+        int cnt = val.length << 2;
+
+        ensureCapacity(pos + cnt);
+
+        if (LITTLE_ENDIAN)
+            copyAndShift(val, INT_ARR_OFF, cnt);
+        else {
+            for (int item : val)
+                writeIntFast(Integer.reverseBytes(item));
+
+            shift(cnt);
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeFloat(float val) {
+        writeInt(Float.floatToIntBits(val));
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeFloatArray(float[] val) {
+        int cnt = val.length << 2;
+
+        ensureCapacity(pos + cnt);
+
+        if (LITTLE_ENDIAN)
+            copyAndShift(val, FLOAT_ARR_OFF, cnt);
+        else {
+            for (float item : val) {
+                writeIntFast(Integer.reverseBytes(Float.floatToIntBits(item)));
+
+                shift(4);
+            }
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeLong(long val) {
+        ensureCapacity(pos + 8);
+
+        if (!LITTLE_ENDIAN)
+            val = Long.reverseBytes(val);
+
+        writeLongFast(val);
+
+        shift(8);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeLongArray(long[] val) {
+        int cnt = val.length << 3;
+
+        ensureCapacity(pos + cnt);
+
+        if (LITTLE_ENDIAN)
+            copyAndShift(val, LONG_ARR_OFF, cnt);
+        else {
+            for (long item : val)
+                writeLongFast(Long.reverseBytes(item));
+
+            shift(cnt);
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeDouble(double val) {
+        writeLong(Double.doubleToLongBits(val));
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeDoubleArray(double[] val) {
+        int cnt = val.length << 3;
+
+        ensureCapacity(pos + cnt);
+
+        if (LITTLE_ENDIAN)
+            copyAndShift(val, DOUBLE_ARR_OFF, cnt);
+        else {
+            for (double item : val) {
+                writeLongFast(Long.reverseBytes(Double.doubleToLongBits(item)));
+
+                shift(8);
+            }
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override public void write(byte[] arr, int off, int len) {
+        ensureCapacity(pos + len);
+
+        copyAndShift(arr, BYTE_ARR_OFF + off, len);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void write(long addr, int cnt) {
+        ensureCapacity(pos + cnt);
+
+        copyAndShift(null, addr, cnt);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void position(int pos) {
+        ensureCapacity(pos);
+
+        this.pos = pos;
+    }
+
+    /** {@inheritDoc} */
+    @Override public long offheapPointer() {
+        return 0;
+    }
+
+    /**
+     * Calculate new capacity.
+     *
+     * @param curCap Current capacity.
+     * @param reqCap Required capacity.
+     * @return New capacity.
+     */
+    protected static int capacity(int curCap, int reqCap) {
+        int newCap;
+
+        if (reqCap < MIN_CAP)
+            newCap = MIN_CAP;
+        else {
+            newCap = curCap << 1;
+
+            if (newCap < reqCap)
+                newCap = reqCap;
+        }
+
+        return newCap;
+    }
+
+    /**
+     * Write next byte to the stream.
+     *
+     * @param val Value.
+     */
+    protected abstract void writeByteAndShift(byte val);
+
+    /**
+     * Copy source object to the stream shift position afterwards.
+     *
+     * @param src Source.
+     * @param off Offset.
+     * @param len Length.
+     */
+    protected abstract void copyAndShift(Object src, long off, int len);
+
+    /**
+     * Write short value (fast path).
+     *
+     * @param val Short value.
+     */
+    protected abstract void writeShortFast(short val);
+
+    /**
+     * Write char value (fast path).
+     *
+     * @param val Char value.
+     */
+    protected abstract void writeCharFast(char val);
+
+    /**
+     * Write int value (fast path).
+     *
+     * @param val Int value.
+     */
+    protected abstract void writeIntFast(int val);
+
+    /**
+     * Write long value (fast path).
+     *
+     * @param val Long value.
+     */
+    protected abstract void writeLongFast(long val);
+
+    /**
+     * Write int value to the given position.
+     *
+     * @param pos Position.
+     * @param val Value.
+     */
+    protected abstract void writeIntPositioned(int pos, int val);
+
+    /**
+     * Ensure capacity.
+     *
+     * @param cnt Required byte count.
+     */
+    protected abstract void ensureCapacity(int cnt);
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/internal/portable/streams/PortableAbstractStream.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/portable/streams/PortableAbstractStream.java b/modules/core/src/main/java/org/apache/ignite/internal/portable/streams/PortableAbstractStream.java
new file mode 100644
index 0000000..a39662b
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/streams/PortableAbstractStream.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.portable.streams;
+
+import org.apache.ignite.internal.util.*;
+
+import sun.misc.*;
+
+import java.nio.*;
+
+/**
+ * Portable abstract stream.
+ */
+public abstract class PortableAbstractStream implements PortableStream {
+    /** Byte: zero. */
+    protected static final byte BYTE_ZERO = 0;
+
+    /** Byte: one. */
+    protected static final byte BYTE_ONE = 1;
+
+    /** Whether little endian is used on the platform. */
+    protected static final boolean LITTLE_ENDIAN = ByteOrder.nativeOrder() == ByteOrder.LITTLE_ENDIAN;
+
+    /** Unsafe instance. */
+    protected static final Unsafe UNSAFE = GridUnsafe.unsafe();
+
+    /** Array offset: boolean. */
+    protected static final long BOOLEAN_ARR_OFF = UNSAFE.arrayBaseOffset(boolean[].class);
+
+    /** Array offset: byte. */
+    protected static final long BYTE_ARR_OFF = UNSAFE.arrayBaseOffset(byte[].class);
+
+    /** Array offset: short. */
+    protected static final long SHORT_ARR_OFF = UNSAFE.arrayBaseOffset(short[].class);
+
+    /** Array offset: char. */
+    protected static final long CHAR_ARR_OFF = UNSAFE.arrayBaseOffset(char[].class);
+
+    /** Array offset: int. */
+    protected static final long INT_ARR_OFF = UNSAFE.arrayBaseOffset(int[].class);
+
+    /** Array offset: float. */
+    protected static final long FLOAT_ARR_OFF = UNSAFE.arrayBaseOffset(float[].class);
+
+    /** Array offset: long. */
+    protected static final long LONG_ARR_OFF = UNSAFE.arrayBaseOffset(long[].class);
+
+    /** Array offset: double. */
+    protected static final long DOUBLE_ARR_OFF = UNSAFE.arrayBaseOffset(double[].class);
+
+    /** Position. */
+    protected int pos;
+
+    /** {@inheritDoc} */
+    @Override public int position() {
+        return pos;
+    }
+
+    /**
+     * Shift position.
+     *
+     * @param cnt Byte count.
+     */
+    protected void shift(int cnt) {
+        pos += cnt;
+    }
+}


[51/59] [abbrv] ignite git commit: Merge remote-tracking branch 'origin/master'

Posted by vk...@apache.org.
Merge remote-tracking branch 'origin/master'


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

Branch: refs/heads/ignite-884
Commit: 824cfa4b59d538eee5b3d53fb4af4c41e8412038
Parents: 8529e10 c9a5340
Author: vozerov-gridgain <vo...@gridgain.com>
Authored: Wed Aug 26 15:44:09 2015 +0300
Committer: vozerov-gridgain <vo...@gridgain.com>
Committed: Wed Aug 26 15:44:09 2015 +0300

----------------------------------------------------------------------
 .../processors/cache/IgniteCacheManyAsyncOperationsTest.java       | 2 +-
 .../java/org/apache/ignite/testsuites/IgniteCacheTestSuite.java    | 1 +
 2 files changed, 2 insertions(+), 1 deletion(-)
----------------------------------------------------------------------



[15/59] [abbrv] ignite git commit: ignite-1258: updated classnames.properties file

Posted by vk...@apache.org.
ignite-1258: updated classnames.properties file


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

Branch: refs/heads/ignite-884
Commit: a03584afe44badf0dba7a2a6d975a7fe4c752156
Parents: 878dcd9
Author: Denis Magda <dm...@gridgain.com>
Authored: Tue Aug 25 10:16:42 2015 +0300
Committer: Denis Magda <dm...@gridgain.com>
Committed: Tue Aug 25 10:16:42 2015 +0300

----------------------------------------------------------------------
 .../main/resources/META-INF/classnames.properties   | 16 ++++++++++------
 1 file changed, 10 insertions(+), 6 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/a03584af/modules/core/src/main/resources/META-INF/classnames.properties
----------------------------------------------------------------------
diff --git a/modules/core/src/main/resources/META-INF/classnames.properties b/modules/core/src/main/resources/META-INF/classnames.properties
index c5f060b..fb1673a 100644
--- a/modules/core/src/main/resources/META-INF/classnames.properties
+++ b/modules/core/src/main/resources/META-INF/classnames.properties
@@ -72,19 +72,26 @@ org.apache.ignite.cache.store.jdbc.CacheAbstractJdbcStore$EntryMapping$1
 org.apache.ignite.cache.store.jdbc.CacheAbstractJdbcStore$EntryMapping$2
 org.apache.ignite.cache.store.jdbc.CacheJdbcBlobStoreFactory
 org.apache.ignite.cache.store.jdbc.CacheJdbcPojoStoreFactory
+org.apache.ignite.cache.store.jdbc.dialect.BasicJdbcDialect
 org.apache.ignite.cache.store.jdbc.dialect.BasicJdbcDialect$1
 org.apache.ignite.cache.store.jdbc.dialect.BasicJdbcDialect$2
 org.apache.ignite.cache.store.jdbc.dialect.BasicJdbcDialect$3
 org.apache.ignite.cache.store.jdbc.dialect.BasicJdbcDialect$4
 org.apache.ignite.cache.store.jdbc.dialect.BasicJdbcDialect$5
+org.apache.ignite.cache.store.jdbc.dialect.DB2Dialect
 org.apache.ignite.cache.store.jdbc.dialect.DB2Dialect$1
 org.apache.ignite.cache.store.jdbc.dialect.DB2Dialect$2
 org.apache.ignite.cache.store.jdbc.dialect.DB2Dialect$3
+org.apache.ignite.cache.store.jdbc.dialect.H2Dialect
+org.apache.ignite.cache.store.jdbc.dialect.JdbcDialect
+org.apache.ignite.cache.store.jdbc.dialect.MySQLDialect
 org.apache.ignite.cache.store.jdbc.dialect.MySQLDialect$1
+org.apache.ignite.cache.store.jdbc.dialect.OracleDialect
 org.apache.ignite.cache.store.jdbc.dialect.OracleDialect$1
 org.apache.ignite.cache.store.jdbc.dialect.OracleDialect$2
 org.apache.ignite.cache.store.jdbc.dialect.OracleDialect$3
 org.apache.ignite.cache.store.jdbc.dialect.OracleDialect$4
+org.apache.ignite.cache.store.jdbc.dialect.SQLServerDialect
 org.apache.ignite.cache.store.jdbc.dialect.SQLServerDialect$1
 org.apache.ignite.cache.store.jdbc.dialect.SQLServerDialect$2
 org.apache.ignite.cache.store.jdbc.dialect.SQLServerDialect$3
@@ -247,10 +254,6 @@ org.apache.ignite.internal.executor.GridExecutorService
 org.apache.ignite.internal.executor.GridExecutorService$1
 org.apache.ignite.internal.executor.GridExecutorService$TaskTerminateListener
 org.apache.ignite.internal.igfs.common.IgfsIpcCommand
-org.apache.ignite.internal.interop.InteropAwareEventFilter
-org.apache.ignite.internal.interop.InteropBootstrapFactory
-org.apache.ignite.internal.interop.InteropException
-org.apache.ignite.internal.interop.InteropNoCallbackException
 org.apache.ignite.internal.managers.GridManagerAdapter$1$1
 org.apache.ignite.internal.managers.checkpoint.GridCheckpointManager$CheckpointSet
 org.apache.ignite.internal.managers.checkpoint.GridCheckpointRequest
@@ -275,6 +278,7 @@ org.apache.ignite.internal.managers.eventstorage.GridEventStorageMessage
 org.apache.ignite.internal.managers.indexing.GridIndexingManager$1
 org.apache.ignite.internal.managers.loadbalancer.GridLoadBalancerAdapter
 org.apache.ignite.internal.managers.loadbalancer.GridLoadBalancerManager$1
+org.apache.ignite.internal.platform.PlatformAwareEventFilter
 org.apache.ignite.internal.portable.PortableClassDescriptor$Mode
 org.apache.ignite.internal.portable.PortableContext
 org.apache.ignite.internal.portable.PortableLazyMap$1$1$1
@@ -422,8 +426,7 @@ org.apache.ignite.internal.processors.cache.GridCachePartitionExchangeManager$Ex
 org.apache.ignite.internal.processors.cache.GridCachePartitionExchangeManager$MessageHandler
 org.apache.ignite.internal.processors.cache.GridCacheProcessor$2
 org.apache.ignite.internal.processors.cache.GridCacheProcessor$3
-org.apache.ignite.internal.processors.cache.GridCacheProcessor$4
-org.apache.ignite.internal.processors.cache.GridCacheProcessor$6
+org.apache.ignite.internal.processors.cache.GridCacheProcessor$5
 org.apache.ignite.internal.processors.cache.GridCacheProcessor$LocalAffinityFunction
 org.apache.ignite.internal.processors.cache.GridCacheProxyImpl
 org.apache.ignite.internal.processors.cache.GridCacheReturn
@@ -554,6 +557,7 @@ org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtTxLocalAdapte
 org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtTxPrepareFuture$1
 org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtTxPrepareFuture$2
 org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtTxPrepareFuture$3
+org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtTxPrepareFuture$4
 org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtTxPrepareRequest
 org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtTxPrepareResponse
 org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtTxRemote


[32/59] [abbrv] ignite git commit: Moving platform classes to "...internal.processors..." package to follow Ignite common approach.

Posted by vk...@apache.org.
Moving platform classes to "...internal.processors..." package to follow Ignite common approach.


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

Branch: refs/heads/ignite-884
Commit: 2225f8d2aeb8836ad2bf0573584b3affd7b4aecc
Parents: c47a706
Author: vozerov-gridgain <vo...@gridgain.com>
Authored: Wed Aug 26 09:36:44 2015 +0300
Committer: vozerov-gridgain <vo...@gridgain.com>
Committed: Wed Aug 26 09:36:44 2015 +0300

----------------------------------------------------------------------
 .../internal/platform/PlatformBootstrap.java    |  36 -
 .../platform/PlatformBootstrapFactory.java      |  37 -
 .../internal/platform/PlatformException.java    |  71 --
 .../internal/platform/PlatformIgnition.java     | 187 ----
 .../platform/PlatformNoCallbackException.java   |  50 --
 .../callback/PlatformCallbackGateway.java       | 869 -------------------
 .../callback/PlatformCallbackUtils.java         | 468 ----------
 .../platform/memory/PlatformAbstractMemory.java | 121 ---
 .../PlatformBigEndianInputStreamImpl.java       | 126 ---
 .../PlatformBigEndianOutputStreamImpl.java      | 162 ----
 .../platform/memory/PlatformExternalMemory.java |  55 --
 .../platform/memory/PlatformInputStream.java    |  30 -
 .../memory/PlatformInputStreamImpl.java         | 323 -------
 .../platform/memory/PlatformMemory.java         |  77 --
 .../platform/memory/PlatformMemoryManager.java  |  46 -
 .../memory/PlatformMemoryManagerImpl.java       |  83 --
 .../platform/memory/PlatformMemoryPool.java     | 133 ---
 .../platform/memory/PlatformMemoryUtils.java    | 468 ----------
 .../platform/memory/PlatformOutputStream.java   |  30 -
 .../memory/PlatformOutputStreamImpl.java        | 259 ------
 .../platform/memory/PlatformPooledMemory.java   |  63 --
 .../platform/memory/PlatformUnpooledMemory.java |  51 --
 .../platform/utils/PlatformReaderBiClosure.java |  34 -
 .../platform/utils/PlatformReaderClosure.java   |  34 -
 .../platform/utils/PlatformWriterBiClosure.java |  34 -
 .../platform/utils/PlatformWriterClosure.java   |  33 -
 .../processors/platform/PlatformBootstrap.java  |  36 +
 .../platform/PlatformBootstrapFactory.java      |  37 +
 .../processors/platform/PlatformException.java  |  71 ++
 .../processors/platform/PlatformIgnition.java   | 186 ++++
 .../platform/PlatformNoCallbackException.java   |  50 ++
 .../callback/PlatformCallbackGateway.java       | 869 +++++++++++++++++++
 .../callback/PlatformCallbackUtils.java         | 468 ++++++++++
 .../platform/memory/PlatformAbstractMemory.java | 121 +++
 .../PlatformBigEndianInputStreamImpl.java       | 126 +++
 .../PlatformBigEndianOutputStreamImpl.java      | 162 ++++
 .../platform/memory/PlatformExternalMemory.java |  55 ++
 .../platform/memory/PlatformInputStream.java    |  30 +
 .../memory/PlatformInputStreamImpl.java         | 323 +++++++
 .../platform/memory/PlatformMemory.java         |  77 ++
 .../platform/memory/PlatformMemoryManager.java  |  46 +
 .../memory/PlatformMemoryManagerImpl.java       |  83 ++
 .../platform/memory/PlatformMemoryPool.java     | 133 +++
 .../platform/memory/PlatformMemoryUtils.java    | 468 ++++++++++
 .../platform/memory/PlatformOutputStream.java   |  30 +
 .../memory/PlatformOutputStreamImpl.java        | 259 ++++++
 .../platform/memory/PlatformPooledMemory.java   |  63 ++
 .../platform/memory/PlatformUnpooledMemory.java |  51 ++
 .../platform/utils/PlatformReaderBiClosure.java |  34 +
 .../platform/utils/PlatformReaderClosure.java   |  34 +
 .../platform/utils/PlatformWriterBiClosure.java |  34 +
 .../platform/utils/PlatformWriterClosure.java   |  33 +
 52 files changed, 3879 insertions(+), 3880 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/2225f8d2/modules/platform/src/main/java/org/apache/ignite/internal/platform/PlatformBootstrap.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/platform/PlatformBootstrap.java b/modules/platform/src/main/java/org/apache/ignite/internal/platform/PlatformBootstrap.java
deleted file mode 100644
index faee665..0000000
--- a/modules/platform/src/main/java/org/apache/ignite/internal/platform/PlatformBootstrap.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * 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.platform;
-
-import org.apache.ignite.configuration.*;
-import org.apache.ignite.internal.processors.platform.*;
-
-/**
- * Platform bootstrap. Responsible for starting Ignite node with non-Java platform.
- */
-public interface PlatformBootstrap {
-    /**
-     * Start Ignite node.
-     *
-     * @param cfg Configuration.
-     * @param envPtr Environment pointer.
-     * @param dataPtr Optional pointer to additional data required for startup.
-     * @return Platform processor.
-     */
-    public PlatformProcessor start(IgniteConfiguration cfg, long envPtr, long dataPtr);
-}

http://git-wip-us.apache.org/repos/asf/ignite/blob/2225f8d2/modules/platform/src/main/java/org/apache/ignite/internal/platform/PlatformBootstrapFactory.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/platform/PlatformBootstrapFactory.java b/modules/platform/src/main/java/org/apache/ignite/internal/platform/PlatformBootstrapFactory.java
deleted file mode 100644
index 31d1ca5..0000000
--- a/modules/platform/src/main/java/org/apache/ignite/internal/platform/PlatformBootstrapFactory.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * 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.platform;
-
-/**
- * Platform bootstrap factory.
- */
-public interface PlatformBootstrapFactory {
-    /**
-     * Get bootstrap factory ID.
-     *
-     * @return ID.
-     */
-    public int id();
-
-    /**
-     * Create bootstrap instance.
-     *
-     * @return Bootstrap instance.
-     */
-    public PlatformBootstrap create();
-}

http://git-wip-us.apache.org/repos/asf/ignite/blob/2225f8d2/modules/platform/src/main/java/org/apache/ignite/internal/platform/PlatformException.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/platform/PlatformException.java b/modules/platform/src/main/java/org/apache/ignite/internal/platform/PlatformException.java
deleted file mode 100644
index d0bf565..0000000
--- a/modules/platform/src/main/java/org/apache/ignite/internal/platform/PlatformException.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * 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.platform;
-
-import org.apache.ignite.*;
-import org.apache.ignite.internal.util.typedef.internal.*;
-import org.jetbrains.annotations.*;
-
-/**
- * Interop checked exception.
- */
-public class PlatformException extends IgniteCheckedException {
-    /** */
-    private static final long serialVersionUID = 0L;
-
-    /**
-     * Create empty exception.
-     */
-    public PlatformException() {
-        // No-op.
-    }
-
-    /**
-     * Creates new exception with given error message.
-     *
-     * @param msg Error message.
-     */
-    public PlatformException(String msg) {
-        super(msg);
-    }
-
-    /**
-     * Creates new grid exception with given throwable as a cause and
-     * source of error message.
-     *
-     * @param cause Non-null throwable cause.
-     */
-    public PlatformException(Throwable cause) {
-        this(cause.getMessage(), cause);
-    }
-
-    /**
-     * Creates new exception with given error message and optional nested exception.
-     *
-     * @param msg Error message.
-     * @param cause Optional nested exception (can be {@code null}).
-     */
-    public PlatformException(String msg, @Nullable Throwable cause) {
-        super(msg, cause);
-    }
-
-    /** {@inheritDoc} */
-    @Override public String toString() {
-        return S.toString(PlatformException.class, this);
-    }
-}

http://git-wip-us.apache.org/repos/asf/ignite/blob/2225f8d2/modules/platform/src/main/java/org/apache/ignite/internal/platform/PlatformIgnition.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/platform/PlatformIgnition.java b/modules/platform/src/main/java/org/apache/ignite/internal/platform/PlatformIgnition.java
deleted file mode 100644
index 2d31307..0000000
--- a/modules/platform/src/main/java/org/apache/ignite/internal/platform/PlatformIgnition.java
+++ /dev/null
@@ -1,187 +0,0 @@
-/*
- * 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.platform;
-
-import org.apache.ignite.*;
-import org.apache.ignite.configuration.*;
-import org.apache.ignite.internal.*;
-import org.apache.ignite.internal.processors.platform.*;
-import org.apache.ignite.internal.processors.resource.*;
-import org.apache.ignite.internal.util.typedef.internal.*;
-import org.apache.ignite.lang.*;
-import org.jetbrains.annotations.*;
-
-import java.net.*;
-import java.security.*;
-import java.util.*;
-
-/**
- * Entry point for platform nodes.
- */
-@SuppressWarnings("UnusedDeclaration")
-public class PlatformIgnition {
-    /** Map with active instances. */
-    private static final HashMap<String, PlatformProcessor> instances = new HashMap<>();
-
-    /**
-     * Start Ignite node in platform mode.
-     *
-     * @param springCfgPath Spring configuration path.
-     * @param gridName Grid name.
-     * @param factoryId Factory ID.
-     * @param envPtr Environment pointer.
-     * @param dataPtr Optional pointer to additional data required for startup.
-     * @return Ignite instance.
-     */
-    public static synchronized PlatformProcessor start(@Nullable String springCfgPath, @Nullable String gridName,
-        int factoryId, long envPtr, long dataPtr) {
-        if (envPtr <= 0)
-            throw new IgniteException("Environment pointer must be positive.");
-
-        ClassLoader oldClsLdr = Thread.currentThread().getContextClassLoader();
-
-        Thread.currentThread().setContextClassLoader(PlatformProcessor.class.getClassLoader());
-
-        try {
-            IgniteConfiguration cfg = configuration(springCfgPath);
-
-            if (gridName != null)
-                cfg.setGridName(gridName);
-            else
-                gridName = cfg.getGridName();
-
-            PlatformBootstrap bootstrap = bootstrap(factoryId);
-
-            PlatformProcessor proc = bootstrap.start(cfg, envPtr, dataPtr);
-
-            PlatformProcessor old = instances.put(gridName, proc);
-
-            assert old == null;
-
-            return proc;
-        }
-        finally {
-            Thread.currentThread().setContextClassLoader(oldClsLdr);
-        }
-    }
-
-    /**
-     * Get instance by environment pointer.
-     *
-     * @param gridName Grid name.
-     * @return Instance or {@code null} if it doesn't exist (never started or stopped).
-     */
-    @Nullable public static synchronized PlatformProcessor instance(@Nullable String gridName) {
-        return instances.get(gridName);
-    }
-
-    /**
-     * Get environment pointer of the given instance.
-     *
-     * @param gridName Grid name.
-     * @return Environment pointer or {@code 0} in case grid with such name doesn't exist.
-     */
-    public static synchronized long environmentPointer(@Nullable String gridName) {
-        PlatformProcessor proc = instance(gridName);
-
-        return proc != null ? proc.environmentPointer() : 0;
-    }
-
-    /**
-     * Stop single instance.
-     *
-     * @param gridName Grid name,
-     * @param cancel Cancel flag.
-     * @return {@code True} if instance was found and stopped.
-     */
-    public static synchronized boolean stop(@Nullable String gridName, boolean cancel) {
-        if (Ignition.stop(gridName, cancel)) {
-            PlatformProcessor old = instances.remove(gridName);
-
-            assert old != null;
-
-            return true;
-        }
-        else
-            return false;
-    }
-
-    /**
-     * Stop all instances.
-     *
-     * @param cancel Cancel flag.
-     */
-    public static synchronized void stopAll(boolean cancel) {
-        for (PlatformProcessor proc : instances.values())
-            Ignition.stop(proc.ignite().name(), cancel);
-
-        instances.clear();
-    }
-
-    /**
-     * Create configuration.
-     *
-     * @param springCfgPath Path to Spring XML.
-     * @return Configuration.
-     */
-    private static IgniteConfiguration configuration(@Nullable String springCfgPath) {
-        try {
-            URL url = springCfgPath == null ? U.resolveIgniteUrl(IgnitionEx.DFLT_CFG) :
-                U.resolveSpringUrl(springCfgPath);
-
-            IgniteBiTuple<IgniteConfiguration, GridSpringResourceContext> t = IgnitionEx.loadConfiguration(url);
-
-            return t.get1();
-        }
-        catch (IgniteCheckedException e) {
-            throw new IgniteException("Failed to instantiate configuration from Spring XML: " + springCfgPath, e);
-        }
-    }
-
-    /**
-     * Create bootstrap for the given factory ID.
-     *
-     * @param factoryId Factory ID.
-     * @return Bootstrap.
-     */
-    private static PlatformBootstrap bootstrap(final int factoryId) {
-        PlatformBootstrapFactory factory = AccessController.doPrivileged(
-            new PrivilegedAction<PlatformBootstrapFactory>() {
-                @Override public PlatformBootstrapFactory run() {
-                    for (PlatformBootstrapFactory factory : ServiceLoader.load(PlatformBootstrapFactory.class)) {
-                        if (factory.id() == factoryId)
-                            return factory;
-                    }
-
-                    return null;
-                }
-            });
-
-        if (factory == null)
-            throw new IgniteException("Interop factory is not found (did you put into the classpath?): " + factoryId);
-
-        return factory.create();
-    }
-
-    /**
-     * Private constructor.
-     */
-    private PlatformIgnition() {
-        // No-op.
-    }
-}

http://git-wip-us.apache.org/repos/asf/ignite/blob/2225f8d2/modules/platform/src/main/java/org/apache/ignite/internal/platform/PlatformNoCallbackException.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/platform/PlatformNoCallbackException.java b/modules/platform/src/main/java/org/apache/ignite/internal/platform/PlatformNoCallbackException.java
deleted file mode 100644
index 893c332..0000000
--- a/modules/platform/src/main/java/org/apache/ignite/internal/platform/PlatformNoCallbackException.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * 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.platform;
-
-import org.apache.ignite.internal.util.typedef.internal.*;
-
-/**
- * Exception raised when interop callback is not set in native platform.
- */
-@SuppressWarnings("UnusedDeclaration")
-public class PlatformNoCallbackException extends PlatformException {
-    /** */
-    private static final long serialVersionUID = 0L;
-
-    /**
-     * Constructor.
-     */
-    public PlatformNoCallbackException() {
-        // No-op.
-    }
-
-    /**
-     * Constructor.
-     *
-     * @param msg Message.
-     */
-    public PlatformNoCallbackException(String msg) {
-        super(msg);
-    }
-
-    /** {@inheritDoc} */
-    @Override public String toString() {
-        return S.toString(PlatformNoCallbackException.class, this);
-    }
-}

http://git-wip-us.apache.org/repos/asf/ignite/blob/2225f8d2/modules/platform/src/main/java/org/apache/ignite/internal/platform/callback/PlatformCallbackGateway.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/platform/callback/PlatformCallbackGateway.java b/modules/platform/src/main/java/org/apache/ignite/internal/platform/callback/PlatformCallbackGateway.java
deleted file mode 100644
index d565c00..0000000
--- a/modules/platform/src/main/java/org/apache/ignite/internal/platform/callback/PlatformCallbackGateway.java
+++ /dev/null
@@ -1,869 +0,0 @@
-/*
- * 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.platform.callback;
-
-import org.apache.ignite.*;
-import org.apache.ignite.internal.util.*;
-
-/**
- * Gateway to all platform-dependent callbacks. Implementers might extend this class and provide additional callbacks.
- */
-@SuppressWarnings({"FieldCanBeLocal", "UnusedDeclaration"})
-public class PlatformCallbackGateway {
-    /** Environment pointer. */
-    protected final long envPtr;
-
-    /** Lock. */
-    private final GridSpinReadWriteLock lock = new GridSpinReadWriteLock();
-
-    /**
-     * Native gateway.
-     *
-     * @param envPtr Environment pointer.
-     */
-    public PlatformCallbackGateway(long envPtr) {
-        this.envPtr = envPtr;
-    }
-
-    /**
-     * Get environment pointer.
-     *
-     * @return Environment pointer.
-     */
-    public long environmentPointer() {
-        return envPtr;
-    }
-
-    /**
-     * Create cache store.
-     *
-     * @param memPtr Memory pointer.
-     * @return Pointer.
-     */
-    public long cacheStoreCreate(long memPtr) {
-        enter();
-
-        try {
-            return PlatformCallbackUtils.cacheStoreCreate(envPtr, memPtr);
-        }
-        finally {
-            leave();
-        }
-    }
-
-    /**
-     * @param objPtr Object pointer.
-     * @param memPtr Memory pointer.
-     * @param cb Callback.
-     * @return Result.
-     */
-    public int cacheStoreInvoke(long objPtr, long memPtr, Object cb) {
-        enter();
-
-        try {
-            return PlatformCallbackUtils.cacheStoreInvoke(envPtr, objPtr, memPtr, cb);
-        }
-        finally {
-            leave();
-        }
-    }
-
-    /**
-     * @param objPtr Object pointer.
-     */
-    public void cacheStoreDestroy(long objPtr) {
-        enter();
-
-        try {
-            PlatformCallbackUtils.cacheStoreDestroy(envPtr, objPtr);
-        }
-        finally {
-            leave();
-        }
-    }
-
-    /**
-     * Creates cache store session.
-     *
-     * @param storePtr Store instance pointer.
-     * @return Session instance pointer.
-     */
-    public long cacheStoreSessionCreate(long storePtr) {
-        enter();
-
-        try {
-            return PlatformCallbackUtils.cacheStoreSessionCreate(envPtr, storePtr);
-        }
-        finally {
-            leave();
-        }
-    }
-
-    /**
-     * Creates cache entry filter and returns a pointer.
-     *
-     * @param memPtr Memory pointer.
-     * @return Pointer.
-     */
-    public long cacheEntryFilterCreate(long memPtr) {
-        enter();
-
-        try {
-            return PlatformCallbackUtils.cacheEntryFilterCreate(envPtr, memPtr);
-        }
-        finally {
-            leave();
-        }
-    }
-
-    /**
-     * @param ptr Pointer.
-     * @param memPtr Memory pointer.
-     * @return Result.
-     */
-    public int cacheEntryFilterApply(long ptr, long memPtr) {
-        enter();
-
-        try {
-            return PlatformCallbackUtils.cacheEntryFilterApply(envPtr, ptr, memPtr);
-        }
-        finally {
-            leave();
-        }
-    }
-
-    /**
-     * @param ptr Pointer.
-     */
-    public void cacheEntryFilterDestroy(long ptr) {
-        enter();
-
-        try {
-            PlatformCallbackUtils.cacheEntryFilterDestroy(envPtr, ptr);
-        }
-        finally {
-            leave();
-        }
-    }
-
-    /**
-     * Invoke cache entry processor.
-     *
-     * @param outMemPtr Output memory pointer.
-     * @param inMemPtr Input memory pointer.
-     */
-    public void cacheInvoke(long outMemPtr, long inMemPtr) {
-        enter();
-
-        try {
-            PlatformCallbackUtils.cacheInvoke(envPtr, outMemPtr, inMemPtr);
-        }
-        finally {
-            leave();
-        }
-    }
-
-    /**
-     * Perform native task map. Do not throw exceptions, serializing them to the output stream instead.
-     *
-     * @param taskPtr Task pointer.
-     * @param outMemPtr Output memory pointer (exists if topology changed, otherwise {@code 0}).
-     * @param inMemPtr Input memory pointer.
-     */
-    public void computeTaskMap(long taskPtr, long outMemPtr, long inMemPtr) {
-        enter();
-
-        try {
-            PlatformCallbackUtils.computeTaskMap(envPtr, taskPtr, outMemPtr, inMemPtr);
-        }
-        finally {
-            leave();
-        }
-    }
-
-    /**
-     * Perform native task job result notification.
-     *
-     * @param taskPtr Task pointer.
-     * @param jobPtr Job pointer.
-     * @param memPtr Memory pointer (always zero for local job execution).
-     * @return Job result enum ordinal.
-     */
-    public int computeTaskJobResult(long taskPtr, long jobPtr, long memPtr) {
-        enter();
-
-        try {
-            return PlatformCallbackUtils.computeTaskJobResult(envPtr, taskPtr, jobPtr, memPtr);
-        }
-        finally {
-            leave();
-        }
-    }
-
-    /**
-     * Perform native task reduce.
-     *
-     * @param taskPtr Task pointer.
-     */
-    public void computeTaskReduce(long taskPtr) {
-        enter();
-
-        try {
-            PlatformCallbackUtils.computeTaskReduce(envPtr, taskPtr);
-        }
-        finally {
-            leave();
-        }
-    }
-
-    /**
-     * Complete task with native error.
-     *
-     * @param taskPtr Task pointer.
-     * @param memPtr Memory pointer with exception data or {@code 0} in case of success.
-     */
-    public void computeTaskComplete(long taskPtr, long memPtr) {
-        enter();
-
-        try {
-            PlatformCallbackUtils.computeTaskComplete(envPtr, taskPtr, memPtr);
-        }
-        finally {
-            leave();
-        }
-    }
-
-    /**
-     * Serialize native job.
-     *
-     * @param jobPtr Job pointer.
-     * @param memPtr Memory pointer.
-     * @return {@code True} if serialization succeeded.
-     */
-    public int computeJobSerialize(long jobPtr, long memPtr) {
-        enter();
-
-        try {
-            return PlatformCallbackUtils.computeJobSerialize(envPtr, jobPtr, memPtr);
-        }
-        finally {
-            leave();
-        }
-    }
-
-    /**
-     * Create job in native platform.
-     *
-     * @param memPtr Memory pointer.
-     * @return Pointer to job.
-     */
-    public long computeJobCreate(long memPtr) {
-        enter();
-
-        try {
-            return PlatformCallbackUtils.computeJobCreate(envPtr, memPtr);
-        }
-        finally {
-            leave();
-        }
-    }
-
-    /**
-     * Execute native job on a node other than where it was created.
-     *
-     * @param jobPtr Job pointer.
-     * @param cancel Cancel flag.
-     * @param memPtr Memory pointer to write result to for remote job execution or {@code 0} for local job execution.
-     */
-    public void computeJobExecute(long jobPtr, int cancel, long memPtr) {
-        enter();
-
-        try {
-            PlatformCallbackUtils.computeJobExecute(envPtr, jobPtr, cancel, memPtr);
-        }
-        finally {
-            leave();
-        }
-    }
-
-    /**
-     * Cancel the job.
-     *
-     * @param jobPtr Job pointer.
-     */
-    public void computeJobCancel(long jobPtr) {
-        enter();
-
-        try {
-            PlatformCallbackUtils.computeJobCancel(envPtr, jobPtr);
-        }
-        finally {
-            leave();
-        }
-    }
-
-    /**
-     * Destroy the job.
-     *
-     * @param ptr Pointer.
-     */
-    public void computeJobDestroy(long ptr) {
-        enter();
-
-        try {
-            PlatformCallbackUtils.computeJobDestroy(envPtr, ptr);
-        }
-        finally {
-            leave();
-        }
-    }
-
-    /**
-     * Invoke local callback.
-     *
-     * @param cbPtr Callback pointer.
-     * @param memPtr Memory pointer.
-     */
-    public void continuousQueryListenerApply(long cbPtr, long memPtr) {
-        enter();
-
-        try {
-            PlatformCallbackUtils.continuousQueryListenerApply(envPtr, cbPtr, memPtr);
-        }
-        finally {
-            leave();
-        }
-    }
-
-    /**
-     * Create filter in native platform.
-     *
-     * @param memPtr Memory pointer.
-     * @return Pointer to created filter.
-     */
-    public long continuousQueryFilterCreate(long memPtr) {
-        enter();
-
-        try {
-            return PlatformCallbackUtils.continuousQueryFilterCreate(envPtr, memPtr);
-        }
-        finally {
-            leave();
-        }
-    }
-
-    /**
-     * Invoke remote filter.
-     *
-     * @param filterPtr Filter pointer.
-     * @param memPtr Memory pointer.
-     * @return Result.
-     */
-    public int continuousQueryFilterApply(long filterPtr, long memPtr) {
-        enter();
-
-        try {
-            return PlatformCallbackUtils.continuousQueryFilterApply(envPtr, filterPtr, memPtr);
-        }
-        finally {
-            leave();
-        }
-    }
-
-    /**
-     * Release remote  filter.
-     *
-     * @param filterPtr Filter pointer.
-     */
-    public void continuousQueryFilterRelease(long filterPtr) {
-        enter();
-
-        try {
-            PlatformCallbackUtils.continuousQueryFilterRelease(envPtr, filterPtr);
-        }
-        finally {
-            leave();
-        }
-    }
-
-    /**
-     * Notify native data streamer about topology update.
-     *
-     * @param ptr Data streamer native pointer.
-     * @param topVer Topology version.
-     * @param topSize Topology size.
-     */
-    public void dataStreamerTopologyUpdate(long ptr, long topVer, int topSize) {
-        enter();
-
-        try {
-            PlatformCallbackUtils.dataStreamerTopologyUpdate(envPtr, ptr, topVer, topSize);
-        }
-        finally {
-            leave();
-        }
-    }
-
-    /**
-     * Invoke stream receiver.
-     *
-     * @param ptr Receiver native pointer.
-     * @param cache Cache object.
-     * @param memPtr Stream pointer.
-     * @param keepPortable Portable flag.
-     */
-    public void dataStreamerStreamReceiverInvoke(long ptr, Object cache, long memPtr, boolean keepPortable) {
-        enter();
-
-        try {
-            PlatformCallbackUtils.dataStreamerStreamReceiverInvoke(envPtr, ptr, cache, memPtr, keepPortable);
-        }
-        finally {
-            leave();
-        }
-    }
-
-    /**
-     * Notify future with byte result.
-     *
-     * @param futPtr Future pointer.
-     * @param res Result.
-     */
-    public void futureByteResult(long futPtr, int res) {
-        enter();
-
-        try {
-            PlatformCallbackUtils.futureByteResult(envPtr, futPtr, res);
-        }
-        finally {
-            leave();
-        }
-    }
-
-    /**
-     * Notify future with boolean result.
-     *
-     * @param futPtr Future pointer.
-     * @param res Result.
-     */
-    public void futureBoolResult(long futPtr, int res) {
-        enter();
-
-        try {
-            PlatformCallbackUtils.futureBoolResult(envPtr, futPtr, res);
-        }
-        finally {
-            leave();
-        }
-    }
-
-    /**
-     * Notify future with short result.
-     *
-     * @param futPtr Future pointer.
-     * @param res Result.
-     */
-    public void futureShortResult(long futPtr, int res) {
-        enter();
-
-        try {
-            PlatformCallbackUtils.futureShortResult(envPtr, futPtr, res);
-        }
-        finally {
-            leave();
-        }
-    }
-
-    /**
-     * Notify future with byte result.
-     *
-     * @param futPtr Future pointer.
-     * @param res Result.
-     */
-    public void futureCharResult(long futPtr, int res) {
-        enter();
-
-        try {
-            PlatformCallbackUtils.futureCharResult(envPtr, futPtr, res);
-        }
-        finally {
-            leave();
-        }
-    }
-
-    /**
-     * Notify future with int result.
-     *
-     * @param futPtr Future pointer.
-     * @param res Result.
-     */
-    public void futureIntResult(long futPtr, int res) {
-        enter();
-
-        try {
-            PlatformCallbackUtils.futureIntResult(envPtr, futPtr, res);
-        }
-        finally {
-            leave();
-        }
-    }
-
-    /**
-     * Notify future with float result.
-     *
-     * @param futPtr Future pointer.
-     * @param res Result.
-     */
-    public void futureFloatResult(long futPtr, float res) {
-        enter();
-
-        try {
-            PlatformCallbackUtils.futureFloatResult(envPtr, futPtr, res);
-        }
-        finally {
-            leave();
-        }
-    }
-
-    /**
-     * Notify future with long result.
-     *
-     * @param futPtr Future pointer.
-     * @param res Result.
-     */
-    public void futureLongResult(long futPtr, long res) {
-        enter();
-
-        try {
-            PlatformCallbackUtils.futureLongResult(envPtr, futPtr, res);
-        }
-        finally {
-            leave();
-        }
-    }
-
-    /**
-     * Notify future with double result.
-     *
-     * @param futPtr Future pointer.
-     * @param res Result.
-     */
-    public void futureDoubleResult(long futPtr, double res) {
-        enter();
-
-        try {
-            PlatformCallbackUtils.futureDoubleResult(envPtr, futPtr, res);
-        }
-        finally {
-            leave();
-        }
-    }
-
-    /**
-     * Notify future with object result.
-     *
-     * @param futPtr Future pointer.
-     * @param memPtr Memory pointer.
-     */
-    public void futureObjectResult(long futPtr, long memPtr) {
-        enter();
-
-        try {
-            PlatformCallbackUtils.futureObjectResult(envPtr, futPtr, memPtr);
-        }
-        finally {
-            leave();
-        }
-    }
-
-    /**
-     * Notify future with null result.
-     *
-     * @param futPtr Future pointer.
-     */
-    public void futureNullResult(long futPtr) {
-        enter();
-
-        try {
-            PlatformCallbackUtils.futureNullResult(envPtr, futPtr);
-        }
-        finally {
-            leave();
-        }
-    }
-
-    /**
-     * Notify future with error.
-     *
-     * @param futPtr Future pointer.
-     * @param memPtr Pointer to memory with error information.
-     */
-    public void futureError(long futPtr, long memPtr) {
-        enter();
-
-        try {
-            PlatformCallbackUtils.futureError(envPtr, futPtr, memPtr);
-        }
-        finally {
-            leave();
-        }
-    }
-
-    /**
-     * Creates message filter and returns a pointer.
-     *
-     * @param memPtr Memory pointer.
-     * @return Pointer.
-     */
-    public long messagingFilterCreate(long memPtr) {
-        enter();
-
-        try {
-            return PlatformCallbackUtils.messagingFilterCreate(envPtr, memPtr);
-        }
-        finally {
-            leave();
-        }
-    }
-
-    /**
-     * @param ptr Pointer.
-     * @param memPtr Memory pointer.
-     * @return Result.
-     */
-    public int messagingFilterApply(long ptr, long memPtr) {
-        enter();
-
-        try {
-            return PlatformCallbackUtils.messagingFilterApply(envPtr, ptr, memPtr);
-        }
-        finally {
-            leave();
-        }}
-
-    /**
-     * @param ptr Pointer.
-     */
-    public void messagingFilterDestroy(long ptr) {
-        enter();
-
-        try {
-            PlatformCallbackUtils.messagingFilterDestroy(envPtr, ptr);
-        }
-        finally {
-            leave();
-        }
-    }
-
-    /**
-     * Creates event filter and returns a pointer.
-     *
-     * @param memPtr Memory pointer.
-     * @return Pointer.
-     */
-    public long eventFilterCreate(long memPtr) {
-        enter();
-
-        try {
-            return PlatformCallbackUtils.eventFilterCreate(envPtr, memPtr);
-        }
-        finally {
-            leave();
-        }
-    }
-
-    /**
-     * @param ptr Pointer.
-     * @param memPtr Memory pointer.
-     * @return Result.
-     */
-    public int eventFilterApply(long ptr, long memPtr) {
-        enter();
-
-        try {
-            return PlatformCallbackUtils.eventFilterApply(envPtr, ptr, memPtr);
-        }
-        finally {
-            leave();
-        }
-    }
-
-    /**
-     * @param ptr Pointer.
-     */
-    public void eventFilterDestroy(long ptr) {
-        enter();
-
-        try {
-            PlatformCallbackUtils.eventFilterDestroy(envPtr, ptr);
-        }
-        finally {
-            leave();
-        }
-    }
-
-    /**
-     * Sends node info to native target.
-     *
-     * @param memPtr Ptr to a stream with serialized node.
-     */
-    public void nodeInfo(long memPtr) {
-        enter();
-
-        try {
-            PlatformCallbackUtils.nodeInfo(envPtr, memPtr);
-        }
-        finally {
-            leave();
-        }
-    }
-
-    /**
-     * Kernal start callback.
-     *
-     * @param memPtr Memory pointer.
-     */
-    public void onStart(long memPtr) {
-        enter();
-
-        try {
-            PlatformCallbackUtils.onStart(envPtr, memPtr);
-        }
-        finally {
-            leave();
-        }
-    }
-
-    /**
-     * Lifecycle event callback.
-     *
-     * @param ptr Holder pointer.
-     * @param evt Event.
-     */
-    public void lifecycleEvent(long ptr, int evt) {
-        enter();
-
-        try {
-            PlatformCallbackUtils.lifecycleEvent(envPtr, ptr, evt);
-        }
-        finally {
-            leave();
-        }
-    }
-
-    /**
-     * Re-allocate external memory chunk.
-     *
-     * @param memPtr Cross-platform pointer.
-     * @param cap Capacity.
-     */
-    public void memoryReallocate(long memPtr, int cap) {
-        enter();
-
-        try {
-            PlatformCallbackUtils.memoryReallocate(envPtr, memPtr, cap);
-        }
-        finally {
-            leave();
-        }
-    }
-
-    /**
-     * Initializes native service.
-     *
-     * @param memPtr Pointer.
-     * @throws org.apache.ignite.IgniteCheckedException In case of error.
-     */
-    public long serviceInit(long memPtr) throws IgniteCheckedException {
-        return PlatformCallbackUtils.serviceInit(envPtr, memPtr);
-    }
-
-    /**
-     * Executes native service.
-     *
-     * @param svcPtr Pointer to the service in the native platform.
-     * @param memPtr Stream pointer.
-     * @throws org.apache.ignite.IgniteCheckedException In case of error.
-     */
-    public void serviceExecute(long svcPtr, long memPtr) throws IgniteCheckedException {
-        PlatformCallbackUtils.serviceExecute(envPtr, svcPtr, memPtr);
-    }
-
-    /**
-     * Cancels native service.
-     *
-     * @param svcPtr Pointer to the service in the native platform.
-     * @param memPtr Stream pointer.
-     * @throws org.apache.ignite.IgniteCheckedException In case of error.
-     */
-    public void serviceCancel(long svcPtr, long memPtr) throws IgniteCheckedException {
-        PlatformCallbackUtils.serviceCancel(envPtr, svcPtr, memPtr);
-    }
-
-    /**
-     * Invokes service method.
-     *
-     * @param svcPtr Pointer to the service in the native platform.
-     * @param outMemPtr Output memory pointer.
-     * @param inMemPtr Input memory pointer.
-     * @throws org.apache.ignite.IgniteCheckedException In case of error.
-     */
-    public void serviceInvokeMethod(long svcPtr, long outMemPtr, long inMemPtr) throws IgniteCheckedException {
-        PlatformCallbackUtils.serviceInvokeMethod(envPtr, svcPtr, outMemPtr, inMemPtr);
-    }
-
-    /**
-     * Invokes cluster node filter.
-     *
-     * @param memPtr Stream pointer.
-     */
-    public int clusterNodeFilterApply(long memPtr) {
-        return PlatformCallbackUtils.clusterNodeFilterApply(envPtr, memPtr);
-    }
-
-    /**
-     * Kernal stop callback.
-     */
-    public void onStop() {
-        block();
-
-        PlatformCallbackUtils.onStop(envPtr);
-    }
-
-    /**
-     * Enter gateway.
-     */
-    protected void enter() {
-        if (!lock.tryReadLock())
-            throw new IgniteException("Failed to execute native callback because grid is stopping.");
-    }
-
-    /**
-     * Leave gateway.
-     */
-    protected void leave() {
-        lock.readUnlock();
-    }
-
-    /**
-     * Block gateway.
-     */
-    protected void block() {
-        lock.writeLock();
-    }
-}

http://git-wip-us.apache.org/repos/asf/ignite/blob/2225f8d2/modules/platform/src/main/java/org/apache/ignite/internal/platform/callback/PlatformCallbackUtils.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/platform/callback/PlatformCallbackUtils.java b/modules/platform/src/main/java/org/apache/ignite/internal/platform/callback/PlatformCallbackUtils.java
deleted file mode 100644
index d81ce68..0000000
--- a/modules/platform/src/main/java/org/apache/ignite/internal/platform/callback/PlatformCallbackUtils.java
+++ /dev/null
@@ -1,468 +0,0 @@
-/*
- * 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.platform.callback;
-
-/**
- * Platform callback utility methods. Implemented in target platform. All methods in this class must be
- * package-visible and invoked only through {@link PlatformCallbackGateway}.
- */
-public class PlatformCallbackUtils {
-    /**
-     * Create cache store.
-     *
-     * @param envPtr Environment pointer.
-     * @param memPtr Memory pointer.
-     * @return Pointer.
-     */
-    static native long cacheStoreCreate(long envPtr, long memPtr);
-
-    /**
-     * @param envPtr Environment pointer.
-     * @param objPtr Object pointer.
-     * @param memPtr Memory pointer.
-     * @param cb Callback.
-     * @return Result.
-     */
-    static native int cacheStoreInvoke(long envPtr, long objPtr, long memPtr, Object cb);
-
-    /**
-     * @param envPtr Environment pointer.
-     * @param objPtr Object pointer.
-     */
-    static native void cacheStoreDestroy(long envPtr, long objPtr);
-
-    /**
-     * Creates cache store session.
-     *
-     * @param envPtr Environment pointer.
-     * @param storePtr Store instance pointer.
-     * @return Session instance pointer.
-     */
-    static native long cacheStoreSessionCreate(long envPtr, long storePtr);
-
-    /**
-     * Creates cache entry filter and returns a pointer.
-     *
-     * @param envPtr Environment pointer.
-     * @param memPtr Memory pointer.
-     * @return Pointer.
-     */
-    static native long cacheEntryFilterCreate(long envPtr, long memPtr);
-
-    /**
-     * @param envPtr Environment pointer.
-     * @param objPtr Pointer.
-     * @param memPtr Memory pointer.
-     * @return Result.
-     */
-    static native int cacheEntryFilterApply(long envPtr, long objPtr, long memPtr);
-
-    /**
-     * @param envPtr Environment pointer.
-     * @param objPtr Pointer.
-     */
-    static native void cacheEntryFilterDestroy(long envPtr, long objPtr);
-
-    /**
-     * Invoke cache entry processor.
-     *
-     * @param envPtr Environment pointer.
-     * @param outMemPtr Output memory pointer.
-     * @param inMemPtr Input memory pointer.
-     */
-    static native void cacheInvoke(long envPtr, long outMemPtr, long inMemPtr);
-
-    /**
-     * Perform native task map. Do not throw exceptions, serializing them to the output stream instead.
-     *
-     * @param envPtr Environment pointer.
-     * @param taskPtr Task pointer.
-     * @param outMemPtr Output memory pointer (exists if topology changed, otherwise {@code 0}).
-     * @param inMemPtr Input memory pointer.
-     */
-    static native void computeTaskMap(long envPtr, long taskPtr, long outMemPtr, long inMemPtr);
-
-    /**
-     * Perform native task job result notification.
-     *
-     * @param envPtr Environment pointer.
-     * @param taskPtr Task pointer.
-     * @param jobPtr Job pointer.
-     * @param memPtr Memory pointer (always zero for local job execution).
-     * @return Job result enum ordinal.
-     */
-    static native int computeTaskJobResult(long envPtr, long taskPtr, long jobPtr, long memPtr);
-
-    /**
-     * Perform native task reduce.
-     *
-     * @param envPtr Environment pointer.
-     * @param taskPtr Task pointer.
-     */
-    static native void computeTaskReduce(long envPtr, long taskPtr);
-
-    /**
-     * Complete task with native error.
-     *
-     * @param envPtr Environment pointer.
-     * @param taskPtr Task pointer.
-     * @param memPtr Memory pointer with exception data or {@code 0} in case of success.
-     */
-    static native void computeTaskComplete(long envPtr, long taskPtr, long memPtr);
-
-    /**
-     * Serialize native job.
-     *
-     * @param envPtr Environment pointer.
-     * @param jobPtr Job pointer.
-     * @param memPtr Memory pointer.
-     * @return {@code True} if serialization succeeded.
-     */
-    static native int computeJobSerialize(long envPtr, long jobPtr, long memPtr);
-
-    /**
-     * Create job in native platform.
-     *
-     * @param envPtr Environment pointer.
-     * @param memPtr Memory pointer.
-     * @return Pointer to job.
-     */
-    static native long computeJobCreate(long envPtr, long memPtr);
-
-    /**
-     * Execute native job on a node other than where it was created.
-     *
-     * @param envPtr Environment pointer.
-     * @param jobPtr Job pointer.
-     * @param cancel Cancel flag.
-     * @param memPtr Memory pointer to write result to for remote job execution or {@code 0} for local job execution.
-     */
-    static native void computeJobExecute(long envPtr, long jobPtr, int cancel, long memPtr);
-
-    /**
-     * Cancel the job.
-     *
-     * @param envPtr Environment pointer.
-     * @param jobPtr Job pointer.
-     */
-    static native void computeJobCancel(long envPtr, long jobPtr);
-
-    /**
-     * Destroy the job.
-     *
-     * @param envPtr Environment pointer.
-     * @param ptr Pointer.
-     */
-    static native void computeJobDestroy(long envPtr, long ptr);
-
-    /**
-     * Invoke local callback.
-     *
-     * @param envPtr Environment pointer.
-     * @param cbPtr Callback pointer.
-     * @param memPtr Memory pointer.
-     */
-    static native void continuousQueryListenerApply(long envPtr, long cbPtr, long memPtr);
-
-    /**
-     * Create filter in native platform.
-     *
-     * @param envPtr Environment pointer.
-     * @param memPtr Memory pointer.
-     * @return Pointer to created filter.
-     */
-    static native long continuousQueryFilterCreate(long envPtr, long memPtr);
-
-    /**
-     * Invoke remote filter.
-     *
-     * @param envPtr Environment pointer.
-     * @param filterPtr Filter pointer.
-     * @param memPtr Memory pointer.
-     * @return Result.
-     */
-    static native int continuousQueryFilterApply(long envPtr, long filterPtr, long memPtr);
-
-    /**
-     * Release remote  filter.
-     *
-     * @param envPtr Environment pointer.
-     * @param filterPtr Filter pointer.
-     */
-    static native void continuousQueryFilterRelease(long envPtr, long filterPtr);
-
-    /**
-     * Notify native data streamer about topology update.
-     *
-     * @param envPtr Environment pointer.
-     * @param ptr Data streamer native pointer.
-     * @param topVer Topology version.
-     * @param topSize Topology size.
-     */
-    static native void dataStreamerTopologyUpdate(long envPtr, long ptr, long topVer, int topSize);
-
-    /**
-     * Invoke stream receiver.
-     *
-     * @param envPtr Environment pointer.
-     * @param ptr Receiver native pointer.
-     * @param cache Cache object.
-     * @param memPtr Stream pointer.
-     * @param keepPortable Portable flag.
-     */
-    static native void dataStreamerStreamReceiverInvoke(long envPtr, long ptr, Object cache, long memPtr,
-        boolean keepPortable);
-
-    /**
-     * Notify future with byte result.
-     *
-     * @param envPtr Environment pointer.
-     * @param futPtr Future pointer.
-     * @param res Result.
-     */
-    static native void futureByteResult(long envPtr, long futPtr, int res);
-
-    /**
-     * Notify future with boolean result.
-     *
-     * @param envPtr Environment pointer.
-     * @param futPtr Future pointer.
-     * @param res Result.
-     */
-    static native void futureBoolResult(long envPtr, long futPtr, int res);
-
-    /**
-     * Notify future with short result.
-     *
-     * @param envPtr Environment pointer.
-     * @param futPtr Future pointer.
-     * @param res Result.
-     */
-    static native void futureShortResult(long envPtr, long futPtr, int res);
-
-    /**
-     * Notify future with byte result.
-     *
-     * @param envPtr Environment pointer.
-     * @param futPtr Future pointer.
-     * @param res Result.
-     */
-    static native void futureCharResult(long envPtr, long futPtr, int res);
-
-    /**
-     * Notify future with int result.
-     *
-     * @param envPtr Environment pointer.
-     * @param futPtr Future pointer.
-     * @param res Result.
-     */
-    static native void futureIntResult(long envPtr, long futPtr, int res);
-
-    /**
-     * Notify future with float result.
-     *
-     * @param envPtr Environment pointer.
-     * @param futPtr Future pointer.
-     * @param res Result.
-     */
-    static native void futureFloatResult(long envPtr, long futPtr, float res);
-
-    /**
-     * Notify future with long result.
-     *
-     * @param envPtr Environment pointer.
-     * @param futPtr Future pointer.
-     * @param res Result.
-     */
-    static native void futureLongResult(long envPtr, long futPtr, long res);
-
-    /**
-     * Notify future with double result.
-     *
-     * @param envPtr Environment pointer.
-     * @param futPtr Future pointer.
-     * @param res Result.
-     */
-    static native void futureDoubleResult(long envPtr, long futPtr, double res);
-
-    /**
-     * Notify future with object result.
-     *
-     * @param envPtr Environment pointer.
-     * @param futPtr Future pointer.
-     * @param memPtr Memory pointer.
-     */
-    static native void futureObjectResult(long envPtr, long futPtr, long memPtr);
-
-    /**
-     * Notify future with null result.
-     *
-     * @param envPtr Environment pointer.
-     * @param futPtr Future pointer.
-     */
-    static native void futureNullResult(long envPtr, long futPtr);
-
-    /**
-     * Notify future with error.
-     *
-     * @param envPtr Environment pointer.
-     * @param futPtr Future pointer.
-     * @param memPtr Pointer to memory with error information.
-     */
-    static native void futureError(long envPtr, long futPtr, long memPtr);
-
-    /**
-     * Creates message filter and returns a pointer.
-     *
-     * @param envPtr Environment pointer.
-     * @param memPtr Memory pointer.
-     * @return Pointer.
-     */
-    static native long messagingFilterCreate(long envPtr, long memPtr);
-
-    /**
-     * @param envPtr Environment pointer.
-     * @param objPtr Pointer.
-     * @param memPtr Memory pointer.
-     * @return Result.
-     */
-    static native int messagingFilterApply(long envPtr, long objPtr, long memPtr);
-
-    /**
-     * @param envPtr Environment pointer.
-     * @param objPtr Pointer.
-     */
-    static native void messagingFilterDestroy(long envPtr, long objPtr);
-
-    /**
-     * Creates event filter and returns a pointer.
-     *
-     * @param envPtr Environment pointer.
-     * @param memPtr Memory pointer.
-     * @return Pointer.
-     */
-    static native long eventFilterCreate(long envPtr, long memPtr);
-
-    /**
-     * @param envPtr Environment pointer.
-     * @param objPtr Pointer.
-     * @param memPtr Memory pointer.
-     * @return Result.
-     */
-    static native int eventFilterApply(long envPtr, long objPtr, long memPtr);
-
-    /**
-     * @param envPtr Environment pointer.
-     * @param objPtr Pointer.
-     */
-    static native void eventFilterDestroy(long envPtr, long objPtr);
-
-    /**
-     * Sends node info to native target.
-     *
-     * @param envPtr Environment pointer.
-     * @param memPtr Ptr to a stream with serialized node.
-     */
-    static native void nodeInfo(long envPtr, long memPtr);
-
-    /**
-     * Kernal start callback.
-     *
-     * @param envPtr Environment pointer.
-     * @param memPtr Memory pointer.
-     */
-    static native void onStart(long envPtr, long memPtr);
-
-    /*
-     * Kernal stop callback.
-     *
-     * @param envPtr Environment pointer.
-     */
-    static native void onStop(long envPtr);
-
-    /**
-     * Lifecycle event callback.
-     *
-     * @param envPtr Environment pointer.
-     * @param ptr Holder pointer.
-     * @param evt Event.
-     */
-    static native void lifecycleEvent(long envPtr, long ptr, int evt);
-
-    /**
-     * Re-allocate external memory chunk.
-     *
-     * @param envPtr Environment pointer.
-     * @param memPtr Cross-platform pointer.
-     * @param cap Capacity.
-     */
-    static native void memoryReallocate(long envPtr, long memPtr, int cap);
-
-    /**
-     * Initializes native service.
-     *
-     * @param envPtr Environment pointer.
-     * @param memPtr Stream pointer.
-     * @return Pointer to the native platform service.
-     */
-    static native long serviceInit(long envPtr, long memPtr);
-
-    /**
-     * Executes native service.
-     *
-     * @param envPtr Environment pointer.
-     * @param svcPtr Pointer to the service in the native platform.
-     * @param memPtr Stream pointer.
-     */
-    static native void serviceExecute(long envPtr, long svcPtr, long memPtr);
-
-    /**
-     * Cancels native service.
-     *
-     * @param envPtr Environment pointer.
-     * @param svcPtr Pointer to the service in the native platform.
-     * @param memPtr Stream pointer.
-     */
-    static native void serviceCancel(long envPtr, long svcPtr, long memPtr);
-
-    /**
-     /**
-     * Invokes service method.
-     *
-     * @param envPtr Environment pointer.
-     * @param svcPtr Pointer to the service in the native platform.
-     * @param outMemPtr Output memory pointer.
-     * @param inMemPtr Input memory pointer.
-     */
-    static native void serviceInvokeMethod(long envPtr, long svcPtr, long outMemPtr, long inMemPtr);
-
-    /**
-     * Invokes cluster node filter.
-     *
-     * @param envPtr Environment pointer.
-     * @param memPtr Stream pointer.
-     */
-    static native int clusterNodeFilterApply(long envPtr, long memPtr);
-
-    /**
-     * Private constructor.
-     */
-    private PlatformCallbackUtils() {
-        // No-op.
-    }
-}

http://git-wip-us.apache.org/repos/asf/ignite/blob/2225f8d2/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformAbstractMemory.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformAbstractMemory.java b/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformAbstractMemory.java
deleted file mode 100644
index cf4c02a..0000000
--- a/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformAbstractMemory.java
+++ /dev/null
@@ -1,121 +0,0 @@
-/*
- * 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.platform.memory;
-
-/**
- * Interop memory chunk abstraction.
- */
-public abstract class PlatformAbstractMemory implements PlatformMemory {
-    /** Stream factory. */
-    private static final StreamFactory STREAM_FACTORY = PlatformMemoryUtils.LITTLE_ENDIAN ?
-        new LittleEndianStreamFactory() : new BigEndianStreamFactory();
-
-    /** Cross-platform memory pointer. */
-    protected long memPtr;
-
-    /**
-     * Constructor.
-     *
-     * @param memPtr Cross-platform memory pointer.
-     */
-    protected PlatformAbstractMemory(long memPtr) {
-        this.memPtr = memPtr;
-    }
-
-    /** {@inheritDoc} */
-    @Override public PlatformInputStream input() {
-        return STREAM_FACTORY.createInput(this);
-    }
-
-    /** {@inheritDoc} */
-    @Override public PlatformOutputStream output() {
-        return STREAM_FACTORY.createOutput(this);
-    }
-
-    /** {@inheritDoc} */
-    @Override public long pointer() {
-        return memPtr;
-    }
-
-    /** {@inheritDoc} */
-    @Override public long data() {
-        return PlatformMemoryUtils.data(memPtr);
-    }
-
-    /** {@inheritDoc} */
-    @Override public int capacity() {
-        return PlatformMemoryUtils.capacity(memPtr);
-    }
-
-    /** {@inheritDoc} */
-    @Override public int length() {
-        return PlatformMemoryUtils.length(memPtr);
-    }
-
-    /**
-     * Stream factory.
-     */
-    private static interface StreamFactory {
-        /**
-         * Create input stream.
-         *
-         * @param mem Memory.
-         * @return Input stream.
-         */
-        PlatformInputStreamImpl createInput(PlatformMemory mem);
-
-        /**
-         * Create output stream.
-         *
-         * @param mem Memory.
-         * @return Output stream.
-         */
-        PlatformOutputStreamImpl createOutput(PlatformMemory mem);
-    }
-
-    /**
-     * Stream factory for LITTLE ENDIAN architecture.
-     */
-    private static class LittleEndianStreamFactory implements StreamFactory {
-        /** {@inheritDoc} */
-        @Override public PlatformInputStreamImpl createInput(PlatformMemory mem) {
-            return new PlatformInputStreamImpl(mem);
-        }
-
-        /** {@inheritDoc} */
-        @Override public PlatformOutputStreamImpl createOutput(PlatformMemory mem) {
-            return new PlatformOutputStreamImpl(mem);
-        }
-    }
-
-    /**
-     * Stream factory for BIG ENDIAN architecture.
-     */
-    private static class BigEndianStreamFactory implements StreamFactory {
-        /** {@inheritDoc} */
-        @Override public PlatformInputStreamImpl createInput(PlatformMemory mem) {
-            return new PlatformBigEndianInputStreamImpl(mem);
-        }
-
-        /** {@inheritDoc} */
-        @Override public PlatformOutputStreamImpl createOutput(PlatformMemory mem) {
-            return new PlatformBigEndianOutputStreamImpl(mem);
-        }
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/ignite/blob/2225f8d2/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformBigEndianInputStreamImpl.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformBigEndianInputStreamImpl.java b/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformBigEndianInputStreamImpl.java
deleted file mode 100644
index fbf7f8e..0000000
--- a/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformBigEndianInputStreamImpl.java
+++ /dev/null
@@ -1,126 +0,0 @@
-/*
- * 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.platform.memory;
-
-/**
- * Interop input stream implementation working with BIG ENDIAN architecture.
- */
-public class PlatformBigEndianInputStreamImpl extends PlatformInputStreamImpl {
-    /**
-     * Constructor.
-     *
-     * @param mem Memory chunk.
-     */
-    public PlatformBigEndianInputStreamImpl(PlatformMemory mem) {
-        super(mem);
-    }
-
-    /** {@inheritDoc} */
-    @Override public short readShort() {
-        return Short.reverseBytes(super.readShort());
-    }
-
-    /** {@inheritDoc} */
-    @Override public short[] readShortArray(int cnt) {
-        short[] res = super.readShortArray(cnt);
-
-        for (int i = 0; i < cnt; i++)
-            res[i] = Short.reverseBytes(res[i]);
-
-        return res;
-    }
-
-    /** {@inheritDoc} */
-    @Override public char readChar() {
-        return Character.reverseBytes(super.readChar());
-    }
-
-    /** {@inheritDoc} */
-    @Override public char[] readCharArray(int cnt) {
-        char[] res = super.readCharArray(cnt);
-
-        for (int i = 0; i < cnt; i++)
-            res[i] = Character.reverseBytes(res[i]);
-
-        return res;
-    }
-
-    /** {@inheritDoc} */
-    @Override public int readInt() {
-        return Integer.reverseBytes(super.readInt());
-    }
-
-    /** {@inheritDoc} */
-    @Override public int readInt(int pos) {
-        return Integer.reverseBytes(super.readInt(pos));
-    }
-
-    /** {@inheritDoc} */
-    @Override public int[] readIntArray(int cnt) {
-        int[] res = super.readIntArray(cnt);
-
-        for (int i = 0; i < cnt; i++)
-            res[i] = Integer.reverseBytes(res[i]);
-
-        return res;
-    }
-
-    /** {@inheritDoc} */
-    @Override public float readFloat() {
-        return Float.intBitsToFloat(Integer.reverseBytes(Float.floatToIntBits(super.readFloat())));
-    }
-
-    /** {@inheritDoc} */
-    @Override public float[] readFloatArray(int cnt) {
-        float[] res = super.readFloatArray(cnt);
-
-        for (int i = 0; i < cnt; i++)
-            res[i] = Float.intBitsToFloat(Integer.reverseBytes(Float.floatToIntBits(res[i])));
-
-        return res;
-    }
-
-    /** {@inheritDoc} */
-    @Override public long readLong() {
-        return Long.reverseBytes(super.readLong());
-    }
-
-    /** {@inheritDoc} */
-    @Override public long[] readLongArray(int cnt) {
-        long[] res = super.readLongArray(cnt);
-
-        for (int i = 0; i < cnt; i++)
-            res[i] = Long.reverseBytes(res[i]);
-
-        return res;
-    }
-
-    /** {@inheritDoc} */
-    @Override public double readDouble() {
-        return Double.longBitsToDouble(Long.reverseBytes(Double.doubleToLongBits(super.readDouble())));
-    }
-
-    /** {@inheritDoc} */
-    @Override public double[] readDoubleArray(int cnt) {
-        double[] res = super.readDoubleArray(cnt);
-
-        for (int i = 0; i < cnt; i++)
-            res[i] = Double.longBitsToDouble(Long.reverseBytes(Double.doubleToLongBits(res[i])));
-
-        return res;
-    }
-}

http://git-wip-us.apache.org/repos/asf/ignite/blob/2225f8d2/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformBigEndianOutputStreamImpl.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformBigEndianOutputStreamImpl.java b/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformBigEndianOutputStreamImpl.java
deleted file mode 100644
index 144e5dc..0000000
--- a/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformBigEndianOutputStreamImpl.java
+++ /dev/null
@@ -1,162 +0,0 @@
-/*
- * 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.platform.memory;
-
-import static org.apache.ignite.internal.platform.memory.PlatformMemoryUtils.*;
-
-/**
- * Interop output stream implementation working with BIG ENDIAN architecture.
- */
-public class PlatformBigEndianOutputStreamImpl extends PlatformOutputStreamImpl {
-    /**
-     * Constructor.
-     *
-     * @param mem Underlying memory chunk.
-     */
-    public PlatformBigEndianOutputStreamImpl(PlatformMemory mem) {
-        super(mem);
-    }
-
-    /** {@inheritDoc} */
-    @Override public void writeShort(short val) {
-        super.writeShort(Short.reverseBytes(val));
-    }
-
-    /** {@inheritDoc} */
-    @Override public void writeShortArray(short[] val) {
-        int cnt = val.length << 1;
-
-        ensureCapacity(pos + cnt);
-
-        long startPos = data + pos;
-
-        for (short item : val) {
-            UNSAFE.putShort(startPos, Short.reverseBytes(item));
-
-            startPos += 2;
-        }
-
-        shift(cnt);
-    }
-
-    /** {@inheritDoc} */
-    @Override public void writeChar(char val) {
-        super.writeChar(Character.reverseBytes(val));
-    }
-
-    /** {@inheritDoc} */
-    @Override public void writeCharArray(char[] val) {
-        int cnt = val.length << 1;
-
-        ensureCapacity(pos + cnt);
-
-        long startPos = data + pos;
-
-        for (char item : val) {
-            UNSAFE.putChar(startPos, Character.reverseBytes(item));
-
-            startPos += 2;
-        }
-
-        shift(cnt);
-    }
-
-    /** {@inheritDoc} */
-    @Override public void writeInt(int val) {
-        super.writeInt(Integer.reverseBytes(val));
-    }
-
-    /** {@inheritDoc} */
-    @Override public void writeIntArray(int[] val) {
-        int cnt = val.length << 2;
-
-        ensureCapacity(pos + cnt);
-
-        long startPos = data + pos;
-
-        for (int item : val) {
-            UNSAFE.putInt(startPos, Integer.reverseBytes(item));
-
-            startPos += 4;
-        }
-
-        shift(cnt);
-    }
-
-    /** {@inheritDoc} */
-    @Override public void writeInt(int pos, int val) {
-        super.writeInt(pos, Integer.reverseBytes(val));
-    }
-
-    /** {@inheritDoc} */
-    @Override public void writeFloatArray(float[] val) {
-        int cnt = val.length << 2;
-
-        ensureCapacity(pos + cnt);
-
-        long startPos = data + pos;
-
-        for (float item : val) {
-            UNSAFE.putInt(startPos, Integer.reverseBytes(Float.floatToIntBits(item)));
-
-            startPos += 4;
-        }
-
-        shift(cnt);
-    }
-
-    /** {@inheritDoc} */
-    @Override public void writeLong(long val) {
-        super.writeLong(Long.reverseBytes(val));
-    }
-
-    /** {@inheritDoc} */
-    @Override public void writeLongArray(long[] val) {
-        int cnt = val.length << 3;
-
-        ensureCapacity(pos + cnt);
-
-        long startPos = data + pos;
-
-        for (long item : val) {
-            UNSAFE.putLong(startPos, Long.reverseBytes(item));
-
-            startPos += 8;
-        }
-
-        shift(cnt);
-    }
-
-    /** {@inheritDoc} */
-    @Override public void writeDoubleArray(double[] val) {
-        int cnt = val.length << 3;
-
-        ensureCapacity(pos + cnt);
-
-        long startPos = data + pos;
-
-        for (double item : val) {
-            UNSAFE.putLong(startPos, Long.reverseBytes(Double.doubleToLongBits(item)));
-
-            startPos += 8;
-        }
-
-        shift(cnt);
-    }
-}
-

http://git-wip-us.apache.org/repos/asf/ignite/blob/2225f8d2/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformExternalMemory.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformExternalMemory.java b/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformExternalMemory.java
deleted file mode 100644
index e04779d..0000000
--- a/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformExternalMemory.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * 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.platform.memory;
-
-import org.apache.ignite.*;
-import org.apache.ignite.internal.platform.callback.*;
-import org.jetbrains.annotations.*;
-
-/**
- * Interop external memory chunk.
- */
-public class PlatformExternalMemory extends PlatformAbstractMemory {
-    /** Native gateway. */
-    private final PlatformCallbackGateway gate;
-
-    /**
-     * Constructor.
-     *
-     * @param gate Native gateway.
-     * @param memPtr Memory pointer.
-     */
-    public PlatformExternalMemory(@Nullable PlatformCallbackGateway gate, long memPtr) {
-        super(memPtr);
-
-        this.gate = gate;
-    }
-
-    /** {@inheritDoc} */
-    @Override public void reallocate(int cap) {
-        if (gate == null)
-            throw new IgniteException("Failed to re-allocate external memory chunk because it is read-only.");
-
-        gate.memoryReallocate(memPtr, cap);
-    }
-
-    /** {@inheritDoc} */
-    @Override public void close() {
-        // Do nothing, memory must be released by native platform.
-    }
-}

http://git-wip-us.apache.org/repos/asf/ignite/blob/2225f8d2/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformInputStream.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformInputStream.java b/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformInputStream.java
deleted file mode 100644
index 6d0d107..0000000
--- a/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformInputStream.java
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * 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.platform.memory;
-
-import org.apache.ignite.internal.portable.streams.*;
-
-/**
- * Interop output stream,
- */
-public interface PlatformInputStream extends PortableInputStream {
-    /**
-     * Synchronize input. Must be called before start reading data from a memory changed by another platform.
-     */
-    public void synchronize();
-}

http://git-wip-us.apache.org/repos/asf/ignite/blob/2225f8d2/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformInputStreamImpl.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformInputStreamImpl.java b/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformInputStreamImpl.java
deleted file mode 100644
index e741c9e..0000000
--- a/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformInputStreamImpl.java
+++ /dev/null
@@ -1,323 +0,0 @@
-/*
- * 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.platform.memory;
-
-import org.apache.ignite.*;
-
-import static org.apache.ignite.internal.platform.memory.PlatformMemoryUtils.*;
-
-/**
- * Interop input stream implementation.
- */
-public class PlatformInputStreamImpl implements PlatformInputStream {
-    /** Underlying memory. */
-    private final PlatformMemory mem;
-
-    /** Real data pointer */
-    private long data;
-
-    /** Amount of available data. */
-    private int len;
-
-    /** Current position. */
-    private int pos;
-
-    /** Heap-copied data. */
-    private byte[] dataCopy;
-
-    /**
-     * Constructor.
-     *
-     * @param mem Underlying memory chunk.
-     */
-    public PlatformInputStreamImpl(PlatformMemory mem) {
-        this.mem = mem;
-
-        data = mem.data();
-        len = mem.length();
-    }
-
-    /** {@inheritDoc} */
-    @Override public byte readByte() {
-        ensureEnoughData(1);
-
-        return UNSAFE.getByte(data + pos++);
-    }
-
-    /** {@inheritDoc} */
-    @Override public byte[] readByteArray(int cnt) {
-        byte[] res = new byte[cnt];
-
-        copyAndShift(res, BYTE_ARR_OFF, cnt);
-
-        return res;
-    }
-
-    /** {@inheritDoc} */
-    @Override public boolean readBoolean() {
-        return readByte() == 1;
-    }
-
-    /** {@inheritDoc} */
-    @Override public boolean[] readBooleanArray(int cnt) {
-        boolean[] res = new boolean[cnt];
-
-        copyAndShift(res, BOOLEAN_ARR_OFF, cnt);
-
-        return res;
-    }
-
-    /** {@inheritDoc} */
-    @Override public short readShort() {
-        ensureEnoughData(2);
-
-        short res = UNSAFE.getShort(data + pos);
-
-        shift(2);
-
-        return res;
-    }
-
-    /** {@inheritDoc} */
-    @Override public short[] readShortArray(int cnt) {
-        int len = cnt << 1;
-
-        short[] res = new short[cnt];
-
-        copyAndShift(res, SHORT_ARR_OFF, len);
-
-        return res;
-    }
-
-    /** {@inheritDoc} */
-    @Override public char readChar() {
-        ensureEnoughData(2);
-
-        char res = UNSAFE.getChar(data + pos);
-
-        shift(2);
-
-        return res;
-    }
-
-    /** {@inheritDoc} */
-    @Override public char[] readCharArray(int cnt) {
-        int len = cnt << 1;
-
-        char[] res = new char[cnt];
-
-        copyAndShift(res, CHAR_ARR_OFF, len);
-
-        return res;
-    }
-
-    /** {@inheritDoc} */
-    @Override public int readInt() {
-        ensureEnoughData(4);
-
-        int res = UNSAFE.getInt(data + pos);
-
-        shift(4);
-
-        return res;
-    }
-
-    /** {@inheritDoc} */
-    @Override public int readInt(int pos) {
-        int delta = pos + 4 - this.pos;
-
-        if (delta > 0)
-            ensureEnoughData(delta);
-
-        return UNSAFE.getInt(data + pos);
-    }
-
-    /** {@inheritDoc} */
-    @Override public int[] readIntArray(int cnt) {
-        int len = cnt << 2;
-
-        int[] res = new int[cnt];
-
-        copyAndShift(res, INT_ARR_OFF, len);
-
-        return res;
-    }
-
-    /** {@inheritDoc} */
-    @Override public float readFloat() {
-        ensureEnoughData(4);
-
-        float res = UNSAFE.getFloat(data + pos);
-
-        shift(4);
-
-        return res;
-    }
-
-    /** {@inheritDoc} */
-    @Override public float[] readFloatArray(int cnt) {
-        int len = cnt << 2;
-
-        float[] res = new float[cnt];
-
-        copyAndShift(res, FLOAT_ARR_OFF, len);
-
-        return res;
-    }
-
-    /** {@inheritDoc} */
-    @Override public long readLong() {
-        ensureEnoughData(8);
-
-        long res = UNSAFE.getLong(data + pos);
-
-        shift(8);
-
-        return res;
-    }
-
-    /** {@inheritDoc} */
-    @Override public long[] readLongArray(int cnt) {
-        int len = cnt << 3;
-
-        long[] res = new long[cnt];
-
-        copyAndShift(res, LONG_ARR_OFF, len);
-
-        return res;
-    }
-
-    /** {@inheritDoc} */
-    @Override public double readDouble() {
-        ensureEnoughData(8);
-
-        double res = UNSAFE.getDouble(data + pos);
-
-        shift(8);
-
-        return res;
-    }
-
-    /** {@inheritDoc} */
-    @Override public double[] readDoubleArray(int cnt) {
-        int len = cnt << 3;
-
-        double[] res = new double[cnt];
-
-        copyAndShift(res, DOUBLE_ARR_OFF, len);
-
-        return res;
-    }
-
-    /** {@inheritDoc} */
-    @Override public int read(byte[] arr, int off, int len) {
-        if (len > remaining())
-            len = remaining();
-
-        copyAndShift(arr, BYTE_ARR_OFF + off, len);
-
-        return len;
-    }
-
-    /** {@inheritDoc} */
-    @Override public int remaining() {
-        return len - pos;
-    }
-
-    /** {@inheritDoc} */
-    @Override public int position() {
-        return pos;
-    }
-
-    /** {@inheritDoc} */
-    @Override public void position(int pos) {
-        if (pos > len)
-            throw new IgniteException("Position is out of bounds: " + pos);
-        else
-            this.pos = pos;
-    }
-
-    /** {@inheritDoc} */
-    @Override public byte[] array() {
-        return arrayCopy();
-    }
-
-    /** {@inheritDoc} */
-    @Override public byte[] arrayCopy() {
-        if (dataCopy == null) {
-            dataCopy = new byte[len];
-
-            UNSAFE.copyMemory(null, data, dataCopy, BYTE_ARR_OFF, dataCopy.length);
-        }
-
-        return dataCopy;
-    }
-
-    /** {@inheritDoc} */
-    @Override public long offheapPointer() {
-        return 0;
-    }
-
-    /** {@inheritDoc} */
-    @Override public boolean hasArray() {
-        return false;
-    }
-
-    /** {@inheritDoc} */
-    @Override public void synchronize() {
-        data = mem.data();
-        len = mem.length();
-    }
-
-    /**
-     * Ensure there is enough data in the stream.
-     *
-     * @param cnt Amount of byte expected to be available.
-     */
-    private void ensureEnoughData(int cnt) {
-        if (remaining() < cnt)
-            throw new IgniteException("Not enough data to read the value [position=" + pos +
-                ", requiredBytes=" + cnt + ", remainingBytes=" + remaining() + ']');
-    }
-
-    /**
-     * Copy required amount of data and shift position.
-     *
-     * @param target Target to copy data to.
-     * @param off Offset.
-     * @param cnt Count.
-     */
-    private void copyAndShift(Object target, long off, int cnt) {
-        ensureEnoughData(cnt);
-
-        UNSAFE.copyMemory(null, data + pos, target, off, cnt);
-
-        shift(cnt);
-    }
-
-    /**
-     * Shift position to the right.
-     *
-     * @param cnt Amount of bytes.
-     */
-    private void shift(int cnt) {
-        pos += cnt;
-
-        assert pos <= len;
-    }
-}

http://git-wip-us.apache.org/repos/asf/ignite/blob/2225f8d2/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformMemory.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformMemory.java b/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformMemory.java
deleted file mode 100644
index 648827a..0000000
--- a/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformMemory.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * 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.platform.memory;
-
-/**
- * Interop memory chunk.
- */
-public interface PlatformMemory extends AutoCloseable {
-    /**
-     * Gets input stream.
-     *
-     * @return Input stream.
-     */
-    public PlatformInputStream input();
-
-    /**
-     * Gets output stream.
-     *
-     * @return Output stream.
-     */
-    public PlatformOutputStream output();
-
-    /**
-     * Gets pointer which can be passed between platforms.
-     *
-     * @return Pointer.
-     */
-    public long pointer();
-
-    /**
-     * Gets data pointer.
-     *
-     * @return Data pointer.
-     */
-    public long data();
-
-    /**
-     * Gets capacity.
-     *
-     * @return Capacity.
-     */
-    public int capacity();
-
-    /**
-     * Gets length.
-     *
-     * @return Length.
-     */
-    public int length();
-
-    /**
-     * Reallocate memory chunk.
-     *
-     * @param cap Minimum capacity.
-     */
-    public void reallocate(int cap);
-
-    /**
-     * Close memory releasing it.
-     */
-    @Override void close();
-}

http://git-wip-us.apache.org/repos/asf/ignite/blob/2225f8d2/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformMemoryManager.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformMemoryManager.java b/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformMemoryManager.java
deleted file mode 100644
index 73ec915..0000000
--- a/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformMemoryManager.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * 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.platform.memory;
-
-/**
- * Interop memory manager interface.
- */
-public interface PlatformMemoryManager {
-    /**
-     * Allocates memory.
-     *
-     * @return Memory.
-     */
-    public PlatformMemory allocate();
-
-    /**
-     * Allocates memory having at least the given capacity.
-     *
-     * @param cap Minimum capacity.
-     * @return Memory.
-     */
-    public PlatformMemory allocate(int cap);
-
-    /**
-     * Gets memory from existing pointer.
-     *
-     * @param memPtr Cross-platform memory pointer.
-     * @return Memory.
-     */
-    public PlatformMemory get(long memPtr);
-}


[38/59] [abbrv] ignite git commit: Fix to RAT.

Posted by vk...@apache.org.
Fix to RAT.


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

Branch: refs/heads/ignite-884
Commit: ed974f3f74dd66cb73645cafcc091f7793b5461d
Parents: 4f3c9a2
Author: vozerov-gridgain <vo...@gridgain.com>
Authored: Wed Aug 26 11:12:11 2015 +0300
Committer: vozerov-gridgain <vo...@gridgain.com>
Committed: Wed Aug 26 11:12:11 2015 +0300

----------------------------------------------------------------------
 parent/pom.xml | 1 +
 1 file changed, 1 insertion(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/ed974f3f/parent/pom.xml
----------------------------------------------------------------------
diff --git a/parent/pom.xml b/parent/pom.xml
index 17fcea7..8d25cf2 100644
--- a/parent/pom.xml
+++ b/parent/pom.xml
@@ -736,6 +736,7 @@
                                         <!--platform-->
                                         <exclude>src/main/dotnet/Apache.Ignite.Core/Apache.Ignite.Core.csproj</exclude>
                                         <exclude>src/main/dotnet/Apache.Ignite.sln</exclude>
+                                        <exclude>src/main/dotnet/Apache.Ignite.sln.DotSettings</exclude>
                                         <exclude>src/test/dotnet/Apache.Ignite.Core.Tests/Apache.Ignite.Core.Tests.csproj</exclude>
                                     </excludes>
                                 </configuration>


[08/59] [abbrv] ignite git commit: ignite-1258: portable objects API support in Ignite

Posted by vk...@apache.org.
http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/internal/portable/streams/PortableHeapInputStream.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/portable/streams/PortableHeapInputStream.java b/modules/core/src/main/java/org/apache/ignite/internal/portable/streams/PortableHeapInputStream.java
new file mode 100644
index 0000000..3baa6a5
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/streams/PortableHeapInputStream.java
@@ -0,0 +1,134 @@
+/*
+ * 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.portable.streams;
+
+import java.util.*;
+
+/**
+ * Portable off-heap input stream.
+ */
+public final class PortableHeapInputStream extends PortableAbstractInputStream {
+    /** Data. */
+    private byte[] data;
+
+    /**
+     * Constructor.
+     *
+     * @param data Data.
+     */
+    public PortableHeapInputStream(byte[] data) {
+        this.data = data;
+
+        len = data.length;
+    }
+
+    /**
+     * @return Copy of this stream.
+     */
+    public PortableHeapInputStream copy() {
+        PortableHeapInputStream in = new PortableHeapInputStream(Arrays.copyOf(data, data.length));
+
+        in.position(pos);
+
+        return in;
+    }
+
+    /**
+     * Method called from JNI to resize stream.
+     *
+     * @param len Required length.
+     * @return Underlying byte array.
+     */
+    public byte[] resize(int len) {
+        if (data.length < len) {
+            byte[] data0 = new byte[len];
+
+            UNSAFE.copyMemory(data, BYTE_ARR_OFF, data0, BYTE_ARR_OFF, data.length);
+
+            data = data0;
+        }
+
+        return data;
+    }
+
+    /** {@inheritDoc} */
+    @Override public int remaining() {
+        return data.length - pos;
+    }
+
+    /** {@inheritDoc} */
+    @Override public byte[] array() {
+        return data;
+    }
+
+    /** {@inheritDoc} */
+    @Override public byte[] arrayCopy() {
+        byte[] res = new byte[len];
+
+        UNSAFE.copyMemory(data, BYTE_ARR_OFF, res, BYTE_ARR_OFF, res.length);
+
+        return res;
+    }
+
+    /** {@inheritDoc} */
+    @Override public boolean hasArray() {
+        return true;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected byte readByteAndShift() {
+        return data[pos++];
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void copyAndShift(Object target, long off, int len) {
+        UNSAFE.copyMemory(data, BYTE_ARR_OFF + pos, target, off, len);
+
+        shift(len);
+    }
+
+    /** {@inheritDoc} */
+    @Override protected short readShortFast() {
+        return UNSAFE.getShort(data, BYTE_ARR_OFF + pos);
+    }
+
+    /** {@inheritDoc} */
+    @Override protected char readCharFast() {
+        return UNSAFE.getChar(data, BYTE_ARR_OFF + pos);
+    }
+
+    /** {@inheritDoc} */
+    @Override protected int readIntFast() {
+        return UNSAFE.getInt(data, BYTE_ARR_OFF + pos);
+    }
+
+    /** {@inheritDoc} */
+    @Override protected long readLongFast() {
+        return UNSAFE.getLong(data, BYTE_ARR_OFF + pos);
+    }
+
+    /** {@inheritDoc} */
+    @Override protected int readIntPositioned(int pos) {
+        int res = UNSAFE.getInt(data, BYTE_ARR_OFF + pos);
+
+        if (!LITTLE_ENDIAN)
+            res = Integer.reverseBytes(res);
+
+        return res;
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/internal/portable/streams/PortableHeapOutputStream.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/portable/streams/PortableHeapOutputStream.java b/modules/core/src/main/java/org/apache/ignite/internal/portable/streams/PortableHeapOutputStream.java
new file mode 100644
index 0000000..f492449
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/streams/PortableHeapOutputStream.java
@@ -0,0 +1,155 @@
+/*
+ * 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.portable.streams;
+
+import static org.apache.ignite.internal.portable.PortableThreadLocalMemoryAllocator.*;
+
+/**
+ * Portable heap output stream.
+ */
+public final class PortableHeapOutputStream extends PortableAbstractOutputStream {
+    /** Default capacity. */
+    private static final int DFLT_CAP = 1024;
+
+    /** Allocator. */
+    private final PortableMemoryAllocator alloc;
+
+    /** Data. */
+    private byte[] data;
+
+    /**
+     * Constructor.
+     */
+    public PortableHeapOutputStream() {
+        this(DFLT_CAP, DFLT_ALLOC);
+    }
+
+    /**
+     * Constructor.
+     *
+     * @param cap Initial capacity.
+     */
+    public PortableHeapOutputStream(int cap) {
+        this(cap, THREAD_LOCAL_ALLOC);
+    }
+
+    /**
+     * Constructor.
+     *
+     * @param cap Initial capacity.
+     * @param alloc Allocator.
+     */
+    public PortableHeapOutputStream(int cap, PortableMemoryAllocator alloc) {
+        data = alloc.allocate(cap);
+
+        this.alloc = alloc;
+    }
+
+    /**
+     * Constructor.
+     *
+     * @param data Data.
+     */
+    public PortableHeapOutputStream(byte[] data) {
+        this(data, DFLT_ALLOC);
+    }
+
+    /**
+     * Constructor.
+     *
+     * @param data Data.
+     * @param alloc Allocator.
+     */
+    public PortableHeapOutputStream(byte[] data, PortableMemoryAllocator alloc) {
+        this.data = data;
+        this.alloc = alloc;
+    }
+
+    /** {@inheritDoc} */
+    @Override public void close() {
+        alloc.release(data, pos);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void ensureCapacity(int cnt) {
+        if (cnt > data.length) {
+            int newCap = capacity(data.length, cnt);
+
+            data = alloc.reallocate(data, newCap);
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override public byte[] array() {
+        return data;
+    }
+
+    /** {@inheritDoc} */
+    @Override public byte[] arrayCopy() {
+        byte[] res = new byte[pos];
+
+        UNSAFE.copyMemory(data, BYTE_ARR_OFF, res, BYTE_ARR_OFF, pos);
+
+        return res;
+    }
+
+    /** {@inheritDoc} */
+    @Override public boolean hasArray() {
+        return true;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void writeByteAndShift(byte val) {
+        data[pos++] = val;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void copyAndShift(Object src, long off, int len) {
+        UNSAFE.copyMemory(src, off, data, BYTE_ARR_OFF + pos, len);
+
+        shift(len);
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void writeShortFast(short val) {
+        UNSAFE.putShort(data, BYTE_ARR_OFF + pos, val);
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void writeCharFast(char val) {
+        UNSAFE.putChar(data, BYTE_ARR_OFF + pos, val);
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void writeIntFast(int val) {
+        UNSAFE.putInt(data, BYTE_ARR_OFF + pos, val);
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void writeLongFast(long val) {
+        UNSAFE.putLong(data, BYTE_ARR_OFF + pos, val);
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void writeIntPositioned(int pos, int val) {
+        if (!LITTLE_ENDIAN)
+            val = Integer.reverseBytes(val);
+
+        UNSAFE.putInt(data, BYTE_ARR_OFF + pos, val);
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/internal/portable/streams/PortableInputStream.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/portable/streams/PortableInputStream.java b/modules/core/src/main/java/org/apache/ignite/internal/portable/streams/PortableInputStream.java
new file mode 100644
index 0000000..cd6e039
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/streams/PortableInputStream.java
@@ -0,0 +1,168 @@
+/*
+ * 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.portable.streams;
+
+/**
+ * Portable input stream.
+ */
+public interface PortableInputStream extends PortableStream {
+    /**
+     * Read byte value.
+     *
+     * @return Byte value.
+     */
+    public byte readByte();
+
+    /**
+     * Read byte array.
+     *
+     * @param cnt Expected item count.
+     * @return Byte array.
+     */
+    public byte[] readByteArray(int cnt);
+
+    /**
+     * Reads {@code cnt} of bytes into byte array.
+     *
+     * @param arr Expected item count.
+     * @param off offset
+     * @param cnt number of bytes to read.
+     * @return actual length read.
+     */
+    public int read(byte[] arr, int off, int cnt);
+
+    /**
+     * Read boolean value.
+     *
+     * @return Boolean value.
+     */
+    public boolean readBoolean();
+
+    /**
+     * Read boolean array.
+     *
+     * @param cnt Expected item count.
+     * @return Boolean array.
+     */
+    public boolean[] readBooleanArray(int cnt);
+
+    /**
+     * Read short value.
+     *
+     * @return Short value.
+     */
+    public short readShort();
+
+    /**
+     * Read short array.
+     *
+     * @param cnt Expected item count.
+     * @return Short array.
+     */
+    public short[] readShortArray(int cnt);
+
+    /**
+     * Read char value.
+     *
+     * @return Char value.
+     */
+    public char readChar();
+
+    /**
+     * Read char array.
+     *
+     * @param cnt Expected item count.
+     * @return Char array.
+     */
+    public char[] readCharArray(int cnt);
+
+    /**
+     * Read int value.
+     *
+     * @return Int value.
+     */
+    public int readInt();
+
+    /**
+     * Read int value at the given position.
+     *
+     * @param pos Position.
+     * @return Value.
+     */
+    public int readInt(int pos);
+
+    /**
+     * Read int array.
+     *
+     * @param cnt Expected item count.
+     * @return Int array.
+     */
+    public int[] readIntArray(int cnt);
+
+    /**
+     * Read float value.
+     *
+     * @return Float value.
+     */
+    public float readFloat();
+
+    /**
+     * Read float array.
+     *
+     * @param cnt Expected item count.
+     * @return Float array.
+     */
+    public float[] readFloatArray(int cnt);
+
+    /**
+     * Read long value.
+     *
+     * @return Long value.
+     */
+    public long readLong();
+
+    /**
+     * Read long array.
+     *
+     * @param cnt Expected item count.
+     * @return Long array.
+     */
+    public long[] readLongArray(int cnt);
+
+    /**
+     * Read double value.
+     *
+     * @return Double value.
+     */
+    public double readDouble();
+
+    /**
+     * Read double array.
+     *
+     * @param cnt Expected item count.
+     * @return Double array.
+     */
+    public double[] readDoubleArray(int cnt);
+
+    /**
+     * Gets amount of remaining data in bytes.
+     *
+     * @return Remaining data.
+     */
+    public int remaining();
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/internal/portable/streams/PortableMemoryAllocator.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/portable/streams/PortableMemoryAllocator.java b/modules/core/src/main/java/org/apache/ignite/internal/portable/streams/PortableMemoryAllocator.java
new file mode 100644
index 0000000..071396a
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/streams/PortableMemoryAllocator.java
@@ -0,0 +1,76 @@
+/*
+ * 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.portable.streams;
+
+/**
+ * Portable memory allocator.
+ */
+public interface PortableMemoryAllocator {
+    /** Default memory allocator. */
+    public static final PortableMemoryAllocator DFLT_ALLOC = new PortableSimpleMemoryAllocator();
+
+    /**
+     * Allocate memory.
+     *
+     * @param size Size.
+     * @return Data.
+     */
+    public byte[] allocate(int size);
+
+    /**
+     * Reallocates memory.
+     *
+     * @param data Current data chunk.
+     * @param size New size required.
+     *
+     * @return Data.
+     */
+    public byte[] reallocate(byte[] data, int size);
+
+    /**
+     * Release memory.
+     *
+     * @param data Data.
+     * @param maxMsgSize Max message size sent during the time the allocator is used.
+     */
+    public void release(byte[] data, int maxMsgSize);
+
+    /**
+     * Allocate memory.
+     *
+     * @param size Size.
+     * @return Address.
+     */
+    public long allocateDirect(int size);
+
+    /**
+     * Reallocate memory.
+     *
+     * @param addr Address.
+     * @param size Size.
+     * @return Address.
+     */
+    public long reallocateDirect(long addr, int size);
+
+    /**
+     * Release memory.
+     *
+     * @param addr Address.
+     */
+    public void releaseDirect(long addr);
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/internal/portable/streams/PortableOffheapInputStream.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/portable/streams/PortableOffheapInputStream.java b/modules/core/src/main/java/org/apache/ignite/internal/portable/streams/PortableOffheapInputStream.java
new file mode 100644
index 0000000..bfdd97a
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/streams/PortableOffheapInputStream.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.portable.streams;
+
+/**
+ * Portable off-heap input stream.
+ */
+public class PortableOffheapInputStream extends PortableAbstractInputStream {
+    /** Pointer. */
+    private final long ptr;
+
+    /** Capacity. */
+    private final int cap;
+
+    /** */
+    private boolean forceHeap;
+
+    /**
+     * Constructor.
+     *
+     * @param ptr Pointer.
+     * @param cap Capacity.
+     */
+    public PortableOffheapInputStream(long ptr, int cap) {
+        this(ptr, cap, false);
+    }
+
+    /**
+     * Constructor.
+     *
+     * @param ptr Pointer.
+     * @param cap Capacity.
+     * @param forceHeap If {@code true} method {@link #offheapPointer} returns 0 and unmarshalling will
+     *        create heap-based objects.
+     */
+    public PortableOffheapInputStream(long ptr, int cap, boolean forceHeap) {
+        this.ptr = ptr;
+        this.cap = cap;
+        this.forceHeap = forceHeap;
+
+        len = cap;
+    }
+
+    /** {@inheritDoc} */
+    @Override public int remaining() {
+        return cap - pos;
+    }
+
+    /** {@inheritDoc} */
+    @Override public byte[] array() {
+        return arrayCopy();
+    }
+
+    /** {@inheritDoc} */
+    @Override public byte[] arrayCopy() {
+        byte[] res = new byte[len];
+
+        UNSAFE.copyMemory(null, ptr, res, BYTE_ARR_OFF, res.length);
+
+        return res;
+    }
+
+    /** {@inheritDoc} */
+    @Override public boolean hasArray() {
+        return false;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected byte readByteAndShift() {
+        return UNSAFE.getByte(ptr + pos++);
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void copyAndShift(Object target, long off, int len) {
+        UNSAFE.copyMemory(null, ptr + pos, target, off, len);
+
+        shift(len);
+    }
+
+    /** {@inheritDoc} */
+    @Override protected short readShortFast() {
+        return UNSAFE.getShort(ptr + pos);
+    }
+
+    /** {@inheritDoc} */
+    @Override protected char readCharFast() {
+        return UNSAFE.getChar(ptr + pos);
+    }
+
+    /** {@inheritDoc} */
+    @Override protected int readIntFast() {
+        return UNSAFE.getInt(ptr + pos);
+    }
+
+    /** {@inheritDoc} */
+    @Override protected long readLongFast() {
+        return UNSAFE.getLong(ptr + pos);
+    }
+
+    /** {@inheritDoc} */
+    @Override protected int readIntPositioned(int pos) {
+        int res = UNSAFE.getInt(ptr + pos);
+
+        if (!LITTLE_ENDIAN)
+            res = Integer.reverseBytes(res);
+
+        return res;
+    }
+
+    /** {@inheritDoc} */
+    @Override public long offheapPointer() {
+        return forceHeap ? 0 : ptr;
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/internal/portable/streams/PortableOffheapOutputStream.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/portable/streams/PortableOffheapOutputStream.java b/modules/core/src/main/java/org/apache/ignite/internal/portable/streams/PortableOffheapOutputStream.java
new file mode 100644
index 0000000..adfb6bf
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/streams/PortableOffheapOutputStream.java
@@ -0,0 +1,169 @@
+/*
+ * 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.portable.streams;
+
+/**
+ * Portable offheap output stream.
+ */
+public class PortableOffheapOutputStream extends PortableAbstractOutputStream {
+    /** Pointer. */
+    private long ptr;
+
+    /** Length of bytes that cen be used before resize is necessary. */
+    private int cap;
+
+    /**
+     * Constructor.
+     *
+     * @param cap Capacity.
+     */
+    public PortableOffheapOutputStream(int cap) {
+        this(0, cap);
+    }
+
+    /**
+     * Constructor.
+     *
+     * @param ptr Pointer to existing address.
+     * @param cap Capacity.
+     */
+    public PortableOffheapOutputStream(long ptr, int cap) {
+        this.ptr = ptr == 0 ? allocate(cap) : ptr;
+
+        this.cap = cap;
+    }
+
+    /** {@inheritDoc} */
+    @Override public void close() {
+        release(ptr);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void ensureCapacity(int cnt) {
+        if (cnt > cap) {
+            int newCap = capacity(cap, cnt);
+
+            ptr = reallocate(ptr, newCap);
+
+            cap = newCap;
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override public byte[] array() {
+        return arrayCopy();
+    }
+
+    /** {@inheritDoc} */
+    @Override public byte[] arrayCopy() {
+        byte[] res = new byte[pos];
+
+        UNSAFE.copyMemory(null, ptr, res, BYTE_ARR_OFF, pos);
+
+        return res;
+    }
+
+    /**
+     * @return Pointer.
+     */
+    public long pointer() {
+        return ptr;
+    }
+
+    /**
+     * @return Capacity.
+     */
+    public int capacity() {
+        return cap;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void writeByteAndShift(byte val) {
+        UNSAFE.putByte(ptr + pos++, val);
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void copyAndShift(Object src, long offset, int len) {
+        UNSAFE.copyMemory(src, offset, null, ptr + pos, len);
+
+        shift(len);
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void writeShortFast(short val) {
+        UNSAFE.putShort(ptr + pos, val);
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void writeCharFast(char val) {
+        UNSAFE.putChar(ptr + pos, val);
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void writeIntFast(int val) {
+        UNSAFE.putInt(ptr + pos, val);
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void writeLongFast(long val) {
+        UNSAFE.putLong(ptr + pos, val);
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void writeIntPositioned(int pos, int val) {
+        if (!LITTLE_ENDIAN)
+            val = Integer.reverseBytes(val);
+
+        UNSAFE.putInt(ptr + pos, val);
+    }
+
+    /** {@inheritDoc} */
+    @Override public boolean hasArray() {
+        return false;
+    }
+
+    /**
+     * Allocate memory.
+     *
+     * @param cap Capacity.
+     * @return Pointer.
+     */
+    protected long allocate(int cap) {
+        return UNSAFE.allocateMemory(cap);
+    }
+
+    /**
+     * Reallocate memory.
+     *
+     * @param ptr Old pointer.
+     * @param cap Capacity.
+     * @return New pointer.
+     */
+    protected long reallocate(long ptr, int cap) {
+        return UNSAFE.reallocateMemory(ptr, cap);
+    }
+
+    /**
+     * Release memory.
+     *
+     * @param ptr Pointer.
+     */
+    protected void release(long ptr) {
+        UNSAFE.freeMemory(ptr);
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/internal/portable/streams/PortableOutputStream.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/portable/streams/PortableOutputStream.java b/modules/core/src/main/java/org/apache/ignite/internal/portable/streams/PortableOutputStream.java
new file mode 100644
index 0000000..f320566
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/streams/PortableOutputStream.java
@@ -0,0 +1,165 @@
+/*
+ * 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.portable.streams;
+
+/**
+ * Portable output stream.
+ */
+public interface PortableOutputStream extends PortableStream, AutoCloseable {
+    /**
+     * Write byte value.
+     *
+     * @param val Byte value.
+     */
+    public void writeByte(byte val);
+
+    /**
+     * Write byte array.
+     *
+     * @param val Byte array.
+     */
+    public void writeByteArray(byte[] val);
+
+    /**
+     * Write boolean value.
+     *
+     * @param val Boolean value.
+     */
+    public void writeBoolean(boolean val);
+
+    /**
+     * Write boolean array.
+     *
+     * @param val Boolean array.
+     */
+    public void writeBooleanArray(boolean[] val);
+
+    /**
+     * Write short value.
+     *
+     * @param val Short value.
+     */
+    public void writeShort(short val);
+
+    /**
+     * Write short array.
+     *
+     * @param val Short array.
+     */
+    public void writeShortArray(short[] val);
+
+    /**
+     * Write char value.
+     *
+     * @param val Char value.
+     */
+    public void writeChar(char val);
+
+    /**
+     * Write char array.
+     *
+     * @param val Char array.
+     */
+    public void writeCharArray(char[] val);
+
+    /**
+     * Write int value.
+     *
+     * @param val Int value.
+     */
+    public void writeInt(int val);
+
+    /**
+     * Write int value to the given position.
+     *
+     * @param pos Position.
+     * @param val Value.
+     */
+    public void writeInt(int pos, int val);
+
+    /**
+     * Write int array.
+     *
+     * @param val Int array.
+     */
+    public void writeIntArray(int[] val);
+
+    /**
+     * Write float value.
+     *
+     * @param val Float value.
+     */
+    public void writeFloat(float val);
+
+    /**
+     * Write float array.
+     *
+     * @param val Float array.
+     */
+    public void writeFloatArray(float[] val);
+
+    /**
+     * Write long value.
+     *
+     * @param val Long value.
+     */
+    public void writeLong(long val);
+
+    /**
+     * Write long array.
+     *
+     * @param val Long array.
+     */
+    public void writeLongArray(long[] val);
+
+    /**
+     * Write double value.
+     *
+     * @param val Double value.
+     */
+    public void writeDouble(double val);
+
+    /**
+     * Write double array.
+     *
+     * @param val Double array.
+     */
+    public void writeDoubleArray(double[] val);
+
+    /**
+     * Write byte array.
+     *
+     * @param arr Array.
+     * @param off Offset.
+     * @param len Length.
+     */
+    public void write(byte[] arr, int off, int len);
+
+    /**
+     * Write data from unmanaged memory.
+     *
+     * @param addr Address.
+     * @param cnt Count.
+     */
+    public void write(long addr, int cnt);
+
+    /**
+     * Close the stream releasing resources.
+     */
+    @Override public void close();
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/internal/portable/streams/PortableSimpleMemoryAllocator.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/portable/streams/PortableSimpleMemoryAllocator.java b/modules/core/src/main/java/org/apache/ignite/internal/portable/streams/PortableSimpleMemoryAllocator.java
new file mode 100644
index 0000000..6021140
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/streams/PortableSimpleMemoryAllocator.java
@@ -0,0 +1,67 @@
+/*
+ * 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.portable.streams;
+
+import org.apache.ignite.internal.util.*;
+
+import sun.misc.*;
+
+/**
+ * Naive implementation of portable memory allocator.
+ */
+public class PortableSimpleMemoryAllocator implements PortableMemoryAllocator {
+    /** Unsafe. */
+    private static final Unsafe UNSAFE = GridUnsafe.unsafe();
+
+    /** Array offset: byte. */
+    protected static final long BYTE_ARR_OFF = UNSAFE.arrayBaseOffset(byte[].class);
+
+    /** {@inheritDoc} */
+    @Override public byte[] allocate(int size) {
+        return new byte[size];
+    }
+
+    /** {@inheritDoc} */
+    @Override public byte[] reallocate(byte[] data, int size) {
+        byte[] newData = new byte[size];
+
+        UNSAFE.copyMemory(data, BYTE_ARR_OFF, newData, BYTE_ARR_OFF, data.length);
+
+        return newData;
+    }
+
+    /** {@inheritDoc} */
+    @Override public void release(byte[] data, int maxMsgSize) {
+        // No-op.
+    }
+
+    /** {@inheritDoc} */
+    @Override public long allocateDirect(int size) {
+        return UNSAFE.allocateMemory(size);
+    }
+
+    /** {@inheritDoc} */
+    @Override public long reallocateDirect(long addr, int size) {
+        return UNSAFE.reallocateMemory(addr, size);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void releaseDirect(long addr) {
+        UNSAFE.freeMemory(addr);
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/internal/portable/streams/PortableStream.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/portable/streams/PortableStream.java b/modules/core/src/main/java/org/apache/ignite/internal/portable/streams/PortableStream.java
new file mode 100644
index 0000000..5c84609
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/streams/PortableStream.java
@@ -0,0 +1,53 @@
+/*
+ * 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.portable.streams;
+
+/**
+ * Portable stream.
+ */
+public interface PortableStream {
+    /**
+     * @return Position.
+     */
+    public int position();
+
+    /**
+     * @param pos Position.
+     */
+    public void position(int pos);
+
+    /**
+     * @return Underlying array.
+     */
+    public byte[] array();
+
+    /**
+     * @return Copy of data in the stream.
+     */
+    public byte[] arrayCopy();
+
+    /**
+     * @return Offheap pointer if stream is offheap based, otherwise {@code 0}.
+     */
+    public long offheapPointer();
+
+    /**
+     * @return {@code True} is stream is array based.
+     */
+    public boolean hasArray();
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/internal/portable/streams/package-info.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/portable/streams/package-info.java b/modules/core/src/main/java/org/apache/ignite/internal/portable/streams/package-info.java
new file mode 100644
index 0000000..1d39a70
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/streams/package-info.java
@@ -0,0 +1,22 @@
+/*
+ * 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 description. -->
+ * Contains portable APIs implementation for streams.
+ */
+package org.apache.ignite.internal.portable.streams;
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/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 287b3c7..dd4d30b 100644
--- 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
@@ -55,6 +55,7 @@ import org.apache.ignite.lang.*;
 import org.apache.ignite.lifecycle.*;
 import org.apache.ignite.marshaller.*;
 import org.apache.ignite.marshaller.jdk.*;
+import org.apache.ignite.marshaller.portable.*;
 import org.apache.ignite.spi.*;
 import org.jetbrains.annotations.*;
 
@@ -985,6 +986,12 @@ public class GridCacheProcessor extends GridProcessorAdapter {
 
         CacheConfiguration cfg = cacheCtx.config();
 
+        // Intentionally compare Boolean references using '!=' below to check if the flag has been explicitly set.
+        if (cfg.isKeepPortableInStore() && cfg.isKeepPortableInStore() != CacheConfiguration.DFLT_KEEP_PORTABLE_IN_STORE
+            && !(ctx.config().getMarshaller() instanceof PortableMarshaller))
+            U.warn(log, "CacheConfiguration.isKeepPortableInStore() configuration property will be ignored because " +
+                "PortableMarshaller is not used");
+
         // Start managers.
         for (GridCacheManager mgr : F.view(cacheCtx.managers(), F.notContains(dhtExcludes(cacheCtx))))
             mgr.start(cacheCtx);

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/IgniteCacheProxy.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/IgniteCacheProxy.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/IgniteCacheProxy.java
index e532778..3381403 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/IgniteCacheProxy.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/IgniteCacheProxy.java
@@ -272,6 +272,11 @@ public class IgniteCacheProxy<K, V> extends AsyncSupportAdapter<IgniteCache<K, V
     }
 
     /** {@inheritDoc} */
+    @Override public <K1, V1> IgniteCache<K1, V1> withKeepPortable() {
+        return keepPortable();
+    }
+
+    /** {@inheritDoc} */
     @Override public IgniteCache<K, V> withNoRetries() {
         GridCacheGateway<K, V> gate = this.gate;
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/portable/CacheDefaultPortableAffinityKeyMapper.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/portable/CacheDefaultPortableAffinityKeyMapper.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/portable/CacheDefaultPortableAffinityKeyMapper.java
new file mode 100644
index 0000000..f8be30c
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/portable/CacheDefaultPortableAffinityKeyMapper.java
@@ -0,0 +1,51 @@
+/*
+ * 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.portable;
+
+import org.apache.ignite.*;
+import org.apache.ignite.internal.*;
+import org.apache.ignite.internal.processors.cache.*;
+import org.apache.ignite.internal.util.typedef.internal.*;
+import org.apache.ignite.portable.*;
+
+/**
+ *
+ */
+public class CacheDefaultPortableAffinityKeyMapper extends GridCacheDefaultAffinityKeyMapper {
+    /** */
+    private static final long serialVersionUID = 0L;
+
+    /** {@inheritDoc} */
+    @Override public Object affinityKey(Object key) {
+        IgniteKernal kernal = (IgniteKernal)ignite;
+
+        CacheObjectPortableProcessorImpl proc = (CacheObjectPortableProcessorImpl)kernal.context().cacheObjects();
+
+        try {
+            key = proc.toPortable(key);
+        }
+        catch (IgniteException e) {
+            U.error(log, "Failed to marshal key to portable: " + key, e);
+        }
+
+        if (key instanceof PortableObject)
+            return proc.affinityKey((PortableObject)key);
+        else
+            return super.affinityKey(key);
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/portable/CacheObjectPortableContext.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/portable/CacheObjectPortableContext.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/portable/CacheObjectPortableContext.java
new file mode 100644
index 0000000..d4de1ec
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/portable/CacheObjectPortableContext.java
@@ -0,0 +1,187 @@
+/*
+ * 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.portable;
+
+import org.apache.ignite.internal.*;
+import org.apache.ignite.internal.portable.*;
+import org.apache.ignite.internal.processors.cache.*;
+import org.apache.ignite.internal.util.typedef.*;
+import org.apache.ignite.internal.util.typedef.internal.*;
+import org.apache.ignite.portable.*;
+
+import org.jsr166.*;
+
+import java.util.*;
+import java.util.concurrent.*;
+
+/**
+ *
+ */
+public class CacheObjectPortableContext extends CacheObjectContext {
+    /** */
+    private boolean portableEnabled;
+
+    /**
+     * @param kernalCtx Kernal context.
+     * @param portableEnabled Portable enabled flag.
+     * @param cpyOnGet Copy on get flag.
+     * @param storeVal {@code True} if should store unmarshalled value in cache.
+     */
+    public CacheObjectPortableContext(GridKernalContext kernalCtx,
+        boolean cpyOnGet,
+        boolean storeVal,
+        boolean portableEnabled) {
+        super(kernalCtx, portableEnabled ? new CacheDefaultPortableAffinityKeyMapper() :
+            new GridCacheDefaultAffinityKeyMapper(), cpyOnGet, storeVal);
+
+        this.portableEnabled = portableEnabled;
+    }
+
+    /**
+     * @return Portable enabled flag.
+     */
+    public boolean portableEnabled() {
+        return portableEnabled;
+    }
+
+    /** {@inheritDoc} */
+    @Override public Object unwrapPortableIfNeeded(Object o, boolean keepPortable) {
+        if (o == null)
+            return null;
+
+        if (keepPortable || !portableEnabled() || !PortableUtils.isPortableOrCollectionType(o.getClass()))
+            return o;
+
+        return unwrapPortable(o);
+    }
+
+    /** {@inheritDoc} */
+    @Override public Collection<Object> unwrapPortablesIfNeeded(Collection<Object> col, boolean keepPortable) {
+        if (keepPortable || !portableEnabled())
+            return col;
+
+        if (col instanceof ArrayList)
+            return unwrapPortables((ArrayList<Object>)col);
+
+        if (col instanceof Set)
+            return unwrapPortables((Set<Object>)col);
+
+        Collection<Object> col0 = new ArrayList<>(col.size());
+
+        for (Object obj : col)
+            col0.add(unwrapPortable(obj));
+
+        return col0;
+    }
+
+    /**
+     * Unwraps map.
+     *
+     * @param map Map to unwrap.
+     * @param keepPortable Keep portable flag.
+     * @return Unwrapped collection.
+     */
+    public Map<Object, Object> unwrapPortablesIfNeeded(Map<Object, Object> map, boolean keepPortable) {
+        if (keepPortable || !portableEnabled())
+            return map;
+
+        Map<Object, Object> map0 = PortableUtils.newMap(map);
+
+        for (Map.Entry<Object, Object> e : map.entrySet())
+            map0.put(unwrapPortable(e.getKey()), unwrapPortable(e.getValue()));
+
+        return map0;
+    }
+
+    /**
+     * Unwraps array list.
+     *
+     * @param col List to unwrap.
+     * @return Unwrapped list.
+     */
+    private Collection<Object> unwrapPortables(ArrayList<Object> col) {
+        int size = col.size();
+
+        for (int i = 0; i < size; i++) {
+            Object o = col.get(i);
+
+            Object unwrapped = unwrapPortable(o);
+
+            if (o != unwrapped)
+                col.set(i, unwrapped);
+        }
+
+        return col;
+    }
+
+    /**
+     * Unwraps set with portables.
+     *
+     * @param set Set to unwrap.
+     * @return Unwrapped set.
+     */
+    private Set<Object> unwrapPortables(Set<Object> set) {
+        Set<Object> set0 = PortableUtils.newSet(set);
+
+        Iterator<Object> iter = set.iterator();
+
+        while (iter.hasNext())
+            set0.add(unwrapPortable(iter.next()));
+
+        return set0;
+    }
+
+    /**
+     * @param o Object to unwrap.
+     * @return Unwrapped object.
+     */
+    private Object unwrapPortable(Object o) {
+        if (o instanceof Map.Entry) {
+            Map.Entry entry = (Map.Entry)o;
+
+            Object key = entry.getKey();
+
+            boolean unwrapped = false;
+
+            if (key instanceof PortableObject) {
+                key = ((PortableObject)key).deserialize();
+
+                unwrapped = true;
+            }
+
+            Object val = entry.getValue();
+
+            if (val instanceof PortableObject) {
+                val = ((PortableObject)val).deserialize();
+
+                unwrapped = true;
+            }
+
+            return unwrapped ? F.t(key, val) : o;
+        }
+        else if (o instanceof Collection)
+            return unwrapPortablesIfNeeded((Collection<Object>)o, false);
+        else if (o instanceof Map)
+            return unwrapPortablesIfNeeded((Map<Object, Object>)o, false);
+        else if (o instanceof PortableObject)
+            return ((PortableObject)o).deserialize();
+
+        return o;
+    }
+}
+

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/portable/CacheObjectPortableProcessor.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/portable/CacheObjectPortableProcessor.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/portable/CacheObjectPortableProcessor.java
new file mode 100644
index 0000000..fb047d1
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/portable/CacheObjectPortableProcessor.java
@@ -0,0 +1,101 @@
+/*
+ * 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.portable;
+
+import org.apache.ignite.*;
+import org.apache.ignite.internal.processors.cacheobject.*;
+import org.apache.ignite.portable.*;
+
+import org.jetbrains.annotations.*;
+
+import java.util.*;
+
+/**
+ * Extended cache object processor interface with additional methods for portables.
+ */
+public interface CacheObjectPortableProcessor extends IgniteCacheObjectProcessor {
+    /**
+     * @param typeId Type ID.
+     * @return Builder.
+     */
+    public PortableBuilder builder(int typeId);
+
+    /**
+     * @param clsName Class name.
+     * @return Builder.
+     */
+    public PortableBuilder builder(String clsName);
+
+    /**
+     * Creates builder initialized by existing portable object.
+     *
+     * @param portableObj Portable object to edit.
+     * @return Portable builder.
+     */
+    public PortableBuilder builder(PortableObject portableObj);
+
+    /**
+     * @param typeId Type ID.
+     * @param newMeta New meta data.
+     * @throws IgniteException In case of error.
+     */
+    public void addMeta(int typeId, final PortableMetadata newMeta) throws IgniteException;
+
+    /**
+     * @param typeId Type ID.
+     * @param typeName Type name.
+     * @param affKeyFieldName Affinity key field name.
+     * @param fieldTypeIds Fields map.
+     * @throws IgniteException In case of error.
+     */
+    public void updateMetaData(int typeId, String typeName, @Nullable String affKeyFieldName,
+        Map<String, Integer> fieldTypeIds) throws IgniteException;
+
+    /**
+     * @param typeId Type ID.
+     * @return Meta data.
+     * @throws IgniteException In case of error.
+     */
+    @Nullable public PortableMetadata metadata(int typeId) throws IgniteException;
+
+    /**
+     * @param typeIds Type ID.
+     * @return Meta data.
+     * @throws IgniteException In case of error.
+     */
+    public Map<Integer, PortableMetadata> metadata(Collection<Integer> typeIds) throws IgniteException;
+
+    /**
+     * @return Metadata for all types.
+     * @throws IgniteException In case of error.
+     */
+    public Collection<PortableMetadata> metadata() throws IgniteException;
+
+    /**
+     * @return Portables interface.
+     * @throws IgniteException If failed.
+     */
+    public IgnitePortables portables() throws IgniteException;
+
+    /**
+     * @param obj Original object.
+     * @return Portable object (in case portable marshaller is used).
+     * @throws IgniteException If failed.
+     */
+    public Object marshalToPortable(Object obj) throws IgniteException;
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/portable/CacheObjectPortableProcessorImpl.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/portable/CacheObjectPortableProcessorImpl.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/portable/CacheObjectPortableProcessorImpl.java
new file mode 100644
index 0000000..a421129
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/portable/CacheObjectPortableProcessorImpl.java
@@ -0,0 +1,956 @@
+/*
+ * 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.portable;
+
+import org.apache.ignite.*;
+import org.apache.ignite.cache.*;
+import org.apache.ignite.cluster.*;
+import org.apache.ignite.configuration.*;
+import org.apache.ignite.internal.*;
+import org.apache.ignite.internal.portable.*;
+import org.apache.ignite.internal.portable.streams.*;
+import org.apache.ignite.internal.processors.affinity.*;
+import org.apache.ignite.internal.processors.cache.*;
+import org.apache.ignite.internal.processors.cache.query.*;
+import org.apache.ignite.internal.processors.cacheobject.*;
+import org.apache.ignite.internal.util.*;
+import org.apache.ignite.internal.util.lang.*;
+import org.apache.ignite.internal.util.tostring.*;
+import org.apache.ignite.internal.util.typedef.*;
+import org.apache.ignite.internal.util.typedef.internal.*;
+import org.apache.ignite.lang.*;
+import org.apache.ignite.marshaller.*;
+import org.apache.ignite.marshaller.portable.*;
+import org.apache.ignite.portable.*;
+
+import org.jetbrains.annotations.*;
+import org.jsr166.*;
+import sun.misc.*;
+
+import javax.cache.Cache;
+import javax.cache.*;
+import javax.cache.event.*;
+import javax.cache.processor.*;
+import java.io.*;
+import java.util.*;
+import java.util.concurrent.*;
+
+import static org.apache.ignite.internal.portable.GridPortableMarshaller.*;
+
+/**
+ * Portable processor implementation.
+ */
+public class CacheObjectPortableProcessorImpl extends IgniteCacheObjectProcessorImpl implements
+    CacheObjectPortableProcessor {
+    /** */
+    public static final String[] FIELD_TYPE_NAMES;
+
+    /** */
+    private static final Unsafe UNSAFE = GridUnsafe.unsafe();
+
+    /** */
+    private final CountDownLatch startLatch = new CountDownLatch(1);
+
+    /** */
+    private final boolean clientNode;
+
+    /** */
+    private volatile IgniteCacheProxy<PortableMetaDataKey, PortableMetadata> metaDataCache;
+
+    /** */
+    private final ConcurrentHashMap8<PortableMetaDataKey, PortableMetadata> clientMetaDataCache;
+
+    /** Predicate to filter portable meta data in utility cache. */
+    private final CacheEntryPredicate metaPred = new CacheEntryPredicateAdapter() {
+        private static final long serialVersionUID = 0L;
+
+        @Override public boolean apply(GridCacheEntryEx e) {
+            return e.key().value(e.context().cacheObjectContext(), false) instanceof PortableMetaDataKey;
+        }
+    };
+
+    /** */
+    private PortableContext portableCtx;
+
+    /** */
+    private Marshaller marsh;
+
+    /** */
+    private GridPortableMarshaller portableMarsh;
+
+    /** */
+    @GridToStringExclude
+    private IgnitePortables portables;
+
+    /** Metadata updates collected before metadata cache is initialized. */
+    private final Map<Integer, PortableMetadata> metaBuf = new ConcurrentHashMap<>();
+
+    /** */
+    private UUID metaCacheQryId;
+
+    /**
+     *
+     */
+    static {
+        FIELD_TYPE_NAMES = new String[104];
+
+        FIELD_TYPE_NAMES[BYTE] = "byte";
+        FIELD_TYPE_NAMES[SHORT] = "short";
+        FIELD_TYPE_NAMES[INT] = "int";
+        FIELD_TYPE_NAMES[LONG] = "long";
+        FIELD_TYPE_NAMES[BOOLEAN] = "boolean";
+        FIELD_TYPE_NAMES[FLOAT] = "float";
+        FIELD_TYPE_NAMES[DOUBLE] = "double";
+        FIELD_TYPE_NAMES[CHAR] = "char";
+        FIELD_TYPE_NAMES[UUID] = "UUID";
+        FIELD_TYPE_NAMES[DECIMAL] = "decimal";
+        FIELD_TYPE_NAMES[STRING] = "String";
+        FIELD_TYPE_NAMES[DATE] = "Date";
+        FIELD_TYPE_NAMES[ENUM] = "Enum";
+        FIELD_TYPE_NAMES[OBJ] = "Object";
+        FIELD_TYPE_NAMES[PORTABLE_OBJ] = "Object";
+        FIELD_TYPE_NAMES[COL] = "Collection";
+        FIELD_TYPE_NAMES[MAP] = "Map";
+        FIELD_TYPE_NAMES[BYTE_ARR] = "byte[]";
+        FIELD_TYPE_NAMES[SHORT_ARR] = "short[]";
+        FIELD_TYPE_NAMES[INT_ARR] = "int[]";
+        FIELD_TYPE_NAMES[LONG_ARR] = "long[]";
+        FIELD_TYPE_NAMES[BOOLEAN_ARR] = "boolean[]";
+        FIELD_TYPE_NAMES[FLOAT_ARR] = "float[]";
+        FIELD_TYPE_NAMES[DOUBLE_ARR] = "double[]";
+        FIELD_TYPE_NAMES[CHAR_ARR] = "char[]";
+        FIELD_TYPE_NAMES[UUID_ARR] = "UUID[]";
+        FIELD_TYPE_NAMES[DECIMAL_ARR] = "decimal[]";
+        FIELD_TYPE_NAMES[STRING_ARR] = "String[]";
+        FIELD_TYPE_NAMES[DATE_ARR] = "Date[]";
+        FIELD_TYPE_NAMES[OBJ_ARR] = "Object[]";
+        FIELD_TYPE_NAMES[ENUM_ARR] = "Enum[]";
+    }
+
+    /**
+     * @param typeName Field type name.
+     * @return Field type ID;
+     */
+    @SuppressWarnings("StringEquality")
+    public static int fieldTypeId(String typeName) {
+        for (int i = 0; i < FIELD_TYPE_NAMES.length; i++) {
+            String typeName0 = FIELD_TYPE_NAMES[i];
+
+            if (typeName.equals(typeName0))
+                return i;
+        }
+
+        throw new IllegalArgumentException("Invalid metadata type name: " + typeName);
+    }
+
+    /**
+     * @param typeId Field type ID.
+     * @return Field type name.
+     */
+    public static String fieldTypeName(int typeId) {
+        assert typeId >= 0 && typeId < FIELD_TYPE_NAMES.length : typeId;
+
+        String typeName = FIELD_TYPE_NAMES[typeId];
+
+        assert typeName != null : typeId;
+
+        return typeName;
+    }
+
+    /**
+     * @param typeIds Field type IDs.
+     * @return Field type names.
+     */
+    public static Map<String, String> fieldTypeNames(Map<String, Integer> typeIds) {
+        Map<String, String> names = U.newHashMap(typeIds.size());
+
+        for (Map.Entry<String, Integer> e : typeIds.entrySet())
+            names.put(e.getKey(), fieldTypeName(e.getValue()));
+
+        return names;
+    }
+
+    /**
+     * @param ctx Kernal context.
+     */
+    public CacheObjectPortableProcessorImpl(GridKernalContext ctx) {
+        super(ctx);
+
+        marsh = ctx.grid().configuration().getMarshaller();
+
+        clientNode = this.ctx.clientNode();
+
+        clientMetaDataCache = clientNode ? new ConcurrentHashMap8<PortableMetaDataKey, PortableMetadata>() : null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public void start() throws IgniteCheckedException {
+        if (marsh instanceof PortableMarshaller) {
+            PortableMetaDataHandler metaHnd = new PortableMetaDataHandler() {
+                @Override public void addMeta(int typeId, PortableMetadata newMeta)
+                    throws PortableException {
+                    if (metaDataCache == null) {
+                        PortableMetadata oldMeta = metaBuf.get(typeId);
+
+                        if (oldMeta == null || checkMeta(typeId, oldMeta, newMeta, null)) {
+                            synchronized (this) {
+                                Map<String, String> fields = new HashMap<>();
+
+                                if (checkMeta(typeId, oldMeta, newMeta, fields)) {
+                                    newMeta = new PortableMetaDataImpl(newMeta.typeName(),
+                                        fields,
+                                        newMeta.affinityKeyFieldName());
+
+                                    metaBuf.put(typeId, newMeta);
+                                }
+                                else
+                                    return;
+                            }
+
+                            if (metaDataCache == null)
+                                return;
+                            else
+                                metaBuf.remove(typeId);
+                        }
+                        else
+                            return;
+                    }
+
+                    CacheObjectPortableProcessorImpl.this.addMeta(typeId, newMeta);
+                }
+
+                @Override public PortableMetadata metadata(int typeId) throws PortableException {
+                    if (metaDataCache == null)
+                        U.awaitQuiet(startLatch);
+
+                    return CacheObjectPortableProcessorImpl.this.metadata(typeId);
+                }
+            };
+
+            PortableMarshaller pMarh0 = (PortableMarshaller)marsh;
+
+            portableCtx = new PortableContext(metaHnd, ctx.gridName());
+
+            IgniteUtils.invoke(PortableMarshaller.class, pMarh0, "setPortableContext", portableCtx);
+
+            portableMarsh = new GridPortableMarshaller(portableCtx);
+
+            portables = new IgnitePortablesImpl(ctx, this);
+        }
+    }
+
+    /** {@inheritDoc} */
+    @SuppressWarnings("unchecked")
+    @Override public void onUtilityCacheStarted() throws IgniteCheckedException {
+        metaDataCache = ctx.cache().jcache(CU.UTILITY_CACHE_NAME);
+
+        if (clientNode) {
+            assert !metaDataCache.context().affinityNode();
+
+            metaCacheQryId = metaDataCache.context().continuousQueries().executeInternalQuery(
+                new MetaDataEntryListener(),
+                new MetaDataEntryFilter(),
+                false,
+                true);
+
+            while (true) {
+                ClusterNode oldestSrvNode =
+                    CU.oldestAliveCacheServerNode(ctx.cache().context(), AffinityTopologyVersion.NONE);
+
+                if (oldestSrvNode == null)
+                    break;
+
+                GridCacheQueryManager qryMgr = metaDataCache.context().queries();
+
+                CacheQuery<Map.Entry<PortableMetaDataKey, PortableMetadata>> qry =
+                    qryMgr.createScanQuery(new MetaDataPredicate(), null, false);
+
+                qry.keepAll(false);
+
+                qry.projection(ctx.cluster().get().forNode(oldestSrvNode));
+
+                try {
+                    CacheQueryFuture<Map.Entry<PortableMetaDataKey, PortableMetadata>> fut = qry.execute();
+
+                    Map.Entry<PortableMetaDataKey, PortableMetadata> next;
+
+                    while ((next = fut.next()) != null) {
+                        assert next.getKey() != null : next;
+                        assert next.getValue() != null : next;
+
+                        addClientCacheMetaData(next.getKey(), next.getValue());
+                    }
+                }
+                catch (IgniteCheckedException e) {
+                    if (!ctx.discovery().alive(oldestSrvNode) || !ctx.discovery().pingNode(oldestSrvNode.id()))
+                        continue;
+                    else
+                        throw e;
+                }
+
+                break;
+            }
+        }
+
+        startLatch.countDown();
+
+        for (Map.Entry<Integer, PortableMetadata> e : metaBuf.entrySet())
+            addMeta(e.getKey(), e.getValue());
+
+        metaBuf.clear();
+    }
+
+    /** {@inheritDoc} */
+    @Override public void onKernalStop(boolean cancel) {
+        super.onKernalStop(cancel);
+
+        if (metaCacheQryId != null)
+            metaDataCache.context().continuousQueries().cancelInternalQuery(metaCacheQryId);
+    }
+
+    /**
+     * @param key Metadata key.
+     * @param newMeta Metadata.
+     */
+    private void addClientCacheMetaData(PortableMetaDataKey key, final PortableMetadata newMeta) {
+        clientMetaDataCache.compute(key,
+            new ConcurrentHashMap8.BiFun<PortableMetaDataKey, PortableMetadata, PortableMetadata>() {
+                @Override public PortableMetadata apply(PortableMetaDataKey key, PortableMetadata oldMeta) {
+                    PortableMetadata res;
+
+                    try {
+                        res = checkMeta(key.typeId(), oldMeta, newMeta, null) ? newMeta : oldMeta;
+                    }
+                    catch (PortableException e) {
+                        res = oldMeta;
+                    }
+
+                    return res;
+                }
+            }
+        );
+    }
+
+    /** {@inheritDoc} */
+    @Override public int typeId(String typeName) {
+        return portableCtx.typeId(typeName);
+    }
+
+    /**
+     * @param obj Object.
+     * @return Bytes.
+     * @throws PortableException If failed.
+     */
+    public byte[] marshal(@Nullable Object obj) throws PortableException {
+        byte[] arr = portableMarsh.marshal(obj, 0);
+
+        assert arr.length > 0;
+
+        return arr;
+    }
+
+    /**
+     * @param ptr Off-heap pointer.
+     * @param forceHeap If {@code true} creates heap-based object.
+     * @return Object.
+     * @throws PortableException If failed.
+     */
+    public Object unmarshal(long ptr, boolean forceHeap) throws PortableException {
+        assert ptr > 0 : ptr;
+
+        int size = UNSAFE.getInt(ptr);
+
+        ptr += 4;
+
+        byte type = UNSAFE.getByte(ptr++);
+
+        if (type != CacheObject.TYPE_BYTE_ARR) {
+            assert size > 0 : size;
+
+            PortableInputStream in = new PortableOffheapInputStream(ptr, size, forceHeap);
+
+            return portableMarsh.unmarshal(in);
+        }
+        else
+            return U.copyMemory(ptr, size);
+    }
+
+    /** {@inheritDoc} */
+    @Override public Object marshalToPortable(@Nullable Object obj) throws PortableException {
+        if (obj == null)
+            return null;
+
+        if (PortableUtils.isPortableType(obj.getClass()))
+            return obj;
+
+        if (obj instanceof Object[]) {
+            Object[] arr = (Object[])obj;
+
+            Object[] pArr = new Object[arr.length];
+
+            for (int i = 0; i < arr.length; i++)
+                pArr[i] = marshalToPortable(arr[i]);
+
+            return pArr;
+        }
+
+        if (obj instanceof Collection) {
+            Collection<Object> col = (Collection<Object>)obj;
+
+            Collection<Object> pCol;
+
+            if (col instanceof Set)
+                pCol = (Collection<Object>)PortableUtils.newSet((Set<?>)col);
+            else
+                pCol = new ArrayList<>(col.size());
+
+            for (Object item : col)
+                pCol.add(marshalToPortable(item));
+
+            return pCol;
+        }
+
+        if (obj instanceof Map) {
+            Map<?, ?> map = (Map<?, ?>)obj;
+
+            Map<Object, Object> pMap = PortableUtils.newMap((Map<Object, Object>)obj);
+
+            for (Map.Entry<?, ?> e : map.entrySet())
+                pMap.put(marshalToPortable(e.getKey()), marshalToPortable(e.getValue()));
+
+            return pMap;
+        }
+
+        if (obj instanceof Map.Entry) {
+            Map.Entry<?, ?> e = (Map.Entry<?, ?>)obj;
+
+            return new GridMapEntry<>(marshalToPortable(e.getKey()), marshalToPortable(e.getValue()));
+        }
+
+        byte[] arr = portableMarsh.marshal(obj, 0);
+
+        assert arr.length > 0;
+
+        Object obj0 = portableMarsh.unmarshal(arr, null);
+
+        assert obj0 instanceof PortableObject;
+
+        ((PortableObjectImpl)obj0).detachAllowed(true);
+
+        return obj0;
+    }
+
+    /**
+     * @return Marshaller.
+     */
+    public GridPortableMarshaller marshaller() {
+        return portableMarsh;
+    }
+
+    /** {@inheritDoc} */
+    @Override public PortableBuilder builder(int typeId) {
+        return new PortableBuilderImpl(portableCtx, typeId);
+    }
+
+    /** {@inheritDoc} */
+    @Override public PortableBuilder builder(String clsName) {
+        return new PortableBuilderImpl(portableCtx, clsName);
+    }
+
+    /** {@inheritDoc} */
+    @Override public PortableBuilder builder(PortableObject portableObj) {
+        return PortableBuilderImpl.wrap(portableObj);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void updateMetaData(int typeId, String typeName, @Nullable String affKeyFieldName,
+        Map<String, Integer> fieldTypeIds) throws PortableException {
+        portableCtx.updateMetaData(typeId,
+            new PortableMetaDataImpl(typeName, fieldTypeNames(fieldTypeIds), affKeyFieldName));
+    }
+
+    /** {@inheritDoc} */
+    @Override public void addMeta(final int typeId, final PortableMetadata newMeta) throws PortableException {
+        assert newMeta != null;
+
+        final PortableMetaDataKey key = new PortableMetaDataKey(typeId);
+
+        try {
+            PortableMetadata oldMeta = metaDataCache.localPeek(key);
+
+            if (oldMeta == null || checkMeta(typeId, oldMeta, newMeta, null)) {
+                PortableException err = metaDataCache.invoke(key, new MetaDataProcessor(typeId, newMeta));
+
+                if (err != null)
+                    throw err;
+            }
+        }
+        catch (CacheException e) {
+            throw new PortableException("Failed to update meta data for type: " + newMeta.typeName(), e);
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Nullable @Override public PortableMetadata metadata(final int typeId) throws PortableException {
+        try {
+            if (clientNode)
+                return clientMetaDataCache.get(new PortableMetaDataKey(typeId));
+
+            return metaDataCache.localPeek(new PortableMetaDataKey(typeId));
+        }
+        catch (CacheException e) {
+            throw new PortableException(e);
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override public Map<Integer, PortableMetadata> metadata(Collection<Integer> typeIds)
+        throws PortableException {
+        try {
+            Collection<PortableMetaDataKey> keys = new ArrayList<>(typeIds.size());
+
+            for (Integer typeId : typeIds)
+                keys.add(new PortableMetaDataKey(typeId));
+
+            Map<PortableMetaDataKey, PortableMetadata> meta = metaDataCache.getAll(keys);
+
+            Map<Integer, PortableMetadata> res = U.newHashMap(meta.size());
+
+            for (Map.Entry<PortableMetaDataKey, PortableMetadata> e : meta.entrySet())
+                res.put(e.getKey().typeId(), e.getValue());
+
+            return res;
+        }
+        catch (CacheException e) {
+            throw new PortableException(e);
+        }
+    }
+
+    /** {@inheritDoc} */
+    @SuppressWarnings("unchecked")
+    @Override public Collection<PortableMetadata> metadata() throws PortableException {
+        if (clientNode)
+            return new ArrayList<>(clientMetaDataCache.values());
+
+        return F.viewReadOnly(metaDataCache.entrySetx(metaPred),
+            new C1<Cache.Entry<PortableMetaDataKey, PortableMetadata>, PortableMetadata>() {
+                private static final long serialVersionUID = 0L;
+
+                @Override public PortableMetadata apply(
+                    Cache.Entry<PortableMetaDataKey, PortableMetadata> e) {
+                    return e.getValue();
+                }
+            });
+    }
+
+    /** {@inheritDoc} */
+    @Override public IgnitePortables portables() throws IgniteException {
+        return portables;
+    }
+
+    /** {@inheritDoc} */
+    @Override public boolean isPortableObject(Object obj) {
+        return obj instanceof PortableObject;
+    }
+
+    /** {@inheritDoc} */
+    @Override public boolean isPortableEnabled() {
+        return marsh instanceof PortableMarshaller;
+    }
+
+    /**
+     * @param po Portable object.
+     * @return Affinity key.
+     */
+    public Object affinityKey(PortableObject po) {
+        try {
+            PortableMetadata meta = po.metaData();
+
+            if (meta != null) {
+                String affKeyFieldName = meta.affinityKeyFieldName();
+
+                if (affKeyFieldName != null)
+                    return po.field(affKeyFieldName);
+            }
+        }
+        catch (PortableException e) {
+            U.error(log, "Failed to get affinity field from portable object: " + po, e);
+        }
+
+        return po;
+    }
+
+    /** {@inheritDoc} */
+    @Override public int typeId(Object obj) {
+        if (obj == null)
+            return 0;
+
+        return isPortableObject(obj) ? ((PortableObject)obj).typeId() : typeId(obj.getClass().getSimpleName());
+    }
+
+    /** {@inheritDoc} */
+    @Override public Object field(Object obj, String fieldName) {
+        if (obj == null)
+            return null;
+
+        return isPortableObject(obj) ? ((PortableObject)obj).field(fieldName) : super.field(obj, fieldName);
+    }
+
+    /** {@inheritDoc} */
+    @Override public boolean hasField(Object obj, String fieldName) {
+        return obj != null && ((PortableObject)obj).hasField(fieldName);
+    }
+
+    /**
+     * @return Portable context.
+     */
+    public PortableContext portableContext() {
+        return portableCtx;
+    }
+
+    /** {@inheritDoc} */
+    @Override public CacheObjectContext contextForCache(CacheConfiguration cfg) throws IgniteCheckedException {
+        assert cfg != null;
+
+        boolean portableEnabled = marsh instanceof PortableMarshaller && !GridCacheUtils.isSystemCache(cfg.getName()) &&
+            !GridCacheUtils.isIgfsCache(ctx.config(), cfg.getName());
+
+        CacheObjectContext ctx0 = super.contextForCache(cfg);
+
+        CacheObjectContext res = new CacheObjectPortableContext(ctx,
+            ctx0.copyOnGet(),
+            ctx0.storeValue(),
+            portableEnabled);
+
+        ctx.resource().injectGeneric(res.defaultAffMapper());
+
+        return res;
+    }
+
+    /** {@inheritDoc} */
+    @Override public byte[] marshal(CacheObjectContext ctx, Object val) throws IgniteCheckedException {
+        if (!((CacheObjectPortableContext)ctx).portableEnabled() || portableMarsh == null)
+            return super.marshal(ctx, val);
+
+        byte[] arr = portableMarsh.marshal(val, 0);
+
+        assert arr.length > 0;
+
+        return arr;
+    }
+
+    /** {@inheritDoc} */
+    @Override public Object unmarshal(CacheObjectContext ctx, byte[] bytes, ClassLoader clsLdr)
+        throws IgniteCheckedException {
+        if (!((CacheObjectPortableContext)ctx).portableEnabled() || portableMarsh == null)
+            return super.unmarshal(ctx, bytes, clsLdr);
+
+        return portableMarsh.unmarshal(bytes, clsLdr);
+    }
+
+    /** {@inheritDoc} */
+    @Override public KeyCacheObject toCacheKeyObject(CacheObjectContext ctx, Object obj, boolean userObj) {
+        if (!((CacheObjectPortableContext)ctx).portableEnabled())
+            return super.toCacheKeyObject(ctx, obj, userObj);
+
+        if (obj instanceof KeyCacheObject)
+            return (KeyCacheObject)obj;
+
+        if (((CacheObjectPortableContext)ctx).portableEnabled()) {
+            obj = toPortable(obj);
+
+            if (obj instanceof PortableObject)
+                return (PortableObjectImpl)obj;
+        }
+
+        return toCacheKeyObject0(obj, userObj);
+    }
+
+    /** {@inheritDoc} */
+    @Nullable @Override public CacheObject toCacheObject(CacheObjectContext ctx, @Nullable Object obj,
+        boolean userObj) {
+        if (!((CacheObjectPortableContext)ctx).portableEnabled())
+            return super.toCacheObject(ctx, obj, userObj);
+
+        if (obj == null || obj instanceof CacheObject)
+            return (CacheObject)obj;
+
+        obj = toPortable(obj);
+
+        if (obj instanceof PortableObject)
+            return (PortableObjectImpl)obj;
+
+        return toCacheObject0(obj, userObj);
+    }
+
+    /** {@inheritDoc} */
+    @Override public CacheObject toCacheObject(CacheObjectContext ctx, byte type, byte[] bytes) {
+        if (type == PortableObjectImpl.TYPE_PORTABLE)
+            return new PortableObjectImpl(portableContext(), bytes, 0);
+
+        return super.toCacheObject(ctx, type, bytes);
+    }
+
+    /** {@inheritDoc} */
+    @Override public CacheObject toCacheObject(GridCacheContext ctx, long valPtr, boolean tmp)
+        throws IgniteCheckedException {
+        if (!((CacheObjectPortableContext)ctx.cacheObjectContext()).portableEnabled())
+            return super.toCacheObject(ctx, valPtr, tmp);
+
+        Object val = unmarshal(valPtr, !tmp);
+
+        if (val instanceof PortableObjectOffheapImpl)
+            return (PortableObjectOffheapImpl)val;
+
+        return new CacheObjectImpl(val, null);
+    }
+
+    /** {@inheritDoc} */
+    @Override public Object unwrapTemporary(GridCacheContext ctx, Object obj) throws PortableException {
+        if (!((CacheObjectPortableContext)ctx.cacheObjectContext()).portableEnabled())
+            return obj;
+
+        if (obj instanceof PortableObjectOffheapImpl)
+            return ((PortableObjectOffheapImpl)obj).heapCopy();
+
+        return obj;
+    }
+
+    /**
+     * @param obj Object.
+     * @return Portable object.
+     * @throws IgniteException In case of error.
+     */
+    @Nullable public Object toPortable(@Nullable Object obj) throws IgniteException {
+        if (obj == null)
+            return null;
+
+        if (isPortableObject(obj))
+            return obj;
+
+        return marshalToPortable(obj);
+    }
+
+    /**
+     * @param typeId Type ID.
+     * @param oldMeta Old meta.
+     * @param newMeta New meta.
+     * @param fields Fields map.
+     * @return Whether meta is changed.
+     * @throws PortableException In case of error.
+     */
+    private static boolean checkMeta(int typeId, @Nullable PortableMetadata oldMeta,
+        PortableMetadata newMeta, @Nullable Map<String, String> fields) throws PortableException {
+        assert newMeta != null;
+
+        Map<String, String> oldFields = oldMeta != null ? ((PortableMetaDataImpl)oldMeta).fieldsMeta() : null;
+        Map<String, String> newFields = ((PortableMetaDataImpl)newMeta).fieldsMeta();
+
+        boolean changed = false;
+
+        if (oldMeta != null) {
+            if (!oldMeta.typeName().equals(newMeta.typeName())) {
+                throw new PortableException(
+                    "Two portable types have duplicate type ID [" +
+                        "typeId=" + typeId +
+                        ", typeName1=" + oldMeta.typeName() +
+                        ", typeName2=" + newMeta.typeName() +
+                        ']'
+                );
+            }
+
+            if (!F.eq(oldMeta.affinityKeyFieldName(), newMeta.affinityKeyFieldName())) {
+                throw new PortableException(
+                    "Portable type has different affinity key fields on different clients [" +
+                        "typeName=" + newMeta.typeName() +
+                        ", affKeyFieldName1=" + oldMeta.affinityKeyFieldName() +
+                        ", affKeyFieldName2=" + newMeta.affinityKeyFieldName() +
+                        ']'
+                );
+            }
+
+            if (fields != null)
+                fields.putAll(oldFields);
+        }
+        else
+            changed = true;
+
+        for (Map.Entry<String, String> e : newFields.entrySet()) {
+            String typeName = oldFields != null ? oldFields.get(e.getKey()) : null;
+
+            if (typeName != null) {
+                if (!typeName.equals(e.getValue())) {
+                    throw new PortableException(
+                        "Portable field has different types on different clients [" +
+                            "typeName=" + newMeta.typeName() +
+                            ", fieldName=" + e.getKey() +
+                            ", fieldTypeName1=" + typeName +
+                            ", fieldTypeName2=" + e.getValue() +
+                            ']'
+                    );
+                }
+            }
+            else {
+                if (fields != null)
+                    fields.put(e.getKey(), e.getValue());
+
+                changed = true;
+            }
+        }
+
+        return changed;
+    }
+
+    /**
+     */
+    private static class MetaDataProcessor implements
+        EntryProcessor<PortableMetaDataKey, PortableMetadata, PortableException>, Externalizable {
+        /** */
+        private static final long serialVersionUID = 0L;
+
+        /** */
+        private int typeId;
+
+        /** */
+        private PortableMetadata newMeta;
+
+        /**
+         * For {@link Externalizable}.
+         */
+        public MetaDataProcessor() {
+            // No-op.
+        }
+
+        /**
+         * @param typeId Type ID.
+         * @param newMeta New metadata.
+         */
+        private MetaDataProcessor(int typeId, PortableMetadata newMeta) {
+            assert newMeta != null;
+
+            this.typeId = typeId;
+            this.newMeta = newMeta;
+        }
+
+        /** {@inheritDoc} */
+        @Override public PortableException process(
+            MutableEntry<PortableMetaDataKey, PortableMetadata> entry,
+            Object... args) {
+            try {
+                PortableMetadata oldMeta = entry.getValue();
+
+                Map<String, String> fields = new HashMap<>();
+
+                if (checkMeta(typeId, oldMeta, newMeta, fields)) {
+                    PortableMetadata res = new PortableMetaDataImpl(newMeta.typeName(),
+                        fields,
+                        newMeta.affinityKeyFieldName());
+
+                    entry.setValue(res);
+
+                    return null;
+                }
+                else
+                    return null;
+            }
+            catch (PortableException e) {
+                return e;
+            }
+        }
+
+        /** {@inheritDoc} */
+        @Override public void writeExternal(ObjectOutput out) throws IOException {
+            out.writeInt(typeId);
+            out.writeObject(newMeta);
+        }
+
+        /** {@inheritDoc} */
+        @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
+            typeId = in.readInt();
+            newMeta = (PortableMetadata)in.readObject();
+        }
+
+        /** {@inheritDoc} */
+        @Override public String toString() {
+            return S.toString(MetaDataProcessor.class, this);
+        }
+    }
+
+    /**
+     *
+     */
+    class MetaDataEntryListener implements CacheEntryUpdatedListener<PortableMetaDataKey, PortableMetadata> {
+        /** {@inheritDoc} */
+        @Override public void onUpdated(
+            Iterable<CacheEntryEvent<? extends PortableMetaDataKey, ? extends PortableMetadata>> evts)
+            throws CacheEntryListenerException {
+            for (CacheEntryEvent<? extends PortableMetaDataKey, ? extends PortableMetadata> evt : evts) {
+                assert evt.getEventType() == EventType.CREATED || evt.getEventType() == EventType.UPDATED : evt;
+
+                PortableMetaDataKey key = evt.getKey();
+
+                final PortableMetadata newMeta = evt.getValue();
+
+                assert newMeta != null : evt;
+
+                addClientCacheMetaData(key, newMeta);
+            }
+        }
+
+        /** {@inheritDoc} */
+        @Override public String toString() {
+            return S.toString(MetaDataEntryListener.class, this);
+        }
+    }
+
+    /**
+     *
+     */
+    static class MetaDataEntryFilter implements CacheEntryEventSerializableFilter<Object, Object> {
+        /** */
+        private static final long serialVersionUID = 0L;
+
+        /** {@inheritDoc} */
+        @Override public boolean evaluate(CacheEntryEvent<?, ?> evt) throws CacheEntryListenerException {
+            return evt.getKey() instanceof PortableMetaDataKey;
+        }
+
+        /** {@inheritDoc} */
+        @Override public String toString() {
+            return S.toString(MetaDataEntryFilter.class, this);
+        }
+    }
+
+    /**
+     *
+     */
+    static class MetaDataPredicate implements IgniteBiPredicate<Object, Object> {
+        /** */
+        private static final long serialVersionUID = 0L;
+
+        /** {@inheritDoc} */
+        @Override public boolean apply(Object key, Object val) {
+            return key instanceof PortableMetaDataKey;
+        }
+
+        /** {@inheritDoc} */
+        @Override public String toString() {
+            return S.toString(MetaDataPredicate.class, this);
+        }
+    }
+}


[04/59] [abbrv] ignite git commit: ignite-1258: portable objects API support in Ignite

Posted by vk...@apache.org.
http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/java/org/apache/ignite/internal/portable/GridPortableMarshallerSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/portable/GridPortableMarshallerSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/portable/GridPortableMarshallerSelfTest.java
new file mode 100644
index 0000000..4af1d17
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/portable/GridPortableMarshallerSelfTest.java
@@ -0,0 +1,3691 @@
+/*
+ * 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.portable;
+
+import org.apache.ignite.*;
+import org.apache.ignite.internal.util.*;
+import org.apache.ignite.internal.util.lang.*;
+import org.apache.ignite.internal.util.typedef.*;
+import org.apache.ignite.internal.util.typedef.internal.*;
+import org.apache.ignite.marshaller.*;
+import org.apache.ignite.marshaller.portable.*;
+import org.apache.ignite.portable.*;
+import org.apache.ignite.testframework.*;
+import org.apache.ignite.testframework.junits.common.*;
+
+import com.sun.tools.jdi.*;
+import com.sun.tools.jdi.LinkedHashMap;
+import org.jsr166.*;
+import sun.misc.*;
+
+import java.lang.reflect.*;
+import java.math.*;
+import java.net.*;
+import java.sql.*;
+import java.util.*;
+import java.util.Date;
+import java.util.concurrent.*;
+
+import static org.apache.ignite.internal.portable.PortableThreadLocalMemoryAllocator.*;
+import static org.junit.Assert.*;
+
+/**
+ * Portable marshaller tests.
+ */
+@SuppressWarnings({"OverlyStrongTypeCast", "ArrayHashCode", "ConstantConditions"})
+public class GridPortableMarshallerSelfTest extends GridCommonAbstractTest {
+    /** */
+    private static final Unsafe UNSAFE = GridUnsafe.unsafe();
+
+    /** */
+    protected static final long BYTE_ARR_OFF = UNSAFE.arrayBaseOffset(byte[].class);
+
+    /** */
+    protected static final PortableMetaDataHandler META_HND = new PortableMetaDataHandler() {
+        @Override public void addMeta(int typeId, PortableMetadata meta) {
+            // No-op.
+        }
+
+        @Override public PortableMetadata metadata(int typeId) {
+            return null;
+        }
+    };
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testNull() throws Exception {
+        assertNull(marshalUnmarshal(null));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testByte() throws Exception {
+        assertEquals((byte)100, marshalUnmarshal((byte)100).byteValue());
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testShort() throws Exception {
+        assertEquals((short)100, marshalUnmarshal((short)100).shortValue());
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testInt() throws Exception {
+        assertEquals(100, marshalUnmarshal(100).intValue());
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testLong() throws Exception {
+        assertEquals(100L, marshalUnmarshal(100L).longValue());
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testFloat() throws Exception {
+        assertEquals(100.001f, marshalUnmarshal(100.001f).floatValue(), 0);
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testDouble() throws Exception {
+        assertEquals(100.001d, marshalUnmarshal(100.001d).doubleValue(), 0);
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testChar() throws Exception {
+        assertEquals((char)100, marshalUnmarshal((char)100).charValue());
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testBoolean() throws Exception {
+        assertEquals(true, marshalUnmarshal(true).booleanValue());
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testDecimal() throws Exception {
+        BigDecimal val;
+
+        assertEquals((val = BigDecimal.ZERO), marshalUnmarshal(val));
+        assertEquals((val = BigDecimal.valueOf(Long.MAX_VALUE, 0)), marshalUnmarshal(val));
+        assertEquals((val = BigDecimal.valueOf(Long.MIN_VALUE, 0)), marshalUnmarshal(val));
+        assertEquals((val = BigDecimal.valueOf(Long.MAX_VALUE, 8)), marshalUnmarshal(val));
+        assertEquals((val = BigDecimal.valueOf(Long.MIN_VALUE, 8)), marshalUnmarshal(val));
+
+        assertEquals((val = new BigDecimal(new BigInteger("-79228162514264337593543950336"))), marshalUnmarshal(val));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testString() throws Exception {
+        assertEquals("str", marshalUnmarshal("str"));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testUuid() throws Exception {
+        UUID uuid = UUID.randomUUID();
+
+        assertEquals(uuid, marshalUnmarshal(uuid));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testDate() throws Exception {
+        Date date = new Date();
+
+        Date val = marshalUnmarshal(date);
+
+        assertEquals(date, val);
+        assertEquals(Timestamp.class, val.getClass()); // With default configuration should unmarshal as Timestamp.
+
+        PortableMarshaller marsh = new PortableMarshaller();
+
+        marsh.setUseTimestamp(false);
+
+        val = marshalUnmarshal(date, marsh);
+
+        assertEquals(date, val);
+        assertEquals(Date.class, val.getClass());
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testTimestamp() throws Exception {
+        Timestamp ts = new Timestamp(System.currentTimeMillis());
+
+        ts.setNanos(999999999);
+
+        assertEquals(ts, marshalUnmarshal(ts));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testByteArray() throws Exception {
+        byte[] arr = new byte[] {10, 20, 30};
+
+        assertArrayEquals(arr, marshalUnmarshal(arr));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testShortArray() throws Exception {
+        short[] arr = new short[] {10, 20, 30};
+
+        assertArrayEquals(arr, marshalUnmarshal(arr));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testIntArray() throws Exception {
+        int[] arr = new int[] {10, 20, 30};
+
+        assertArrayEquals(arr, marshalUnmarshal(arr));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testLongArray() throws Exception {
+        long[] arr = new long[] {10, 20, 30};
+
+        assertArrayEquals(arr, marshalUnmarshal(arr));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testFloatArray() throws Exception {
+        float[] arr = new float[] {10.1f, 20.1f, 30.1f};
+
+        assertArrayEquals(arr, marshalUnmarshal(arr), 0);
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testDoubleArray() throws Exception {
+        double[] arr = new double[] {10.1d, 20.1d, 30.1d};
+
+        assertArrayEquals(arr, marshalUnmarshal(arr), 0);
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testCharArray() throws Exception {
+        char[] arr = new char[] {10, 20, 30};
+
+        assertArrayEquals(arr, marshalUnmarshal(arr));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testBooleanArray() throws Exception {
+        boolean[] arr = new boolean[] {true, false, true};
+
+        assertBooleanArrayEquals(arr, marshalUnmarshal(arr));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testDecimalArray() throws Exception {
+        BigDecimal[] arr = new BigDecimal[] { BigDecimal.ZERO, BigDecimal.ONE, BigDecimal.TEN } ;
+
+        assertArrayEquals(arr, marshalUnmarshal(arr));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testStringArray() throws Exception {
+        String[] arr = new String[] {"str1", "str2", "str3"};
+
+        assertArrayEquals(arr, marshalUnmarshal(arr));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testUuidArray() throws Exception {
+        UUID[] arr = new UUID[] {UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID()};
+
+        assertArrayEquals(arr, marshalUnmarshal(arr));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testDateArray() throws Exception {
+        Date[] arr = new Date[] {new Date(11111), new Date(22222), new Date(33333)};
+
+        assertArrayEquals(arr, marshalUnmarshal(arr));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testObjectArray() throws Exception {
+        Object[] arr = new Object[] {1, 2, 3};
+
+        assertArrayEquals(arr, marshalUnmarshal(arr));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testCollection() throws Exception {
+        testCollection(new ArrayList<Integer>(3));
+        testCollection(new LinkedHashSet<Integer>());
+        testCollection(new HashSet<Integer>());
+        testCollection(new TreeSet<Integer>());
+        testCollection(new ConcurrentSkipListSet<Integer>());
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    private void testCollection(Collection<Integer> col) throws Exception {
+        col.add(1);
+        col.add(2);
+        col.add(3);
+
+        assertEquals(col, marshalUnmarshal(col));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testMap() throws Exception {
+        testMap(new HashMap<Integer, String>());
+        testMap(new LinkedHashMap());
+        testMap(new TreeMap<Integer, String>());
+        testMap(new ConcurrentHashMap8<Integer, String>());
+        testMap(new ConcurrentHashMap<Integer, String>());
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    private void testMap(Map<Integer, String> map) throws Exception {
+        map.put(1, "str1");
+        map.put(2, "str2");
+        map.put(3, "str3");
+
+        assertEquals(map, marshalUnmarshal(map));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testMapEntry() throws Exception {
+        Map.Entry<Integer, String> e = new GridMapEntry<>(1, "str1");
+
+        assertEquals(e, marshalUnmarshal(e));
+
+        Map<Integer, String> map = new HashMap<>(1);
+
+        map.put(2, "str2");
+
+        e = F.firstEntry(map);
+
+        Map.Entry<Integer, String> e0 = marshalUnmarshal(e);
+
+        assertEquals(2, e0.getKey().intValue());
+        assertEquals("str2", e0.getValue());
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testPortableObject() throws Exception {
+        PortableMarshaller marsh = new PortableMarshaller();
+
+        marsh.setTypeConfigurations(Arrays.asList(new PortableTypeConfiguration(SimpleObject.class.getName())));
+
+        SimpleObject obj = simpleObject();
+
+        PortableObject po = marshal(obj, marsh);
+
+        PortableObject po0 = marshalUnmarshal(po, marsh);
+
+        assertTrue(po.hasField("b"));
+        assertTrue(po.hasField("s"));
+        assertTrue(po.hasField("i"));
+        assertTrue(po.hasField("l"));
+        assertTrue(po.hasField("f"));
+        assertTrue(po.hasField("d"));
+        assertTrue(po.hasField("c"));
+        assertTrue(po.hasField("bool"));
+
+        assertFalse(po.hasField("no_such_field"));
+
+        assertEquals(obj, po.deserialize());
+        assertEquals(obj, po0.deserialize());
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testEnum() throws Exception {
+        PortableMarshaller marsh = new PortableMarshaller();
+
+        marsh.setClassNames(Arrays.asList(TestEnum.class.getName()));
+
+        assertEquals(TestEnum.B, marshalUnmarshal(TestEnum.B, marsh));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testUseTimestampFlag() throws Exception {
+        PortableTypeConfiguration cfg1 = new PortableTypeConfiguration(DateClass1.class.getName());
+
+        PortableTypeConfiguration cfg2 = new PortableTypeConfiguration(DateClass2.class.getName());
+
+        cfg2.setUseTimestamp(false);
+
+        PortableMarshaller marsh = new PortableMarshaller();
+
+        marsh.setTypeConfigurations(Arrays.asList(cfg1, cfg2));
+
+        Date date = new Date();
+        Timestamp ts = new Timestamp(System.currentTimeMillis());
+
+        DateClass1 obj1 = new DateClass1();
+        obj1.date = date;
+        obj1.ts = ts;
+
+        DateClass2 obj2 = new DateClass2();
+        obj2.date = date;
+        obj2.ts = ts;
+
+        PortableObject po1 = marshal(obj1, marsh);
+
+        assertEquals(date, po1.field("date"));
+        assertEquals(Timestamp.class, po1.field("date").getClass());
+        assertEquals(ts, po1.field("ts"));
+
+        PortableObject po2 = marshal(obj2, marsh);
+
+        assertEquals(date, po2.field("date"));
+        assertEquals(Date.class, po2.field("date").getClass());
+        assertEquals(new Date(ts.getTime()), po2.field("ts"));
+        assertEquals(Date.class, po2.field("ts").getClass());
+
+        obj1 = po1.deserialize();
+        assertEquals(date, obj1.date);
+        assertEquals(Date.class, obj1.date.getClass());
+        assertEquals(ts, obj1.ts);
+
+        obj2 = po2.deserialize();
+        assertEquals(date, obj2.date);
+        assertEquals(Date.class, obj2.date.getClass());
+        assertEquals(ts, obj2.ts);
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testSimpleObject() throws Exception {
+        PortableMarshaller marsh = new PortableMarshaller();
+
+        marsh.setTypeConfigurations(Arrays.asList(
+            new PortableTypeConfiguration(SimpleObject.class.getName())
+        ));
+
+        SimpleObject obj = simpleObject();
+
+        PortableObject po = marshal(obj, marsh);
+
+        assertEquals(obj.hashCode(), po.hashCode());
+
+        assertEquals(obj, po.deserialize());
+
+        assertEquals(obj.b, (byte)po.field("b"));
+        assertEquals(obj.s, (short)po.field("s"));
+        assertEquals(obj.i, (int)po.field("i"));
+        assertEquals(obj.l, (long)po.field("l"));
+        assertEquals(obj.f, (float)po.field("f"), 0);
+        assertEquals(obj.d, (double)po.field("d"), 0);
+        assertEquals(obj.c, (char)po.field("c"));
+        assertEquals(obj.bool, (boolean)po.field("bool"));
+        assertEquals(obj.str, po.field("str"));
+        assertEquals(obj.uuid, po.field("uuid"));
+        assertEquals(obj.date, po.field("date"));
+        assertEquals(Date.class, obj.date.getClass());
+        assertEquals(obj.ts, po.field("ts"));
+        assertArrayEquals(obj.bArr, (byte[])po.field("bArr"));
+        assertArrayEquals(obj.sArr, (short[])po.field("sArr"));
+        assertArrayEquals(obj.iArr, (int[])po.field("iArr"));
+        assertArrayEquals(obj.lArr, (long[])po.field("lArr"));
+        assertArrayEquals(obj.fArr, (float[])po.field("fArr"), 0);
+        assertArrayEquals(obj.dArr, (double[])po.field("dArr"), 0);
+        assertArrayEquals(obj.cArr, (char[])po.field("cArr"));
+        assertBooleanArrayEquals(obj.boolArr, (boolean[])po.field("boolArr"));
+        assertArrayEquals(obj.strArr, (String[])po.field("strArr"));
+        assertArrayEquals(obj.uuidArr, (UUID[])po.field("uuidArr"));
+        assertArrayEquals(obj.dateArr, (Date[])po.field("dateArr"));
+        assertArrayEquals(obj.objArr, (Object[])po.field("objArr"));
+        assertEquals(obj.col, po.field("col"));
+        assertEquals(obj.map, po.field("map"));
+        assertEquals(new Integer(obj.enumVal.ordinal()), new Integer(((Enum<?>)po.field("enumVal")).ordinal()));
+        assertArrayEquals(ordinals(obj.enumArr), ordinals((Enum<?>[])po.field("enumArr")));
+        assertNull(po.field("unknown"));
+
+        PortableObject innerPo = po.field("inner");
+
+        assertEquals(obj.inner, innerPo.deserialize());
+
+        assertEquals(obj.inner.b, (byte)innerPo.field("b"));
+        assertEquals(obj.inner.s, (short)innerPo.field("s"));
+        assertEquals(obj.inner.i, (int)innerPo.field("i"));
+        assertEquals(obj.inner.l, (long)innerPo.field("l"));
+        assertEquals(obj.inner.f, (float)innerPo.field("f"), 0);
+        assertEquals(obj.inner.d, (double)innerPo.field("d"), 0);
+        assertEquals(obj.inner.c, (char)innerPo.field("c"));
+        assertEquals(obj.inner.bool, (boolean)innerPo.field("bool"));
+        assertEquals(obj.inner.str, innerPo.field("str"));
+        assertEquals(obj.inner.uuid, innerPo.field("uuid"));
+        assertEquals(obj.inner.date, innerPo.field("date"));
+        assertEquals(Date.class, obj.inner.date.getClass());
+        assertEquals(obj.inner.ts, innerPo.field("ts"));
+        assertArrayEquals(obj.inner.bArr, (byte[])innerPo.field("bArr"));
+        assertArrayEquals(obj.inner.sArr, (short[])innerPo.field("sArr"));
+        assertArrayEquals(obj.inner.iArr, (int[])innerPo.field("iArr"));
+        assertArrayEquals(obj.inner.lArr, (long[])innerPo.field("lArr"));
+        assertArrayEquals(obj.inner.fArr, (float[])innerPo.field("fArr"), 0);
+        assertArrayEquals(obj.inner.dArr, (double[])innerPo.field("dArr"), 0);
+        assertArrayEquals(obj.inner.cArr, (char[])innerPo.field("cArr"));
+        assertBooleanArrayEquals(obj.inner.boolArr, (boolean[])innerPo.field("boolArr"));
+        assertArrayEquals(obj.inner.strArr, (String[])innerPo.field("strArr"));
+        assertArrayEquals(obj.inner.uuidArr, (UUID[])innerPo.field("uuidArr"));
+        assertArrayEquals(obj.inner.dateArr, (Date[])innerPo.field("dateArr"));
+        assertArrayEquals(obj.inner.objArr, (Object[])innerPo.field("objArr"));
+        assertEquals(obj.inner.col, innerPo.field("col"));
+        assertEquals(obj.inner.map, innerPo.field("map"));
+        assertEquals(new Integer(obj.inner.enumVal.ordinal()),
+            new Integer(((Enum<?>)innerPo.field("enumVal")).ordinal()));
+        assertArrayEquals(ordinals(obj.inner.enumArr), ordinals((Enum<?>[])innerPo.field("enumArr")));
+        assertNull(innerPo.field("inner"));
+        assertNull(innerPo.field("unknown"));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testPortable() throws Exception {
+        PortableMarshaller marsh = new PortableMarshaller();
+
+        marsh.setTypeConfigurations(Arrays.asList(
+            new PortableTypeConfiguration(SimpleObject.class.getName()),
+            new PortableTypeConfiguration(TestPortableObject.class.getName())
+        ));
+
+        TestPortableObject obj = portableObject();
+
+        PortableObject po = marshal(obj, marsh);
+
+        assertEquals(obj.hashCode(), po.hashCode());
+
+        assertEquals(obj, po.deserialize());
+
+        assertEquals(obj.b, (byte)po.field("_b"));
+        assertEquals(obj.s, (short)po.field("_s"));
+        assertEquals(obj.i, (int)po.field("_i"));
+        assertEquals(obj.l, (long)po.field("_l"));
+        assertEquals(obj.f, (float)po.field("_f"), 0);
+        assertEquals(obj.d, (double)po.field("_d"), 0);
+        assertEquals(obj.c, (char)po.field("_c"));
+        assertEquals(obj.bool, (boolean)po.field("_bool"));
+        assertEquals(obj.str, po.field("_str"));
+        assertEquals(obj.uuid, po.field("_uuid"));
+        assertEquals(obj.date, po.field("_date"));
+        assertEquals(obj.ts, po.field("_ts"));
+        assertArrayEquals(obj.bArr, (byte[])po.field("_bArr"));
+        assertArrayEquals(obj.sArr, (short[])po.field("_sArr"));
+        assertArrayEquals(obj.iArr, (int[])po.field("_iArr"));
+        assertArrayEquals(obj.lArr, (long[])po.field("_lArr"));
+        assertArrayEquals(obj.fArr, (float[])po.field("_fArr"), 0);
+        assertArrayEquals(obj.dArr, (double[])po.field("_dArr"), 0);
+        assertArrayEquals(obj.cArr, (char[])po.field("_cArr"));
+        assertBooleanArrayEquals(obj.boolArr, (boolean[])po.field("_boolArr"));
+        assertArrayEquals(obj.strArr, (String[])po.field("_strArr"));
+        assertArrayEquals(obj.uuidArr, (UUID[])po.field("_uuidArr"));
+        assertArrayEquals(obj.dateArr, (Date[])po.field("_dateArr"));
+        assertArrayEquals(obj.objArr, (Object[])po.field("_objArr"));
+        assertEquals(obj.col, po.field("_col"));
+        assertEquals(obj.map, po.field("_map"));
+        assertEquals(new Integer(obj.enumVal.ordinal()), new Integer(((Enum<?>)po.field("_enumVal")).ordinal()));
+        assertArrayEquals(ordinals(obj.enumArr), ordinals((Enum<?>[])po.field("_enumArr")));
+        assertNull(po.field("unknown"));
+
+        PortableObject simplePo = po.field("_simple");
+
+        assertEquals(obj.simple, simplePo.deserialize());
+
+        assertEquals(obj.simple.b, (byte)simplePo.field("b"));
+        assertEquals(obj.simple.s, (short)simplePo.field("s"));
+        assertEquals(obj.simple.i, (int)simplePo.field("i"));
+        assertEquals(obj.simple.l, (long)simplePo.field("l"));
+        assertEquals(obj.simple.f, (float)simplePo.field("f"), 0);
+        assertEquals(obj.simple.d, (double)simplePo.field("d"), 0);
+        assertEquals(obj.simple.c, (char)simplePo.field("c"));
+        assertEquals(obj.simple.bool, (boolean)simplePo.field("bool"));
+        assertEquals(obj.simple.str, simplePo.field("str"));
+        assertEquals(obj.simple.uuid, simplePo.field("uuid"));
+        assertEquals(obj.simple.date, simplePo.field("date"));
+        assertEquals(Date.class, obj.simple.date.getClass());
+        assertEquals(obj.simple.ts, simplePo.field("ts"));
+        assertArrayEquals(obj.simple.bArr, (byte[])simplePo.field("bArr"));
+        assertArrayEquals(obj.simple.sArr, (short[])simplePo.field("sArr"));
+        assertArrayEquals(obj.simple.iArr, (int[])simplePo.field("iArr"));
+        assertArrayEquals(obj.simple.lArr, (long[])simplePo.field("lArr"));
+        assertArrayEquals(obj.simple.fArr, (float[])simplePo.field("fArr"), 0);
+        assertArrayEquals(obj.simple.dArr, (double[])simplePo.field("dArr"), 0);
+        assertArrayEquals(obj.simple.cArr, (char[])simplePo.field("cArr"));
+        assertBooleanArrayEquals(obj.simple.boolArr, (boolean[])simplePo.field("boolArr"));
+        assertArrayEquals(obj.simple.strArr, (String[])simplePo.field("strArr"));
+        assertArrayEquals(obj.simple.uuidArr, (UUID[])simplePo.field("uuidArr"));
+        assertArrayEquals(obj.simple.dateArr, (Date[])simplePo.field("dateArr"));
+        assertArrayEquals(obj.simple.objArr, (Object[])simplePo.field("objArr"));
+        assertEquals(obj.simple.col, simplePo.field("col"));
+        assertEquals(obj.simple.map, simplePo.field("map"));
+        assertEquals(new Integer(obj.simple.enumVal.ordinal()),
+            new Integer(((Enum<?>)simplePo.field("enumVal")).ordinal()));
+        assertArrayEquals(ordinals(obj.simple.enumArr), ordinals((Enum<?>[])simplePo.field("enumArr")));
+        assertNull(simplePo.field("simple"));
+        assertNull(simplePo.field("portable"));
+        assertNull(simplePo.field("unknown"));
+
+        PortableObject portablePo = po.field("_portable");
+
+        assertEquals(obj.portable, portablePo.deserialize());
+
+        assertEquals(obj.portable.b, (byte)portablePo.field("_b"));
+        assertEquals(obj.portable.s, (short)portablePo.field("_s"));
+        assertEquals(obj.portable.i, (int)portablePo.field("_i"));
+        assertEquals(obj.portable.l, (long)portablePo.field("_l"));
+        assertEquals(obj.portable.f, (float)portablePo.field("_f"), 0);
+        assertEquals(obj.portable.d, (double)portablePo.field("_d"), 0);
+        assertEquals(obj.portable.c, (char)portablePo.field("_c"));
+        assertEquals(obj.portable.bool, (boolean)portablePo.field("_bool"));
+        assertEquals(obj.portable.str, portablePo.field("_str"));
+        assertEquals(obj.portable.uuid, portablePo.field("_uuid"));
+        assertEquals(obj.portable.date, portablePo.field("_date"));
+        assertEquals(obj.portable.ts, portablePo.field("_ts"));
+        assertArrayEquals(obj.portable.bArr, (byte[])portablePo.field("_bArr"));
+        assertArrayEquals(obj.portable.sArr, (short[])portablePo.field("_sArr"));
+        assertArrayEquals(obj.portable.iArr, (int[])portablePo.field("_iArr"));
+        assertArrayEquals(obj.portable.lArr, (long[])portablePo.field("_lArr"));
+        assertArrayEquals(obj.portable.fArr, (float[])portablePo.field("_fArr"), 0);
+        assertArrayEquals(obj.portable.dArr, (double[])portablePo.field("_dArr"), 0);
+        assertArrayEquals(obj.portable.cArr, (char[])portablePo.field("_cArr"));
+        assertBooleanArrayEquals(obj.portable.boolArr, (boolean[])portablePo.field("_boolArr"));
+        assertArrayEquals(obj.portable.strArr, (String[])portablePo.field("_strArr"));
+        assertArrayEquals(obj.portable.uuidArr, (UUID[])portablePo.field("_uuidArr"));
+        assertArrayEquals(obj.portable.dateArr, (Date[])portablePo.field("_dateArr"));
+        assertArrayEquals(obj.portable.objArr, (Object[])portablePo.field("_objArr"));
+        assertEquals(obj.portable.col, portablePo.field("_col"));
+        assertEquals(obj.portable.map, portablePo.field("_map"));
+        assertEquals(new Integer(obj.portable.enumVal.ordinal()),
+            new Integer(((Enum<?>)portablePo.field("_enumVal")).ordinal()));
+        assertArrayEquals(ordinals(obj.portable.enumArr), ordinals((Enum<?>[])portablePo.field("_enumArr")));
+        assertNull(portablePo.field("_simple"));
+        assertNull(portablePo.field("_portable"));
+        assertNull(portablePo.field("unknown"));
+    }
+
+    /**
+     * @param obj Simple object.
+     * @param po Portable object.
+     */
+    private void checkSimpleObjectData(SimpleObject obj, PortableObject po) {
+        assertEquals(obj.b, (byte)po.field("b"));
+        assertEquals(obj.s, (short)po.field("s"));
+        assertEquals(obj.i, (int)po.field("i"));
+        assertEquals(obj.l, (long)po.field("l"));
+        assertEquals(obj.f, (float)po.field("f"), 0);
+        assertEquals(obj.d, (double)po.field("d"), 0);
+        assertEquals(obj.c, (char)po.field("c"));
+        assertEquals(obj.bool, (boolean)po.field("bool"));
+        assertEquals(obj.str, po.field("str"));
+        assertEquals(obj.uuid, po.field("uuid"));
+        assertEquals(obj.date, po.field("date"));
+        assertEquals(Date.class, obj.date.getClass());
+        assertEquals(obj.ts, po.field("ts"));
+        assertArrayEquals(obj.bArr, (byte[])po.field("bArr"));
+        assertArrayEquals(obj.sArr, (short[])po.field("sArr"));
+        assertArrayEquals(obj.iArr, (int[])po.field("iArr"));
+        assertArrayEquals(obj.lArr, (long[])po.field("lArr"));
+        assertArrayEquals(obj.fArr, (float[])po.field("fArr"), 0);
+        assertArrayEquals(obj.dArr, (double[])po.field("dArr"), 0);
+        assertArrayEquals(obj.cArr, (char[])po.field("cArr"));
+        assertBooleanArrayEquals(obj.boolArr, (boolean[])po.field("boolArr"));
+        assertArrayEquals(obj.strArr, (String[])po.field("strArr"));
+        assertArrayEquals(obj.uuidArr, (UUID[])po.field("uuidArr"));
+        assertArrayEquals(obj.dateArr, (Date[])po.field("dateArr"));
+        assertArrayEquals(obj.objArr, (Object[])po.field("objArr"));
+        assertEquals(obj.col, po.field("col"));
+        assertEquals(obj.map, po.field("map"));
+        assertEquals(new Integer(obj.enumVal.ordinal()), new Integer(((Enum<?>)po.field("enumVal")).ordinal()));
+        assertArrayEquals(ordinals(obj.enumArr), ordinals((Enum<?>[])po.field("enumArr")));
+        assertNull(po.field("unknown"));
+
+        assertEquals(obj, po.deserialize());
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testInvalidClass() throws Exception {
+        byte[] arr = new byte[20];
+
+        arr[0] = 103;
+
+        U.intToBytes(Integer.reverseBytes(11111), arr, 2);
+
+        final PortableObject po = new PortableObjectImpl(initPortableContext(new PortableMarshaller()), arr, 0);
+
+        GridTestUtils.assertThrows(log, new Callable<Object>() {
+                                       @Override public Object call() throws Exception {
+                                           po.deserialize();
+
+                                           return null;
+                                       }
+                                   }, PortableInvalidClassException.class, "Unknown type ID: 11111"
+        );
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testClassWithoutPublicConstructor() throws Exception {
+        PortableMarshaller marsh = new PortableMarshaller();
+
+        marsh.setTypeConfigurations(Arrays.asList(
+                                        new PortableTypeConfiguration(NoPublicConstructor.class.getName()),
+                                        new PortableTypeConfiguration(NoPublicDefaultConstructor.class.getName()),
+                                        new PortableTypeConfiguration(ProtectedConstructor.class.getName()))
+        );
+
+        initPortableContext(marsh);
+
+        NoPublicConstructor npc = new NoPublicConstructor();
+        PortableObject npc2 = marshal(npc, marsh);
+
+        assertEquals("test", npc2.<NoPublicConstructor>deserialize().val);
+
+        NoPublicDefaultConstructor npdc = new NoPublicDefaultConstructor(239);
+        PortableObject npdc2 = marshal(npdc, marsh);
+
+        assertEquals(239, npdc2.<NoPublicDefaultConstructor>deserialize().val);
+
+        ProtectedConstructor pc = new ProtectedConstructor();
+        PortableObject pc2 = marshal(pc, marsh);
+
+        assertEquals(ProtectedConstructor.class, pc2.<ProtectedConstructor>deserialize().getClass());
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testCustomSerializer() throws Exception {
+        PortableMarshaller marsh = new PortableMarshaller();
+
+        PortableTypeConfiguration type =
+            new PortableTypeConfiguration(CustomSerializedObject1.class.getName());
+
+        type.setSerializer(new CustomSerializer1());
+
+        marsh.setTypeConfigurations(Arrays.asList(type));
+
+        CustomSerializedObject1 obj1 = new CustomSerializedObject1(10);
+
+        PortableObject po1 = marshal(obj1, marsh);
+
+        assertEquals(20, po1.<CustomSerializedObject1>deserialize().val);
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testCustomSerializerWithGlobal() throws Exception {
+        PortableMarshaller marsh = new PortableMarshaller();
+
+        marsh.setSerializer(new CustomSerializer1());
+
+        PortableTypeConfiguration type1 =
+            new PortableTypeConfiguration(CustomSerializedObject1.class.getName());
+        PortableTypeConfiguration type2 =
+            new PortableTypeConfiguration(CustomSerializedObject2.class.getName());
+
+        type2.setSerializer(new CustomSerializer2());
+
+        marsh.setTypeConfigurations(Arrays.asList(type1, type2));
+
+        CustomSerializedObject1 obj1 = new CustomSerializedObject1(10);
+
+        PortableObject po1 = marshal(obj1, marsh);
+
+        assertEquals(20, po1.<CustomSerializedObject1>deserialize().val);
+
+        CustomSerializedObject2 obj2 = new CustomSerializedObject2(10);
+
+        PortableObject po2 = marshal(obj2, marsh);
+
+        assertEquals(30, po2.<CustomSerializedObject2>deserialize().val);
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testCustomIdMapper() throws Exception {
+        PortableMarshaller marsh = new PortableMarshaller();
+
+        PortableTypeConfiguration type =
+            new PortableTypeConfiguration(CustomMappedObject1.class.getName());
+
+        type.setIdMapper(new PortableIdMapper() {
+            @Override public int typeId(String clsName) {
+                return 11111;
+            }
+
+            @Override public int fieldId(int typeId, String fieldName) {
+                assert typeId == 11111;
+
+                if ("val1".equals(fieldName))
+                    return 22222;
+                else if ("val2".equals(fieldName))
+                    return 33333;
+
+                assert false : "Unknown field: " + fieldName;
+
+                return 0;
+            }
+        });
+
+        marsh.setTypeConfigurations(Arrays.asList(type));
+
+        CustomMappedObject1 obj1 = new CustomMappedObject1(10, "str");
+
+        PortableObject po1 = marshal(obj1, marsh);
+
+        assertEquals(11111, po1.typeId());
+        assertEquals(22222, intFromPortable(po1, 18));
+        assertEquals(33333, intFromPortable(po1, 31));
+
+        assertEquals(10, po1.<CustomMappedObject1>deserialize().val1);
+        assertEquals("str", po1.<CustomMappedObject1>deserialize().val2);
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testCustomIdMapperWithGlobal() throws Exception {
+        PortableMarshaller marsh = new PortableMarshaller();
+
+        marsh.setIdMapper(new PortableIdMapper() {
+            @Override public int typeId(String clsName) {
+                return 11111;
+            }
+
+            @Override public int fieldId(int typeId, String fieldName) {
+                assert typeId == 11111;
+
+                if ("val1".equals(fieldName)) return 22222;
+                else if ("val2".equals(fieldName)) return 33333;
+
+                assert false : "Unknown field: " + fieldName;
+
+                return 0;
+            }
+        });
+
+        PortableTypeConfiguration type1 =
+            new PortableTypeConfiguration(CustomMappedObject1.class.getName());
+        PortableTypeConfiguration type2 =
+            new PortableTypeConfiguration(CustomMappedObject2.class.getName());
+
+        type2.setIdMapper(new PortableIdMapper() {
+            @Override public int typeId(String clsName) {
+                return 44444;
+            }
+
+            @Override public int fieldId(int typeId, String fieldName) {
+                assert typeId == 44444;
+
+                if ("val1".equals(fieldName)) return 55555;
+                else if ("val2".equals(fieldName)) return 66666;
+
+                assert false : "Unknown field: " + fieldName;
+
+                return 0;
+            }
+        });
+
+        marsh.setTypeConfigurations(Arrays.asList(type1, type2));
+
+        CustomMappedObject1 obj1 = new CustomMappedObject1(10, "str1");
+
+        PortableObject po1 = marshal(obj1, marsh);
+
+        assertEquals(11111, po1.typeId());
+        assertEquals(22222, intFromPortable(po1, 18));
+        assertEquals(33333, intFromPortable(po1, 31));
+
+        assertEquals(10, po1.<CustomMappedObject1>deserialize().val1);
+        assertEquals("str1", po1.<CustomMappedObject1>deserialize().val2);
+
+        CustomMappedObject2 obj2 = new CustomMappedObject2(20, "str2");
+
+        PortableObject po2 = marshal(obj2, marsh);
+
+        assertEquals(44444, po2.typeId());
+        assertEquals(55555, intFromPortable(po2, 18));
+        assertEquals(66666, intFromPortable(po2, 31));
+
+        assertEquals(20, po2.<CustomMappedObject2>deserialize().val1);
+        assertEquals("str2", po2.<CustomMappedObject2>deserialize().val2);
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testDynamicObject() throws Exception {
+        PortableMarshaller marsh = new PortableMarshaller();
+
+        marsh.setTypeConfigurations(Arrays.asList(
+            new PortableTypeConfiguration(DynamicObject.class.getName())
+        ));
+
+        PortableObject po1 = marshal(new DynamicObject(0, 10, 20, 30), marsh);
+
+        assertEquals(new Integer(10), po1.field("val1"));
+        assertEquals(null, po1.field("val2"));
+        assertEquals(null, po1.field("val3"));
+
+        DynamicObject do1 = po1.deserialize();
+
+        assertEquals(10, do1.val1);
+        assertEquals(0, do1.val2);
+        assertEquals(0, do1.val3);
+
+        PortableObject po2 = marshal(new DynamicObject(1, 10, 20, 30), marsh);
+
+        assertEquals(new Integer(10), po2.field("val1"));
+        assertEquals(new Integer(20), po2.field("val2"));
+        assertEquals(null, po2.field("val3"));
+
+        DynamicObject do2 = po2.deserialize();
+
+        assertEquals(10, do2.val1);
+        assertEquals(20, do2.val2);
+        assertEquals(0, do2.val3);
+
+        PortableObject po3 = marshal(new DynamicObject(2, 10, 20, 30), marsh);
+
+        assertEquals(new Integer(10), po3.field("val1"));
+        assertEquals(new Integer(20), po3.field("val2"));
+        assertEquals(new Integer(30), po3.field("val3"));
+
+        DynamicObject do3 = po3.deserialize();
+
+        assertEquals(10, do3.val1);
+        assertEquals(20, do3.val2);
+        assertEquals(30, do3.val3);
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testCycleLink() throws Exception {
+        PortableMarshaller marsh = new PortableMarshaller();
+
+        marsh.setTypeConfigurations(Arrays.asList(
+            new PortableTypeConfiguration(CycleLinkObject.class.getName())
+        ));
+
+        CycleLinkObject obj = new CycleLinkObject();
+
+        obj.self = obj;
+
+        PortableObject po = marshal(obj, marsh);
+
+        CycleLinkObject obj0 = po.deserialize();
+
+        assert obj0.self == obj0;
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testDetached() throws Exception {
+        PortableMarshaller marsh = new PortableMarshaller();
+
+        marsh.setTypeConfigurations(Arrays.asList(
+            new PortableTypeConfiguration(DetachedTestObject.class.getName()),
+            new PortableTypeConfiguration(DetachedInnerTestObject.class.getName())
+        ));
+
+        UUID id = UUID.randomUUID();
+
+        DetachedTestObject obj = marshal(new DetachedTestObject(
+            new DetachedInnerTestObject(null, id)), marsh).deserialize();
+
+        assertEquals(id, obj.inner1.id);
+        assertEquals(id, obj.inner4.id);
+
+        assert obj.inner1 == obj.inner4;
+
+        PortableObjectImpl innerPo = (PortableObjectImpl)obj.inner2;
+
+        assert innerPo.detached();
+
+        DetachedInnerTestObject inner = innerPo.deserialize();
+
+        assertEquals(id, inner.id);
+
+        PortableObjectImpl detachedPo = (PortableObjectImpl)innerPo.detach();
+
+        assert detachedPo.detached();
+
+        inner = detachedPo.deserialize();
+
+        assertEquals(id, inner.id);
+
+        innerPo = (PortableObjectImpl)obj.inner3;
+
+        assert innerPo.detached();
+
+        inner = innerPo.deserialize();
+
+        assertEquals(id, inner.id);
+        assertNotNull(inner.inner);
+
+        detachedPo = (PortableObjectImpl)innerPo.detach();
+
+        assert detachedPo.detached();
+
+        inner = innerPo.deserialize();
+
+        assertEquals(id, inner.id);
+        assertNotNull(inner.inner);
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testCollectionFields() throws Exception {
+        PortableMarshaller marsh = new PortableMarshaller();
+
+        marsh.setTypeConfigurations(Arrays.asList(
+            new PortableTypeConfiguration(CollectionFieldsObject.class.getName()),
+            new PortableTypeConfiguration(Key.class.getName()),
+            new PortableTypeConfiguration(Value.class.getName())
+        ));
+
+        Object[] arr = new Object[] {new Value(1), new Value(2), new Value(3)};
+        Collection<Value> col = Arrays.asList(new Value(4), new Value(5), new Value(6));
+        Map<Key, Value> map = F.asMap(new Key(10), new Value(10), new Key(20), new Value(20), new Key(30), new Value(30));
+
+        CollectionFieldsObject obj = new CollectionFieldsObject(arr, col, map);
+
+        PortableObject po = marshal(obj, marsh);
+
+        Object[] arr0 = po.field("arr");
+
+        assertEquals(3, arr0.length);
+
+        int i = 1;
+
+        for (Object valPo : arr0)
+            assertEquals(i++, ((PortableObject)valPo).<Value>deserialize().val);
+
+        Collection<PortableObject> col0 = po.field("col");
+
+        i = 4;
+
+        for (PortableObject valPo : col0)
+            assertEquals(i++, valPo.<Value>deserialize().val);
+
+        Map<PortableObject, PortableObject> map0 = po.field("map");
+
+        for (Map.Entry<PortableObject, PortableObject> e : map0.entrySet())
+            assertEquals(e.getKey().<Key>deserialize().key, e.getValue().<Value>deserialize().val);
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testDefaultMapping() throws Exception {
+        PortableMarshaller marsh1 = new PortableMarshaller();
+
+        PortableTypeConfiguration customMappingType =
+            new PortableTypeConfiguration(TestPortableObject.class.getName());
+
+        customMappingType.setIdMapper(new PortableIdMapper() {
+            @Override public int typeId(String clsName) {
+                String typeName;
+
+                try {
+                    Method mtd = PortableContext.class.getDeclaredMethod("typeName", String.class);
+
+                    mtd.setAccessible(true);
+
+                    typeName = (String)mtd.invoke(null, clsName);
+                }
+                catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
+                    throw new RuntimeException(e);
+                }
+
+                return typeName.toLowerCase().hashCode();
+            }
+
+            @Override public int fieldId(int typeId, String fieldName) {
+                return fieldName.toLowerCase().hashCode();
+            }
+        });
+
+        marsh1.setTypeConfigurations(Arrays.asList(
+            new PortableTypeConfiguration(SimpleObject.class.getName()),
+            customMappingType
+        ));
+
+        TestPortableObject obj = portableObject();
+
+        PortableObjectImpl po = marshal(obj, marsh1);
+
+        PortableMarshaller marsh2 = new PortableMarshaller();
+
+        marsh2.setTypeConfigurations(Arrays.asList(
+            new PortableTypeConfiguration(SimpleObject.class.getName()),
+            new PortableTypeConfiguration(TestPortableObject.class.getName())
+        ));
+
+        PortableContext ctx = initPortableContext(marsh2);
+
+        po.context(ctx);
+
+        assertEquals(obj, po.deserialize());
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testTypeNames() throws Exception {
+        PortableMarshaller marsh = new PortableMarshaller();
+
+        PortableTypeConfiguration customType1 = new PortableTypeConfiguration(Value.class.getName());
+
+        customType1.setIdMapper(new PortableIdMapper() {
+            @Override public int typeId(String clsName) {
+                return 100;
+            }
+
+            @Override public int fieldId(int typeId, String fieldName) {
+                return 0;
+            }
+        });
+
+        PortableTypeConfiguration customType2 = new PortableTypeConfiguration("org.gridgain.NonExistentClass1");
+
+        customType2.setIdMapper(new PortableIdMapper() {
+            @Override public int typeId(String clsName) {
+                return 200;
+            }
+
+            @Override public int fieldId(int typeId, String fieldName) {
+                return 0;
+            }
+        });
+
+        PortableTypeConfiguration customType3 = new PortableTypeConfiguration("NonExistentClass2");
+
+        customType3.setIdMapper(new PortableIdMapper() {
+            @Override public int typeId(String clsName) {
+                return 300;
+            }
+
+            @Override public int fieldId(int typeId, String fieldName) {
+                return 0;
+            }
+        });
+
+        PortableTypeConfiguration customType4 = new PortableTypeConfiguration("NonExistentClass5");
+
+        customType4.setIdMapper(new PortableIdMapper() {
+            @Override public int typeId(String clsName) {
+                return 0;
+            }
+
+            @Override public int fieldId(int typeId, String fieldName) {
+                return 0;
+            }
+        });
+
+        marsh.setTypeConfigurations(Arrays.asList(
+            new PortableTypeConfiguration(Key.class.getName()),
+            new PortableTypeConfiguration("org.gridgain.NonExistentClass3"),
+            new PortableTypeConfiguration("NonExistentClass4"),
+            customType1,
+            customType2,
+            customType3,
+            customType4
+        ));
+
+        PortableContext ctx = initPortableContext(marsh);
+
+        assertEquals("notconfiguredclass".hashCode(), ctx.typeId("NotConfiguredClass"));
+        assertEquals("key".hashCode(), ctx.typeId("Key"));
+        assertEquals("nonexistentclass3".hashCode(), ctx.typeId("NonExistentClass3"));
+        assertEquals("nonexistentclass4".hashCode(), ctx.typeId("NonExistentClass4"));
+        assertEquals(100, ctx.typeId(getClass().getSimpleName() + "$Value"));
+        assertEquals(200, ctx.typeId("NonExistentClass1"));
+        assertEquals(300, ctx.typeId("NonExistentClass2"));
+        assertEquals("nonexistentclass5".hashCode(), ctx.typeId("NonExistentClass5"));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testFieldIdMapping() throws Exception {
+        PortableMarshaller marsh = new PortableMarshaller();
+
+        PortableTypeConfiguration customType1 = new PortableTypeConfiguration(Value.class.getName());
+
+        customType1.setIdMapper(new PortableIdMapper() {
+            @Override public int typeId(String clsName) {
+                return 100;
+            }
+
+            @Override public int fieldId(int typeId, String fieldName) {
+                switch (fieldName) {
+                    case "val1":
+                        return 101;
+
+                    case "val2":
+                        return 102;
+
+                    default:
+                        return 0;
+                }
+            }
+        });
+
+        PortableTypeConfiguration customType2 = new PortableTypeConfiguration("NonExistentClass1");
+
+        customType2.setIdMapper(new PortableIdMapper() {
+            @Override public int typeId(String clsName) {
+                return 200;
+            }
+
+            @Override public int fieldId(int typeId, String fieldName) {
+                switch (fieldName) {
+                    case "val1":
+                        return 201;
+
+                    case "val2":
+                        return 202;
+
+                    default:
+                        return 0;
+                }
+            }
+        });
+
+        marsh.setTypeConfigurations(Arrays.asList(new PortableTypeConfiguration(Key.class.getName()),
+                                                  new PortableTypeConfiguration("NonExistentClass2"),
+                                                  customType1,
+                                                  customType2));
+
+        PortableContext ctx = initPortableContext(marsh);
+
+        assertEquals("val".hashCode(), ctx.fieldId("key".hashCode(), "val"));
+        assertEquals("val".hashCode(), ctx.fieldId("nonexistentclass2".hashCode(), "val"));
+        assertEquals("val".hashCode(), ctx.fieldId("notconfiguredclass".hashCode(), "val"));
+        assertEquals(101, ctx.fieldId(100, "val1"));
+        assertEquals(102, ctx.fieldId(100, "val2"));
+        assertEquals("val3".hashCode(), ctx.fieldId(100, "val3"));
+        assertEquals(201, ctx.fieldId(200, "val1"));
+        assertEquals(202, ctx.fieldId(200, "val2"));
+        assertEquals("val3".hashCode(), ctx.fieldId(200, "val3"));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testDuplicateTypeId() throws Exception {
+        final PortableMarshaller marsh = new PortableMarshaller();
+
+        PortableTypeConfiguration customType1 = new PortableTypeConfiguration("org.gridgain.Class1");
+
+        customType1.setIdMapper(new PortableIdMapper() {
+            @Override public int typeId(String clsName) {
+                return 100;
+            }
+
+            @Override public int fieldId(int typeId, String fieldName) {
+                return 0;
+            }
+        });
+
+        PortableTypeConfiguration customType2 = new PortableTypeConfiguration("org.gridgain.Class2");
+
+        customType2.setIdMapper(new PortableIdMapper() {
+            @Override public int typeId(String clsName) {
+                return 100;
+            }
+
+            @Override public int fieldId(int typeId, String fieldName) {
+                return 0;
+            }
+        });
+
+        marsh.setTypeConfigurations(Arrays.asList(customType1, customType2));
+
+        try {
+            initPortableContext(marsh);
+        }
+        catch (IgniteCheckedException e) {
+            assertEquals("Duplicate type ID [clsName=org.gridgain.Class1, id=100]",
+                e.getCause().getCause().getMessage());
+
+            return;
+        }
+
+        assert false;
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testPortableCopy() throws Exception {
+        PortableMarshaller marsh = new PortableMarshaller();
+
+        marsh.setTypeConfigurations(Arrays.asList(
+            new PortableTypeConfiguration(SimpleObject.class.getName())
+        ));
+
+        SimpleObject obj = simpleObject();
+
+        final PortableObject po = marshal(obj, marsh);
+
+        PortableObject copy = copy(po, null);
+
+        assertEquals(obj, copy.deserialize());
+
+        copy = copy(po, new HashMap<String, Object>());
+
+        assertEquals(obj, copy.deserialize());
+
+        Map<String, Object> map = new HashMap<>(1, 1.0f);
+
+        map.put("i", 3);
+
+        copy = copy(po, map);
+
+        assertEquals((byte)2, copy.<Byte>field("b").byteValue());
+        assertEquals((short)2, copy.<Short>field("s").shortValue());
+        assertEquals(3, copy.<Integer>field("i").intValue());
+        assertEquals(2L, copy.<Long>field("l").longValue());
+        assertEquals(2.2f, copy.<Float>field("f").floatValue(), 0);
+        assertEquals(2.2d, copy.<Double>field("d").doubleValue(), 0);
+        assertEquals((char)2, copy.<Character>field("c").charValue());
+        assertEquals(false, copy.<Boolean>field("bool").booleanValue());
+
+        SimpleObject obj0 = copy.deserialize();
+
+        assertEquals((byte)2, obj0.b);
+        assertEquals((short)2, obj0.s);
+        assertEquals(3, obj0.i);
+        assertEquals(2L, obj0.l);
+        assertEquals(2.2f, obj0.f, 0);
+        assertEquals(2.2d, obj0.d, 0);
+        assertEquals((char)2, obj0.c);
+        assertEquals(false, obj0.bool);
+
+        map = new HashMap<>(3, 1.0f);
+
+        map.put("b", (byte)3);
+        map.put("l", 3L);
+        map.put("bool", true);
+
+        copy = copy(po, map);
+
+        assertEquals((byte)3, copy.<Byte>field("b").byteValue());
+        assertEquals((short)2, copy.<Short>field("s").shortValue());
+        assertEquals(2, copy.<Integer>field("i").intValue());
+        assertEquals(3L, copy.<Long>field("l").longValue());
+        assertEquals(2.2f, copy.<Float>field("f").floatValue(), 0);
+        assertEquals(2.2d, copy.<Double>field("d").doubleValue(), 0);
+        assertEquals((char)2, copy.<Character>field("c").charValue());
+        assertEquals(true, copy.<Boolean>field("bool").booleanValue());
+
+        obj0 = copy.deserialize();
+
+        assertEquals((byte)3, obj0.b);
+        assertEquals((short)2, obj0.s);
+        assertEquals(2, obj0.i);
+        assertEquals(3L, obj0.l);
+        assertEquals(2.2f, obj0.f, 0);
+        assertEquals(2.2d, obj0.d, 0);
+        assertEquals((char)2, obj0.c);
+        assertEquals(true, obj0.bool);
+
+        map = new HashMap<>(8, 1.0f);
+
+        map.put("b", (byte)3);
+        map.put("s", (short)3);
+        map.put("i", 3);
+        map.put("l", 3L);
+        map.put("f", 3.3f);
+        map.put("d", 3.3d);
+        map.put("c", (char)3);
+        map.put("bool", true);
+
+        copy = copy(po, map);
+
+        assertEquals((byte)3, copy.<Byte>field("b").byteValue());
+        assertEquals((short)3, copy.<Short>field("s").shortValue());
+        assertEquals(3, copy.<Integer>field("i").intValue());
+        assertEquals(3L, copy.<Long>field("l").longValue());
+        assertEquals(3.3f, copy.<Float>field("f").floatValue(), 0);
+        assertEquals(3.3d, copy.<Double>field("d").doubleValue(), 0);
+        assertEquals((char)3, copy.<Character>field("c").charValue());
+        assertEquals(true, copy.<Boolean>field("bool").booleanValue());
+
+        obj0 = copy.deserialize();
+
+        assertEquals((byte)3, obj0.b);
+        assertEquals((short)3, obj0.s);
+        assertEquals(3, obj0.i);
+        assertEquals(3L, obj0.l);
+        assertEquals(3.3f, obj0.f, 0);
+        assertEquals(3.3d, obj0.d, 0);
+        assertEquals((char)3, obj0.c);
+        assertEquals(true, obj0.bool);
+
+//        GridTestUtils.assertThrows(
+//            log,
+//            new Callable<Object>() {
+//                @Override public Object call() throws Exception {
+//                    po.copy(F.<String, Object>asMap("i", false));
+//
+//                    return null;
+//                }
+//            },
+//            PortableException.class,
+//            "Invalid value type for field: i"
+//        );
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testPortableCopyString() throws Exception {
+        PortableMarshaller marsh = new PortableMarshaller();
+
+        marsh.setTypeConfigurations(Arrays.asList(
+            new PortableTypeConfiguration(SimpleObject.class.getName())
+        ));
+
+        SimpleObject obj = simpleObject();
+
+        PortableObject po = marshal(obj, marsh);
+
+        PortableObject copy = copy(po, F.<String, Object>asMap("str", "str3"));
+
+        assertEquals("str3", copy.<String>field("str"));
+
+        SimpleObject obj0 = copy.deserialize();
+
+        assertEquals("str3", obj0.str);
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testPortableCopyUuid() throws Exception {
+        PortableMarshaller marsh = new PortableMarshaller();
+
+        marsh.setTypeConfigurations(Arrays.asList(
+            new PortableTypeConfiguration(SimpleObject.class.getName())
+        ));
+
+        SimpleObject obj = simpleObject();
+
+        PortableObject po = marshal(obj, marsh);
+
+        UUID uuid = UUID.randomUUID();
+
+        PortableObject copy = copy(po, F.<String, Object>asMap("uuid", uuid));
+
+        assertEquals(uuid, copy.<UUID>field("uuid"));
+
+        SimpleObject obj0 = copy.deserialize();
+
+        assertEquals(uuid, obj0.uuid);
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testPortableCopyByteArray() throws Exception {
+        PortableMarshaller marsh = new PortableMarshaller();
+
+        marsh.setTypeConfigurations(Arrays.asList(
+            new PortableTypeConfiguration(SimpleObject.class.getName())
+        ));
+
+        SimpleObject obj = simpleObject();
+
+        PortableObject po = marshal(obj, marsh);
+
+        PortableObject copy = copy(po, F.<String, Object>asMap("bArr", new byte[]{1, 2, 3}));
+
+        assertArrayEquals(new byte[]{1, 2, 3}, copy.<byte[]>field("bArr"));
+
+        SimpleObject obj0 = copy.deserialize();
+
+        assertArrayEquals(new byte[]{1, 2, 3}, obj0.bArr);
+    }
+
+    /**
+     * @param po Portable object.
+     * @param fields Fields.
+     * @return Copy.
+     */
+    private PortableObject copy(PortableObject po, Map<String, Object> fields) {
+        PortableBuilder builder = PortableBuilderImpl.wrap(po);
+
+        if (fields != null) {
+            for (Map.Entry<String, Object> e : fields.entrySet())
+                builder.setField(e.getKey(), e.getValue());
+        }
+
+        return builder.build();
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testPortableCopyShortArray() throws Exception {
+        PortableMarshaller marsh = new PortableMarshaller();
+
+        marsh.setTypeConfigurations(Arrays.asList(
+            new PortableTypeConfiguration(SimpleObject.class.getName())
+        ));
+
+        SimpleObject obj = simpleObject();
+
+        PortableObject po = marshal(obj, marsh);
+
+        PortableObject copy = copy(po, F.<String, Object>asMap("sArr", new short[]{1, 2, 3}));
+
+        assertArrayEquals(new short[] {1, 2, 3}, copy.<short[]>field("sArr"));
+
+        SimpleObject obj0 = copy.deserialize();
+
+        assertArrayEquals(new short[] {1, 2, 3}, obj0.sArr);
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testPortableCopyIntArray() throws Exception {
+        PortableMarshaller marsh = new PortableMarshaller();
+
+        marsh.setTypeConfigurations(Arrays.asList(
+            new PortableTypeConfiguration(SimpleObject.class.getName())
+        ));
+
+        SimpleObject obj = simpleObject();
+
+        PortableObject po = marshal(obj, marsh);
+
+        PortableObject copy = copy(po, F.<String, Object>asMap("iArr", new int[]{1, 2, 3}));
+
+        assertArrayEquals(new int[] {1, 2, 3}, copy.<int[]>field("iArr"));
+
+        SimpleObject obj0 = copy.deserialize();
+
+        assertArrayEquals(new int[] {1, 2, 3}, obj0.iArr);
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testPortableCopyLongArray() throws Exception {
+        PortableMarshaller marsh = new PortableMarshaller();
+
+        marsh.setTypeConfigurations(Arrays.asList(
+            new PortableTypeConfiguration(SimpleObject.class.getName())
+        ));
+
+        SimpleObject obj = simpleObject();
+
+        PortableObject po = marshal(obj, marsh);
+
+        PortableObject copy = copy(po, F.<String, Object>asMap("lArr", new long[]{1, 2, 3}));
+
+        assertArrayEquals(new long[] {1, 2, 3}, copy.<long[]>field("lArr"));
+
+        SimpleObject obj0 = copy.deserialize();
+
+        assertArrayEquals(new long[] {1, 2, 3}, obj0.lArr);
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testPortableCopyFloatArray() throws Exception {
+        PortableMarshaller marsh = new PortableMarshaller();
+
+        marsh.setTypeConfigurations(Arrays.asList(
+            new PortableTypeConfiguration(SimpleObject.class.getName())
+        ));
+
+        SimpleObject obj = simpleObject();
+
+        PortableObject po = marshal(obj, marsh);
+
+        PortableObject copy = copy(po, F.<String, Object>asMap("fArr", new float[]{1, 2, 3}));
+
+        assertArrayEquals(new float[] {1, 2, 3}, copy.<float[]>field("fArr"), 0);
+
+        SimpleObject obj0 = copy.deserialize();
+
+        assertArrayEquals(new float[] {1, 2, 3}, obj0.fArr, 0);
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testPortableCopyDoubleArray() throws Exception {
+        PortableMarshaller marsh = new PortableMarshaller();
+
+        marsh.setTypeConfigurations(Arrays.asList(
+            new PortableTypeConfiguration(SimpleObject.class.getName())
+        ));
+
+        SimpleObject obj = simpleObject();
+
+        PortableObject po = marshal(obj, marsh);
+
+        PortableObject copy = copy(po, F.<String, Object>asMap("dArr", new double[]{1, 2, 3}));
+
+        assertArrayEquals(new double[] {1, 2, 3}, copy.<double[]>field("dArr"), 0);
+
+        SimpleObject obj0 = copy.deserialize();
+
+        assertArrayEquals(new double[] {1, 2, 3}, obj0.dArr, 0);
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testPortableCopyCharArray() throws Exception {
+        PortableMarshaller marsh = new PortableMarshaller();
+
+        marsh.setTypeConfigurations(Arrays.asList(
+            new PortableTypeConfiguration(SimpleObject.class.getName())
+        ));
+
+        SimpleObject obj = simpleObject();
+
+        PortableObject po = marshal(obj, marsh);
+
+        PortableObject copy = copy(po, F.<String, Object>asMap("cArr", new char[]{1, 2, 3}));
+
+        assertArrayEquals(new char[]{1, 2, 3}, copy.<char[]>field("cArr"));
+
+        SimpleObject obj0 = copy.deserialize();
+
+        assertArrayEquals(new char[]{1, 2, 3}, obj0.cArr);
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testPortableCopyStringArray() throws Exception {
+        PortableMarshaller marsh = new PortableMarshaller();
+
+        marsh.setTypeConfigurations(Arrays.asList(
+            new PortableTypeConfiguration(SimpleObject.class.getName())
+        ));
+
+        SimpleObject obj = simpleObject();
+
+        PortableObject po = marshal(obj, marsh);
+
+        PortableObject copy = copy(po, F.<String, Object>asMap("strArr", new String[]{"str1", "str2"}));
+
+        assertArrayEquals(new String[]{"str1", "str2"}, copy.<String[]>field("strArr"));
+
+        SimpleObject obj0 = copy.deserialize();
+
+        assertArrayEquals(new String[]{"str1", "str2"}, obj0.strArr);
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testPortableCopyObject() throws Exception {
+        PortableMarshaller marsh = new PortableMarshaller();
+
+        marsh.setTypeConfigurations(Arrays.asList(
+            new PortableTypeConfiguration(SimpleObject.class.getName())
+        ));
+
+        SimpleObject obj = simpleObject();
+
+        PortableObject po = marshal(obj, marsh);
+
+        SimpleObject newObj = new SimpleObject();
+
+        newObj.i = 12345;
+        newObj.fArr = new float[] {5, 8, 0};
+        newObj.str = "newStr";
+
+        PortableObject copy = copy(po, F.<String, Object>asMap("inner", newObj));
+
+        assertEquals(newObj, copy.<PortableObject>field("inner").deserialize());
+
+        SimpleObject obj0 = copy.deserialize();
+
+        assertEquals(newObj, obj0.inner);
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testPortableCopyNonPrimitives() throws Exception {
+        PortableMarshaller marsh = new PortableMarshaller();
+
+        marsh.setTypeConfigurations(Arrays.asList(
+            new PortableTypeConfiguration(SimpleObject.class.getName())
+        ));
+
+        SimpleObject obj = simpleObject();
+
+        PortableObject po = marshal(obj, marsh);
+
+        Map<String, Object> map = new HashMap<>(3, 1.0f);
+
+        SimpleObject newObj = new SimpleObject();
+
+        newObj.i = 12345;
+        newObj.fArr = new float[] {5, 8, 0};
+        newObj.str = "newStr";
+
+        map.put("str", "str555");
+        map.put("inner", newObj);
+        map.put("bArr", new byte[]{6, 7, 9});
+
+        PortableObject copy = copy(po, map);
+
+        assertEquals("str555", copy.<String>field("str"));
+        assertEquals(newObj, copy.<PortableObject>field("inner").deserialize());
+        assertArrayEquals(new byte[]{6, 7, 9}, copy.<byte[]>field("bArr"));
+
+        SimpleObject obj0 = copy.deserialize();
+
+        assertEquals("str555", obj0.str);
+        assertEquals(newObj, obj0.inner);
+        assertArrayEquals(new byte[]{6, 7, 9}, obj0.bArr);
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testPortableCopyMixed() throws Exception {
+        PortableMarshaller marsh = new PortableMarshaller();
+
+        marsh.setTypeConfigurations(Arrays.asList(new PortableTypeConfiguration(SimpleObject.class.getName())));
+
+        SimpleObject obj = simpleObject();
+
+        PortableObject po = marshal(obj, marsh);
+
+        Map<String, Object> map = new HashMap<>(3, 1.0f);
+
+        SimpleObject newObj = new SimpleObject();
+
+        newObj.i = 12345;
+        newObj.fArr = new float[] {5, 8, 0};
+        newObj.str = "newStr";
+
+        map.put("i", 1234);
+        map.put("str", "str555");
+        map.put("inner", newObj);
+        map.put("s", (short)2323);
+        map.put("bArr", new byte[]{6, 7, 9});
+        map.put("b", (byte)111);
+
+        PortableObject copy = copy(po, map);
+
+        assertEquals(1234, copy.<Integer>field("i").intValue());
+        assertEquals("str555", copy.<String>field("str"));
+        assertEquals(newObj, copy.<PortableObject>field("inner").deserialize());
+        assertEquals((short)2323, copy.<Short>field("s").shortValue());
+        assertArrayEquals(new byte[]{6, 7, 9}, copy.<byte[]>field("bArr"));
+        assertEquals((byte)111, copy.<Byte>field("b").byteValue());
+
+        SimpleObject obj0 = copy.deserialize();
+
+        assertEquals(1234, obj0.i);
+        assertEquals("str555", obj0.str);
+        assertEquals(newObj, obj0.inner);
+        assertEquals((short)2323, obj0.s);
+        assertArrayEquals(new byte[]{6, 7, 9}, obj0.bArr);
+        assertEquals((byte)111, obj0.b);
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testKeepDeserialized() throws Exception {
+        PortableMarshaller marsh = new PortableMarshaller();
+
+        marsh.setClassNames(Arrays.asList(SimpleObject.class.getName()));
+        marsh.setKeepDeserialized(true);
+
+        PortableObject po = marshal(simpleObject(), marsh);
+
+        assert po.deserialize() == po.deserialize();
+
+        marsh = new PortableMarshaller();
+
+        marsh.setClassNames(Arrays.asList(SimpleObject.class.getName()));
+        marsh.setKeepDeserialized(false);
+
+        po = marshal(simpleObject(), marsh);
+
+        assert po.deserialize() != po.deserialize();
+
+        marsh = new PortableMarshaller();
+
+        marsh.setKeepDeserialized(true);
+        marsh.setTypeConfigurations(Arrays.asList(
+            new PortableTypeConfiguration(SimpleObject.class.getName())));
+
+        po = marshal(simpleObject(), marsh);
+
+        assert po.deserialize() == po.deserialize();
+
+        marsh = new PortableMarshaller();
+
+        marsh.setKeepDeserialized(false);
+        marsh.setTypeConfigurations(Arrays.asList(
+            new PortableTypeConfiguration(SimpleObject.class.getName())));
+
+        po = marshal(simpleObject(), marsh);
+
+        assert po.deserialize() != po.deserialize();
+
+        marsh = new PortableMarshaller();
+
+        marsh.setKeepDeserialized(true);
+
+        PortableTypeConfiguration typeCfg = new PortableTypeConfiguration(SimpleObject.class.getName());
+
+        typeCfg.setKeepDeserialized(false);
+
+        marsh.setTypeConfigurations(Arrays.asList(typeCfg));
+
+        po = marshal(simpleObject(), marsh);
+
+        assert po.deserialize() != po.deserialize();
+
+        marsh = new PortableMarshaller();
+
+        marsh.setKeepDeserialized(false);
+
+        typeCfg = new PortableTypeConfiguration(SimpleObject.class.getName());
+
+        typeCfg.setKeepDeserialized(true);
+
+        marsh.setTypeConfigurations(Arrays.asList(typeCfg));
+
+        po = marshal(simpleObject(), marsh);
+
+        assert po.deserialize() == po.deserialize();
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testOffheapPortable() throws Exception {
+        PortableMarshaller marsh = new PortableMarshaller();
+
+        marsh.setTypeConfigurations(Arrays.asList(new PortableTypeConfiguration(SimpleObject.class.getName())));
+
+        PortableContext ctx = initPortableContext(marsh);
+
+        SimpleObject simpleObj = simpleObject();
+
+        PortableObjectImpl obj = marshal(simpleObj, marsh);
+
+        long ptr = 0;
+
+        long ptr1 = 0;
+
+        long ptr2 = 0;
+
+        try {
+            ptr = copyOffheap(obj);
+
+            PortableObjectOffheapImpl offheapObj = new PortableObjectOffheapImpl(ctx,
+                ptr,
+                0,
+                obj.array().length);
+
+            assertTrue(offheapObj.equals(offheapObj));
+            assertFalse(offheapObj.equals(null));
+            assertFalse(offheapObj.equals("str"));
+            assertTrue(offheapObj.equals(obj));
+            assertTrue(obj.equals(offheapObj));
+
+            ptr1 = copyOffheap(obj);
+
+            PortableObjectOffheapImpl offheapObj1 = new PortableObjectOffheapImpl(ctx,
+                ptr1,
+                0,
+                obj.array().length);
+
+            assertTrue(offheapObj.equals(offheapObj1));
+            assertTrue(offheapObj1.equals(offheapObj));
+
+            assertEquals(obj.typeId(), offheapObj.typeId());
+            assertEquals(obj.hashCode(), offheapObj.hashCode());
+
+            checkSimpleObjectData(simpleObj, offheapObj);
+
+            PortableObjectOffheapImpl innerOffheapObj = offheapObj.field("inner");
+
+            assertNotNull(innerOffheapObj);
+
+            checkSimpleObjectData(simpleObj.inner, innerOffheapObj);
+
+            obj = (PortableObjectImpl)offheapObj.heapCopy();
+
+            assertEquals(obj.typeId(), offheapObj.typeId());
+            assertEquals(obj.hashCode(), offheapObj.hashCode());
+
+            checkSimpleObjectData(simpleObj, obj);
+
+            PortableObjectImpl innerObj = obj.field("inner");
+
+            assertNotNull(innerObj);
+
+            checkSimpleObjectData(simpleObj.inner, innerObj);
+
+            simpleObj.d = 0;
+
+            obj = marshal(simpleObj, marsh);
+
+            assertFalse(offheapObj.equals(obj));
+            assertFalse(obj.equals(offheapObj));
+
+            ptr2 = copyOffheap(obj);
+
+            PortableObjectOffheapImpl offheapObj2 = new PortableObjectOffheapImpl(ctx,
+                ptr2,
+                0,
+                obj.array().length);
+
+            assertFalse(offheapObj.equals(offheapObj2));
+            assertFalse(offheapObj2.equals(offheapObj));
+        }
+        finally {
+            UNSAFE.freeMemory(ptr);
+
+            if (ptr1 > 0)
+                UNSAFE.freeMemory(ptr1);
+
+            if (ptr2 > 0)
+                UNSAFE.freeMemory(ptr2);
+        }
+    }
+
+    /**
+     *
+     */
+    public void testReadResolve() throws Exception {
+        PortableMarshaller marsh = new PortableMarshaller();
+
+        marsh.setClassNames(
+            Arrays.asList(MySingleton.class.getName(), SingletonMarker.class.getName()));
+
+        PortableObjectImpl portableObj = marshal(MySingleton.INSTANCE, marsh);
+
+        assertTrue(portableObj.array().length <= 1024); // Check that big string was not serialized.
+
+        MySingleton singleton = portableObj.deserialize();
+
+        assertSame(MySingleton.INSTANCE, singleton);
+    }
+
+    /**
+     *
+     */
+    public void testReadResolveOnPortableAware() throws Exception {
+        PortableMarshaller marsh = new PortableMarshaller();
+
+        marsh.setClassNames(Collections.singletonList(MyTestClass.class.getName()));
+
+        PortableObjectImpl portableObj = marshal(new MyTestClass(), marsh);
+
+        MyTestClass obj = portableObj.deserialize();
+
+        assertEquals("readResolve", obj.s);
+    }
+
+    /**
+     * @throws Exception If ecxeption thrown.
+     */
+    public void testDeclareReadResolveInParent() throws Exception {
+        PortableMarshaller marsh = new PortableMarshaller();
+
+        marsh.setClassNames(Arrays.asList(ChildPortable.class.getName()));
+
+        PortableObjectImpl portableObj = marshal(new ChildPortable(), marsh);
+
+        ChildPortable singleton = portableObj.deserialize();
+
+        assertNotNull(singleton.s);
+    }
+
+    /**
+     *
+     */
+    public void testDecimalFields() throws Exception {
+        PortableMarshaller marsh = new PortableMarshaller();
+
+        Collection<String> clsNames = new ArrayList<>();
+
+        clsNames.add(DecimalReflective.class.getName());
+        clsNames.add(DecimalMarshalAware.class.getName());
+
+        marsh.setClassNames(clsNames);
+
+        // 1. Test reflective stuff.
+        DecimalReflective obj1 = new DecimalReflective();
+
+        obj1.val = BigDecimal.ZERO;
+        obj1.valArr = new BigDecimal[] { BigDecimal.ONE, BigDecimal.TEN };
+
+        PortableObjectImpl portObj = marshal(obj1, marsh);
+
+        assertEquals(obj1.val, portObj.field("val"));
+        assertArrayEquals(obj1.valArr, portObj.<BigDecimal[]>field("valArr"));
+
+        assertEquals(obj1.val, portObj.<DecimalReflective>deserialize().val);
+        assertArrayEquals(obj1.valArr, portObj.<DecimalReflective>deserialize().valArr);
+
+        // 2. Test marshal aware stuff.
+        DecimalMarshalAware obj2 = new DecimalMarshalAware();
+
+        obj2.val = BigDecimal.ZERO;
+        obj2.valArr = new BigDecimal[] { BigDecimal.ONE, BigDecimal.TEN.negate() };
+        obj2.rawVal = BigDecimal.TEN;
+        obj2.rawValArr = new BigDecimal[] { BigDecimal.ZERO, BigDecimal.ONE };
+
+        portObj = marshal(obj2, marsh);
+
+        assertEquals(obj2.val, portObj.field("val"));
+        assertArrayEquals(obj2.valArr, portObj.<BigDecimal[]>field("valArr"));
+
+        assertEquals(obj2.val, portObj.<DecimalMarshalAware>deserialize().val);
+        assertArrayEquals(obj2.valArr, portObj.<DecimalMarshalAware>deserialize().valArr);
+        assertEquals(obj2.rawVal, portObj.<DecimalMarshalAware>deserialize().rawVal);
+        assertArrayEquals(obj2.rawValArr, portObj.<DecimalMarshalAware>deserialize().rawValArr);
+    }
+
+    /**
+     * @throws IgniteCheckedException If failed.
+     */
+    public void testFinalField() throws IgniteCheckedException {
+        PortableMarshaller marsh = new PortableMarshaller();
+
+        SimpleObjectWithFinal obj = new SimpleObjectWithFinal();
+
+        SimpleObjectWithFinal po0 = marshalUnmarshal(obj, marsh);
+
+        assertEquals(obj.time, po0.time);
+    }
+
+    /**
+     * @throws IgniteCheckedException If failed.
+     */
+    public void testThreadLocalArrayReleased() throws IgniteCheckedException {
+        // Checking the writer directly.
+        assertEquals(false, THREAD_LOCAL_ALLOC.isThreadLocalArrayAcquired());
+
+        try (PortableWriterExImpl writer = new PortableWriterExImpl(initPortableContext(new PortableMarshaller()), 0)) {
+            assertEquals(true, THREAD_LOCAL_ALLOC.isThreadLocalArrayAcquired());
+
+            writer.writeString("Thread local test");
+
+            writer.array();
+
+            assertEquals(true, THREAD_LOCAL_ALLOC.isThreadLocalArrayAcquired());
+        }
+
+        // Checking the portable marshaller.
+        assertEquals(false, THREAD_LOCAL_ALLOC.isThreadLocalArrayAcquired());
+
+        PortableMarshaller marsh = new PortableMarshaller();
+
+        initPortableContext(marsh);
+
+        marsh.marshal(new SimpleObject());
+
+        assertEquals(false, THREAD_LOCAL_ALLOC.isThreadLocalArrayAcquired());
+
+        // Checking the builder.
+        PortableBuilder builder = new PortableBuilderImpl(initPortableContext(new PortableMarshaller()),
+            "org.gridgain.foo.bar.TestClass");
+
+        builder.setField("a", "1");
+
+        PortableObject portableObj = builder.build();
+
+        assertEquals(false, THREAD_LOCAL_ALLOC.isThreadLocalArrayAcquired());
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testDuplicateName() throws Exception {
+        PortableMarshaller marsh = new PortableMarshaller();
+
+        initPortableContext(marsh);
+
+        Test1.Job job1 = new Test1().new Job();
+        Test2.Job job2 = new Test2().new Job();
+
+        marsh.marshal(job1);
+
+        try {
+            marsh.marshal(job2);
+        } catch (PortableException e) {
+            assertEquals(true, e.getMessage().contains("Failed to register class"));
+            return;
+        }
+
+        assert false;
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testClassFieldsMarshalling() throws Exception {
+        PortableMarshaller marsh = new PortableMarshaller();
+
+        initPortableContext(marsh);
+
+        ObjectWithClassFields obj = new ObjectWithClassFields();
+        obj.cls1 = GridPortableMarshallerSelfTest.class;
+
+        byte[] marshal = marsh.marshal(obj);
+
+        ObjectWithClassFields obj2 = marsh.unmarshal(marshal, null);
+
+        assertEquals(obj.cls1, obj2.cls1);
+        assertNull(obj2.cls2);
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testMarshallingThroughJdk() throws Exception {
+        PortableMarshaller marsh = new PortableMarshaller();
+
+        initPortableContext(marsh);
+
+        InetSocketAddress addr = new InetSocketAddress("192.168.0.2", 4545);
+
+        byte[] arr = marsh.marshal(addr);
+
+        InetSocketAddress addr2 = marsh.unmarshal(arr, null);
+
+        assertEquals(addr.getHostString(), addr2.getHostString());
+        assertEquals(addr.getPort(), addr2.getPort());
+
+        TestAddress testAddr = new TestAddress();
+        testAddr.addr = addr;
+        testAddr.str1 = "Hello World";
+
+        SimpleObject simpleObj = new SimpleObject();
+        simpleObj.c = 'g';
+        simpleObj.date = new Date();
+
+        testAddr.obj = simpleObj;
+
+        arr = marsh.marshal(testAddr);
+
+        TestAddress testAddr2 = marsh.unmarshal(arr, null);
+
+        assertEquals(testAddr.addr.getHostString(), testAddr2.addr.getHostString());
+        assertEquals(testAddr.addr.getPort(), testAddr2.addr.getPort());
+        assertEquals(testAddr.str1, testAddr2.str1);
+        assertEquals(testAddr.obj.c, testAddr2.obj.c);
+        assertEquals(testAddr.obj.date, testAddr2.obj.date);
+    }
+
+    /**
+     *
+     */
+    private static class ObjectWithClassFields {
+        private Class<?> cls1;
+
+        private Class<?> cls2;
+    }
+
+    /**
+     *
+     */
+    private static class TestAddress {
+        /** */
+        private SimpleObject obj;
+
+        /** */
+        private InetSocketAddress addr;
+
+        /** */
+        private String str1;
+    }
+
+    /**
+     *
+     */
+    private static class Test1 {
+        /**
+         *
+         */
+        private class Job {
+
+        }
+    }
+
+    /**
+     *
+     */
+    private static class Test2 {
+        /**
+         *
+         */
+        private class Job {
+
+        }
+    }
+
+    /**
+     * @param obj Object.
+     * @return Offheap address.
+     */
+    private long copyOffheap(PortableObjectImpl obj) {
+        byte[] arr = obj.array();
+
+        long ptr = UNSAFE.allocateMemory(arr.length);
+
+        UNSAFE.copyMemory(arr, BYTE_ARR_OFF, null, ptr, arr.length);
+
+        return ptr;
+    }
+
+    /**
+     * @param enumArr Enum array.
+     * @return Ordinals.
+     */
+    private <T extends Enum<?>> Integer[] ordinals(T[] enumArr) {
+        Integer[] ords = new Integer[enumArr.length];
+
+        for (int i = 0; i < enumArr.length; i++)
+            ords[i] = enumArr[i].ordinal();
+
+        return ords;
+    }
+
+    /**
+     * @param po Portable object.
+     * @param off Offset.
+     * @return Value.
+     */
+    private int intFromPortable(PortableObject po, int off) {
+        byte[] arr = U.field(po, "arr");
+
+        return Integer.reverseBytes(U.bytesToInt(arr, off));
+    }
+
+    /**
+     * @param obj Original object.
+     * @return Result object.
+     */
+    private <T> T marshalUnmarshal(T obj) throws IgniteCheckedException {
+        return marshalUnmarshal(obj, new PortableMarshaller());
+    }
+
+    /**
+     * @param obj Original object.
+     * @param marsh Marshaller.
+     * @return Result object.
+     */
+    private <T> T marshalUnmarshal(Object obj, PortableMarshaller marsh) throws IgniteCheckedException {
+        initPortableContext(marsh);
+
+        byte[] bytes = marsh.marshal(obj);
+
+        return marsh.unmarshal(bytes, null);
+    }
+
+    /**
+     * @param obj Object.
+     * @param marsh Marshaller.
+     * @return Portable object.
+     */
+    private <T> PortableObjectImpl marshal(T obj, PortableMarshaller marsh) throws IgniteCheckedException {
+        initPortableContext(marsh);
+
+        byte[] bytes = marsh.marshal(obj);
+
+        return new PortableObjectImpl(U.<GridPortableMarshaller>field(marsh, "impl").context(),
+            bytes, 0);
+    }
+
+    /**
+     * @return Portable context.
+     */
+    protected PortableContext initPortableContext(PortableMarshaller marsh) throws IgniteCheckedException {
+        PortableContext ctx = new PortableContext(META_HND, null);
+
+        marsh.setContext(new MarshallerContextTestImpl(null));
+
+        IgniteUtils.invoke(PortableMarshaller.class, marsh, "setPortableContext", ctx);
+
+        return ctx;
+    }
+
+    /**
+     * @param exp Expected.
+     * @param act Actual.
+     */
+    private void assertBooleanArrayEquals(boolean[] exp, boolean[] act) {
+        assertEquals(exp.length, act.length);
+
+        for (int i = 0; i < act.length; i++)
+            assertEquals(exp[i], act[i]);
+    }
+
+    /**
+     *
+     */
+    private static class SimpleObjectWithFinal {
+        /** */
+        private final long time = System.currentTimeMillis();
+    }
+
+    /**
+     * @return Simple object.
+     */
+    private SimpleObject simpleObject() {
+        SimpleObject inner = new SimpleObject();
+
+        inner.b = 1;
+        inner.s = 1;
+        inner.i = 1;
+        inner.l = 1;
+        inner.f = 1.1f;
+        inner.d = 1.1d;
+        inner.c = 1;
+        inner.bool = true;
+        inner.str = "str1";
+        inner.uuid = UUID.randomUUID();
+        inner.date = new Date();
+        inner.ts = new Timestamp(System.currentTimeMillis());
+        inner.bArr = new byte[] {1, 2, 3};
+        inner.sArr = new short[] {1, 2, 3};
+        inner.iArr = new int[] {1, 2, 3};
+        inner.lArr = new long[] {1, 2, 3};
+        inner.fArr = new float[] {1.1f, 2.2f, 3.3f};
+        inner.dArr = new double[] {1.1d, 2.2d, 3.3d};
+        inner.cArr = new char[] {1, 2, 3};
+        inner.boolArr = new boolean[] {true, false, true};
+        inner.strArr = new String[] {"str1", "str2", "str3"};
+        inner.uuidArr = new UUID[] {UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID()};
+        inner.dateArr = new Date[] {new Date(11111), new Date(22222), new Date(33333)};
+        inner.objArr = new Object[] {UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID()};
+        inner.col = new ArrayList<>();
+        inner.map = new HashMap<>();
+        inner.enumVal = TestEnum.A;
+        inner.enumArr = new TestEnum[] {TestEnum.A, TestEnum.B};
+
+        inner.col.add("str1");
+        inner.col.add("str2");
+        inner.col.add("str3");
+
+        inner.map.put(1, "str1");
+        inner.map.put(2, "str2");
+        inner.map.put(3, "str3");
+
+        SimpleObject outer = new SimpleObject();
+
+        outer.b = 2;
+        outer.s = 2;
+        outer.i = 2;
+        outer.l = 2;
+        outer.f = 2.2f;
+        outer.d = 2.2d;
+        outer.c = 2;
+        outer.bool = false;
+        outer.str = "str2";
+        outer.uuid = UUID.randomUUID();
+        outer.date = new Date();
+        outer.ts = new Timestamp(System.currentTimeMillis());
+        outer.bArr = new byte[] {10, 20, 30};
+        outer.sArr = new short[] {10, 20, 30};
+        outer.iArr = new int[] {10, 20, 30};
+        outer.lArr = new long[] {10, 20, 30};
+        outer.fArr = new float[] {10.01f, 20.02f, 30.03f};
+        outer.dArr = new double[] {10.01d, 20.02d, 30.03d};
+        outer.cArr = new char[] {10, 20, 30};
+        outer.boolArr = new boolean[] {false, true, false};
+        outer.strArr = new String[] {"str10", "str20", "str30"};
+        outer.uuidArr = new UUID[] {UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID()};
+        outer.dateArr = new Date[] {new Date(44444), new Date(55555), new Date(66666)};
+        outer.objArr = new Object[] {UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID()};
+        outer.col = new ArrayList<>();
+        outer.map = new HashMap<>();
+        outer.enumVal = TestEnum.B;
+        outer.enumArr = new TestEnum[] {TestEnum.B, TestEnum.C};
+        outer.inner = inner;
+
+        outer.col.add("str4");
+        outer.col.add("str5");
+        outer.col.add("str6");
+
+        outer.map.put(4, "str4");
+        outer.map.put(5, "str5");
+        outer.map.put(6, "str6");
+
+        return outer;
+    }
+
+    /**
+     * @return Portable object.
+     */
+    private TestPortableObject portableObject() {
+        SimpleObject innerSimple = new SimpleObject();
+
+        innerSimple.b = 1;
+        innerSimple.s = 1;
+        innerSimple.i = 1;
+        innerSimple.l = 1;
+        innerSimple.f = 1.1f;
+        innerSimple.d = 1.1d;
+        innerSimple.c = 1;
+        innerSimple.bool = true;
+        innerSimple.str = "str1";
+        innerSimple.uuid = UUID.randomUUID();
+        innerSimple.date = new Date();
+        innerSimple.ts = new Timestamp(System.currentTimeMillis());
+        innerSimple.bArr = new byte[] {1, 2, 3};
+        innerSimple.sArr = new short[] {1, 2, 3};
+        innerSimple.iArr = new int[] {1, 2, 3};
+        innerSimple.lArr = new long[] {1, 2, 3};
+        innerSimple.fArr = new float[] {1.1f, 2.2f, 3.3f};
+        innerSimple.dArr = new double[] {1.1d, 2.2d, 3.3d};
+        innerSimple.cArr = new char[] {1, 2, 3};
+        innerSimple.boolArr = new boolean[] {true, false, true};
+        innerSimple.strArr = new String[] {"str1", "str2", "str3"};
+        innerSimple.uuidArr = new UUID[] {UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID()};
+        innerSimple.dateArr = new Date[] {new Date(11111), new Date(22222), new Date(33333)};
+        innerSimple.objArr = new UUID[] {UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID()};
+        innerSimple.col = new ArrayList<>();
+        innerSimple.map = new HashMap<>();
+        innerSimple.enumVal = TestEnum.A;
+        innerSimple.enumArr = new TestEnum[] {TestEnum.A, TestEnum.B};
+
+        innerSimple.col.add("str1");
+        innerSimple.col.add("str2");
+        innerSimple.col.add("str3");
+
+        innerSimple.map.put(1, "str1");
+        innerSimple.map.put(2, "str2");
+        innerSimple.map.put(3, "str3");
+
+        TestPortableObject innerPortable = new TestPortableObject();
+
+        innerPortable.b = 2;
+        innerPortable.s = 2;
+        innerPortable.i = 2;
+        innerPortable.l = 2;
+        innerPortable.f = 2.2f;
+        innerPortable.d = 2.2d;
+        innerPortable.c = 2;
+        innerPortable.bool = true;
+        innerPortable.str = "str2";
+        innerPortable.uuid = UUID.randomUUID();
+        innerPortable.date = new Date();
+        innerPortable.ts = new Timestamp(System.currentTimeMillis());
+        innerPortable.bArr = new byte[] {10, 20, 30};
+        innerPortable.sArr = new short[] {10, 20, 30};
+        innerPortable.iArr = new int[] {10, 20, 30};
+        innerPortable.lArr = new long[] {10, 20, 30};
+        innerPortable.fArr = new float[] {10.01f, 20.02f, 30.03f};
+        innerPortable.dArr = new double[] {10.01d, 20.02d, 30.03d};
+        innerPortable.cArr = new char[] {10, 20, 30};
+        innerPortable.boolArr = new boolean[] {true, false, true};
+        innerPortable.strArr = new String[] {"str10", "str20", "str30"};
+        innerPortable.uuidArr = new UUID[] {UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID()};
+        innerPortable.dateArr = new Date[] {new Date(44444), new Date(55555), new Date(66666)};
+        innerPortable.objArr = new Object[] {UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID()};
+        innerPortable.bRaw = 3;
+        innerPortable.sRaw = 3;
+        innerPortable.iRaw = 3;
+        innerPortable.lRaw = 3;
+        innerPortable.fRaw = 3.3f;
+        innerPortable.dRaw = 3.3d;
+        innerPortable.cRaw = 3;
+        innerPortable.boolRaw = true;
+        innerPortable.strRaw = "str3";
+        innerPortable.uuidRaw = UUID.randomUUID();
+        innerPortable.dateRaw = new Date();
+        innerPortable.tsRaw = new Timestamp(System.currentTimeMillis());
+        innerPortable.bArrRaw = new byte[] {11, 21, 31};
+        innerPortable.sArrRaw = new short[] {11, 21, 31};
+        innerPortable.iArrRaw = new int[] {11, 21, 31};
+        innerPortable.lArrRaw = new long[] {11, 21, 31};
+        innerPortable.fArrRaw = new float[] {11.11f, 21.12f, 31.13f};
+        innerPortable.dArrRaw = new double[] {11.11d, 21.12d, 31.13d};
+        innerPortable.cArrRaw = new char[] {11, 21, 31};
+        innerPortable.boolArrRaw = new boolean[] {true, false, true};
+        innerPortable.strArrRaw = new String[] {"str11", "str21", "str31"};
+        innerPortable.uuidArrRaw = new UUID[] {UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID()};
+        innerPortable.dateArrRaw = new Date[] {new D

<TRUNCATED>

[48/59] [abbrv] ignite git commit: Added test.

Posted by vk...@apache.org.
Added test.


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

Branch: refs/heads/ignite-884
Commit: 7ad43fca62c64a7a8ced5ef5a7a030907bbf68cc
Parents: 76bc7d6
Author: sboikov <sb...@gridgain.com>
Authored: Wed Aug 26 15:41:15 2015 +0300
Committer: sboikov <sb...@gridgain.com>
Committed: Wed Aug 26 15:41:15 2015 +0300

----------------------------------------------------------------------
 .../processors/cache/IgniteCacheManyAsyncOperationsTest.java       | 2 +-
 .../java/org/apache/ignite/testsuites/IgniteCacheTestSuite.java    | 1 +
 2 files changed, 2 insertions(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/7ad43fca/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCacheManyAsyncOperationsTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCacheManyAsyncOperationsTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCacheManyAsyncOperationsTest.java
index ab4f1b8..0f0d929 100644
--- a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCacheManyAsyncOperationsTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCacheManyAsyncOperationsTest.java
@@ -76,7 +76,7 @@ public class IgniteCacheManyAsyncOperationsTest extends IgniteCacheAbstractTest
 
             Map<Integer, byte[]> map = new HashMap<>();
 
-            for (int i = 0; i < 500; i++)
+            for (int i = 0; i < 100; i++)
                 map.put(i, new byte[128]);
 
             for (int iter = 0; iter < 3; iter++) {

http://git-wip-us.apache.org/repos/asf/ignite/blob/7ad43fca/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteCacheTestSuite.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteCacheTestSuite.java b/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteCacheTestSuite.java
index bafdfef..b16d1e3 100644
--- a/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteCacheTestSuite.java
+++ b/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteCacheTestSuite.java
@@ -135,6 +135,7 @@ public class IgniteCacheTestSuite extends TestSuite {
         suite.addTestSuite(GridCacheGetStoreErrorSelfTest.class);
         suite.addTestSuite(CacheFutureExceptionSelfTest.class);
         suite.addTestSuite(GridCacheAsyncOperationsLimitSelfTest.class);
+        suite.addTestSuite(IgniteCacheManyAsyncOperationsTest.class);
         suite.addTestSuite(GridCacheTtlManagerSelfTest.class);
         suite.addTestSuite(GridCacheLifecycleAwareSelfTest.class);
         suite.addTestSuite(IgniteCacheAtomicStopBusySelfTest.class);


[02/59] [abbrv] ignite git commit: ignite-1258: portable objects API support in Ignite

Posted by vk...@apache.org.
http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/GridCachePortableObjectsAbstractMultiThreadedSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/GridCachePortableObjectsAbstractMultiThreadedSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/GridCachePortableObjectsAbstractMultiThreadedSelfTest.java
new file mode 100644
index 0000000..37e4d64
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/GridCachePortableObjectsAbstractMultiThreadedSelfTest.java
@@ -0,0 +1,222 @@
+/*
+ * 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.portable;
+
+import org.apache.ignite.*;
+import org.apache.ignite.cache.*;
+import org.apache.ignite.configuration.*;
+import org.apache.ignite.internal.*;
+import org.apache.ignite.internal.processors.cache.*;
+import org.apache.ignite.marshaller.portable.*;
+import org.apache.ignite.portable.*;
+import org.apache.ignite.testframework.junits.common.*;
+
+import org.jsr166.*;
+
+import java.io.*;
+import java.util.*;
+import java.util.concurrent.*;
+import java.util.concurrent.atomic.*;
+
+import static org.apache.ignite.cache.CacheWriteSynchronizationMode.*;
+
+/**
+ * Test for portable objects stored in cache.
+ */
+public abstract class GridCachePortableObjectsAbstractMultiThreadedSelfTest extends GridCommonAbstractTest {
+    /** */
+    private static final int THREAD_CNT = 64;
+
+    /** */
+    private static final AtomicInteger idxGen = new AtomicInteger();
+
+    /** {@inheritDoc} */
+    @Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception {
+        IgniteConfiguration cfg = super.getConfiguration(gridName);
+
+        CacheConfiguration cacheCfg = new CacheConfiguration();
+
+        cacheCfg.setCacheMode(cacheMode());
+        cacheCfg.setAtomicityMode(atomicityMode());
+        cacheCfg.setNearConfiguration(nearConfiguration());
+        cacheCfg.setWriteSynchronizationMode(writeSynchronizationMode());
+
+        cfg.setCacheConfiguration(cacheCfg);
+
+        PortableMarshaller marsh = new PortableMarshaller();
+
+        marsh.setTypeConfigurations(Arrays.asList(
+            new PortableTypeConfiguration(TestObject.class.getName())));
+
+        cfg.setMarshaller(marsh);
+
+        return cfg;
+    }
+
+    /**
+     * @return Sync mode.
+     */
+    protected CacheWriteSynchronizationMode writeSynchronizationMode() {
+        return PRIMARY_SYNC;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void beforeTestsStarted() throws Exception {
+        startGridsMultiThreaded(gridCount());
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void afterTestsStopped() throws Exception {
+        stopAllGrids();
+    }
+
+    /**
+     * @return Cache mode.
+     */
+    protected abstract CacheMode cacheMode();
+
+    /**
+     * @return Atomicity mode.
+     */
+    protected abstract CacheAtomicityMode atomicityMode();
+
+    /**
+     * @return Distribution mode.
+     */
+    protected abstract NearCacheConfiguration nearConfiguration();
+
+    /**
+     * @return Grid count.
+     */
+    protected int gridCount() {
+        return 1;
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    @SuppressWarnings("BusyWait") public void testGetPut() throws Exception {
+        final AtomicBoolean flag = new AtomicBoolean();
+
+        final LongAdder8 cnt = new LongAdder8();
+
+        IgniteInternalFuture<?> f = multithreadedAsync(
+            new Callable<Object>() {
+                @Override public Object call() throws Exception {
+                    int threadId = idxGen.getAndIncrement() % 2;
+
+                    ThreadLocalRandom rnd = ThreadLocalRandom.current();
+
+                    while (!flag.get()) {
+                        IgniteCache<Object, Object> c = jcache(rnd.nextInt(gridCount()));
+
+                        switch (threadId) {
+                            case 0:
+                                // Put/get/remove portable -> portable.
+
+                                c.put(new TestObject(rnd.nextInt(10000)), new TestObject(rnd.nextInt(10000)));
+
+                                IgniteCache<Object, Object> p2 = ((IgniteCacheProxy<Object, Object>)c).keepPortable();
+
+                                PortableObject v = (PortableObject)p2.get(new TestObject(rnd.nextInt(10000)));
+
+                                if (v != null)
+                                    v.deserialize();
+
+                                c.remove(new TestObject(rnd.nextInt(10000)));
+
+                                break;
+
+                            case 1:
+                                // Put/get int -> portable.
+                                c.put(rnd.nextInt(10000), new TestObject(rnd.nextInt(10000)));
+
+                                IgniteCache<Integer, PortableObject> p4 = ((IgniteCacheProxy<Object, Object>)c).keepPortable();
+
+                                PortableObject v1 = p4.get(rnd.nextInt(10000));
+
+                                if (v1 != null)
+                                    v1.deserialize();
+
+                                p4.remove(rnd.nextInt(10000));
+
+                                break;
+
+                            default:
+                                assert false;
+                        }
+
+                        cnt.add(3);
+                    }
+
+                    return null;
+                }
+            },
+            THREAD_CNT
+        );
+
+        for (int i = 0; i < 30 && !f.isDone(); i++)
+            Thread.sleep(1000);
+
+        flag.set(true);
+
+        f.get();
+
+        info("Operations in 30 sec: " + cnt.sum());
+    }
+
+    /**
+     */
+    private static class TestObject implements PortableMarshalAware, Serializable {
+        /** */
+        private int val;
+
+        /**
+         */
+        private TestObject() {
+            // No-op.
+        }
+
+        /**
+         * @param val Value.
+         */
+        private TestObject(int val) {
+            this.val = val;
+        }
+
+        /** {@inheritDoc} */
+        @Override public int hashCode() {
+            return val;
+        }
+
+        /** {@inheritDoc} */
+        @Override public boolean equals(Object obj) {
+            return obj instanceof TestObject && ((TestObject)obj).val == val;
+        }
+
+        /** {@inheritDoc} */
+        @Override public void writePortable(PortableWriter writer) throws PortableException {
+            writer.writeInt("val", val);
+        }
+
+        /** {@inheritDoc} */
+        @Override public void readPortable(PortableReader reader) throws PortableException {
+            val = reader.readInt("val");
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/GridCachePortableObjectsAbstractSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/GridCachePortableObjectsAbstractSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/GridCachePortableObjectsAbstractSelfTest.java
new file mode 100644
index 0000000..8fa3db0
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/GridCachePortableObjectsAbstractSelfTest.java
@@ -0,0 +1,958 @@
+/*
+ * 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.portable;
+
+import org.apache.ignite.*;
+import org.apache.ignite.cache.*;
+import org.apache.ignite.cache.store.*;
+import org.apache.ignite.configuration.*;
+import org.apache.ignite.internal.*;
+import org.apache.ignite.internal.portable.*;
+import org.apache.ignite.internal.processors.cache.*;
+import org.apache.ignite.internal.util.typedef.*;
+import org.apache.ignite.internal.util.typedef.internal.*;
+import org.apache.ignite.lang.*;
+import org.apache.ignite.marshaller.portable.*;
+import org.apache.ignite.portable.*;
+import org.apache.ignite.spi.discovery.tcp.*;
+import org.apache.ignite.spi.discovery.tcp.ipfinder.*;
+import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.*;
+import org.apache.ignite.testframework.junits.common.*;
+import org.apache.ignite.transactions.*;
+
+import org.jetbrains.annotations.*;
+
+import javax.cache.*;
+import javax.cache.processor.*;
+import java.util.*;
+
+import static org.apache.ignite.cache.CacheAtomicityMode.*;
+import static org.apache.ignite.cache.CacheMemoryMode.*;
+import static org.apache.ignite.cache.CacheWriteSynchronizationMode.*;
+import static org.apache.ignite.transactions.TransactionConcurrency.*;
+import static org.apache.ignite.transactions.TransactionIsolation.*;
+
+/**
+ * Test for portable objects stored in cache.
+ */
+public abstract class GridCachePortableObjectsAbstractSelfTest extends GridCommonAbstractTest {
+    /** */
+    public static final TcpDiscoveryIpFinder IP_FINDER = new TcpDiscoveryVmIpFinder(true);
+
+    /** */
+    private static final int ENTRY_CNT = 100;
+
+    /** {@inheritDoc} */
+    @SuppressWarnings("unchecked")
+    @Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception {
+        IgniteConfiguration cfg = super.getConfiguration(gridName);
+
+        TcpDiscoverySpi disco = new TcpDiscoverySpi();
+
+        disco.setIpFinder(IP_FINDER);
+
+        cfg.setDiscoverySpi(disco);
+
+        CacheConfiguration cacheCfg = new CacheConfiguration();
+
+        cacheCfg.setCacheMode(cacheMode());
+        cacheCfg.setAtomicityMode(atomicityMode());
+        cacheCfg.setNearConfiguration(nearConfiguration());
+        cacheCfg.setWriteSynchronizationMode(FULL_SYNC);
+        cacheCfg.setCacheStoreFactory(singletonFactory(new TestStore()));
+        cacheCfg.setReadThrough(true);
+        cacheCfg.setWriteThrough(true);
+        cacheCfg.setLoadPreviousValue(true);
+        cacheCfg.setBackups(1);
+
+        if (offheapTiered()) {
+            cacheCfg.setMemoryMode(OFFHEAP_TIERED);
+            cacheCfg.setOffHeapMaxMemory(0);
+        }
+
+        cfg.setCacheConfiguration(cacheCfg);
+
+        cfg.setMarshaller(new PortableMarshaller());
+
+        return cfg;
+    }
+
+    /**
+     * @return {@code True} if should use OFFHEAP_TIERED mode.
+     */
+    protected boolean offheapTiered() {
+        return false;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void beforeTestsStarted() throws Exception {
+        startGridsMultiThreaded(gridCount());
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void afterTestsStopped() throws Exception {
+        stopAllGrids();
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void afterTest() throws Exception {
+        for (int i = 0; i < gridCount(); i++) {
+            GridCacheAdapter<Object, Object> c = ((IgniteKernal)grid(i)).internalCache();
+
+            for (GridCacheEntryEx e : c.map().entries0()) {
+                Object key = e.key().value(c.context().cacheObjectContext(), false);
+                Object val = CU.value(e.rawGet(), c.context(), false);
+
+                if (key instanceof PortableObject)
+                    assert ((PortableObjectImpl)key).detached() : val;
+
+                if (val instanceof PortableObject)
+                    assert ((PortableObjectImpl)val).detached() : val;
+            }
+        }
+
+        IgniteCache<Object, Object> c = jcache(0);
+
+        for (int i = 0; i < ENTRY_CNT; i++)
+            c.remove(i);
+
+        if (offheapTiered()) {
+            for (int k = 0; k < 100; k++)
+                c.remove(k);
+        }
+
+        assertEquals(0, c.size());
+    }
+
+    /**
+     * @return Cache mode.
+     */
+    protected abstract CacheMode cacheMode();
+
+    /**
+     * @return Atomicity mode.
+     */
+    protected abstract CacheAtomicityMode atomicityMode();
+
+    /**
+     * @return Distribution mode.
+     */
+    protected abstract NearCacheConfiguration nearConfiguration();
+
+    /**
+     * @return Grid count.
+     */
+    protected abstract int gridCount();
+
+    /**
+     * @throws Exception If failed.
+     */
+    @SuppressWarnings("unchecked")
+    public void testCircularReference() throws Exception {
+        IgniteCache c = keepPortableCache();
+
+        TestReferenceObject obj1 = new TestReferenceObject();
+
+        obj1.obj = new TestReferenceObject(obj1);
+
+        c.put(1, obj1);
+
+        PortableObject po = (PortableObject)c.get(1);
+
+        String str = po.toString();
+
+        log.info("toString: " + str);
+
+        assertNotNull(str);
+
+        assertTrue("Unexpected toString: " + str,
+            str.startsWith("TestReferenceObject") && str.contains("obj=TestReferenceObject ["));
+
+        TestReferenceObject obj1_r = po.deserialize();
+
+        assertNotNull(obj1_r);
+
+        TestReferenceObject obj2_r = obj1_r.obj;
+
+        assertNotNull(obj2_r);
+
+        assertSame(obj1_r, obj2_r.obj);
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testGet() throws Exception {
+        IgniteCache<Integer, TestObject> c = jcache(0);
+
+        for (int i = 0; i < ENTRY_CNT; i++)
+            c.put(i, new TestObject(i));
+
+        for (int i = 0; i < ENTRY_CNT; i++) {
+            TestObject obj = c.get(i);
+
+            assertEquals(i, obj.val);
+        }
+
+        IgniteCache<Integer, PortableObject> kpc = keepPortableCache();
+
+        for (int i = 0; i < ENTRY_CNT; i++) {
+            PortableObject po = kpc.get(i);
+
+            assertEquals(i, (int)po.field("val"));
+        }
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testIterator() throws Exception {
+        IgniteCache<Integer, TestObject> c = jcache(0);
+
+        Map<Integer, TestObject> entries = new HashMap<>();
+
+        for (int i = 0; i < ENTRY_CNT; i++) {
+            TestObject val = new TestObject(i);
+
+            c.put(i, val);
+
+            entries.put(i, val);
+        }
+
+        IgniteCache<Integer, PortableObject> prj = ((IgniteCacheProxy)c).keepPortable();
+
+        Iterator<Cache.Entry<Integer, PortableObject>> it = prj.iterator();
+
+        assertTrue(it.hasNext());
+
+        while (it.hasNext()) {
+            Cache.Entry<Integer, PortableObject> entry = it.next();
+
+            assertTrue(entries.containsKey(entry.getKey()));
+
+            TestObject o = entries.get(entry.getKey());
+
+            PortableObject po = entry.getValue();
+
+            assertEquals(o.val, (int)po.field("val"));
+
+            entries.remove(entry.getKey());
+        }
+
+        assertEquals(0, entries.size());
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testCollection() throws Exception {
+        IgniteCache<Integer, Collection<TestObject>> c = jcache(0);
+
+        for (int i = 0; i < ENTRY_CNT; i++) {
+            Collection<TestObject> col = new ArrayList<>(3);
+
+            for (int j = 0; j < 3; j++)
+                col.add(new TestObject(i * 10 + j));
+
+            c.put(i, col);
+        }
+
+        for (int i = 0; i < ENTRY_CNT; i++) {
+            Collection<TestObject> col = c.get(i);
+
+            assertEquals(3, col.size());
+
+            Iterator<TestObject> it = col.iterator();
+
+            for (int j = 0; j < 3; j++) {
+                assertTrue(it.hasNext());
+
+                assertEquals(i * 10 + j, it.next().val);
+            }
+        }
+
+        IgniteCache<Integer, Collection<PortableObject>> kpc = keepPortableCache();
+
+        for (int i = 0; i < ENTRY_CNT; i++) {
+            Collection<PortableObject> col = kpc.get(i);
+
+            assertEquals(3, col.size());
+
+            Iterator<PortableObject> it = col.iterator();
+
+            for (int j = 0; j < 3; j++) {
+                assertTrue(it.hasNext());
+
+                assertEquals(i * 10 + j, (int)it.next().field("val"));
+            }
+        }
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testMap() throws Exception {
+        IgniteCache<Integer, Map<Integer, TestObject>> c = jcache(0);
+
+        for (int i = 0; i < ENTRY_CNT; i++) {
+            Map<Integer, TestObject> map = U.newHashMap(3);
+
+            for (int j = 0; j < 3; j++) {
+                int idx = i * 10 + j;
+
+                map.put(idx, new TestObject(idx));
+            }
+
+            c.put(i, map);
+        }
+
+        for (int i = 0; i < ENTRY_CNT; i++) {
+            Map<Integer, TestObject> map = c.get(i);
+
+            assertEquals(3, map.size());
+
+            for (int j = 0; j < 3; j++) {
+                int idx = i * 10 + j;
+
+                assertEquals(idx, map.get(idx).val);
+            }
+        }
+
+        IgniteCache<Integer, Map<Integer, PortableObject>> kpc = keepPortableCache();
+
+        for (int i = 0; i < ENTRY_CNT; i++) {
+            Map<Integer, PortableObject> map = kpc.get(i);
+
+            assertEquals(3, map.size());
+
+            for (int j = 0; j < 3; j++) {
+                int idx = i * 10 + j;
+
+                assertEquals(idx, (int)map.get(idx).field("val"));
+            }
+        }
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testGetAsync() throws Exception {
+        IgniteCache<Integer, TestObject> c = jcache(0);
+
+        IgniteCache<Integer, TestObject> cacheAsync = c.withAsync();
+
+        for (int i = 0; i < ENTRY_CNT; i++)
+            c.put(i, new TestObject(i));
+
+        for (int i = 0; i < ENTRY_CNT; i++) {
+            cacheAsync.get(i);
+            TestObject obj = cacheAsync.<TestObject>future().get();
+
+            assertEquals(i, obj.val);
+        }
+
+        IgniteCache<Integer, PortableObject> kpc = keepPortableCache();
+
+        IgniteCache<Integer, PortableObject> cachePortableAsync = kpc.withAsync();
+
+        for (int i = 0; i < ENTRY_CNT; i++) {
+            cachePortableAsync.get(i);
+
+            PortableObject po = cachePortableAsync.<PortableObject>future().get();
+
+            assertEquals(i, (int)po.field("val"));
+        }
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testGetTx() throws Exception {
+        if (atomicityMode() != TRANSACTIONAL)
+            return;
+
+        IgniteCache<Integer, TestObject> c = jcache(0);
+
+        for (int i = 0; i < ENTRY_CNT; i++)
+            c.put(i, new TestObject(i));
+
+        for (int i = 0; i < ENTRY_CNT; i++) {
+            try (Transaction tx = grid(0).transactions().txStart(PESSIMISTIC, REPEATABLE_READ)) {
+                TestObject obj = c.get(i);
+
+                assertEquals(i, obj.val);
+
+                tx.commit();
+            }
+        }
+
+        for (int i = 0; i < ENTRY_CNT; i++) {
+            try (Transaction tx = grid(0).transactions().txStart(PESSIMISTIC, READ_COMMITTED)) {
+                TestObject obj = c.get(i);
+
+                assertEquals(i, obj.val);
+
+                tx.commit();
+            }
+        }
+
+        IgniteCache<Integer, PortableObject> kpc = keepPortableCache();
+
+        for (int i = 0; i < ENTRY_CNT; i++) {
+            try (Transaction tx = grid(0).transactions().txStart(PESSIMISTIC, REPEATABLE_READ)) {
+                PortableObject po = kpc.get(i);
+
+                assertEquals(i, (int)po.field("val"));
+
+                tx.commit();
+            }
+        }
+
+        for (int i = 0; i < ENTRY_CNT; i++) {
+            try (Transaction tx = grid(0).transactions().txStart(PESSIMISTIC, READ_COMMITTED)) {
+                PortableObject po = kpc.get(i);
+
+                assertEquals(i, (int)po.field("val"));
+
+                tx.commit();
+            }
+        }
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testGetAsyncTx() throws Exception {
+        if (atomicityMode() != TRANSACTIONAL)
+            return;
+
+        IgniteCache<Integer, TestObject> c = jcache(0);
+
+        IgniteCache<Integer, TestObject> cacheAsync = c.withAsync();
+
+        for (int i = 0; i < ENTRY_CNT; i++)
+            c.put(i, new TestObject(i));
+
+        for (int i = 0; i < ENTRY_CNT; i++) {
+            try (Transaction tx = grid(0).transactions().txStart(PESSIMISTIC, REPEATABLE_READ)) {
+                cacheAsync.get(i);
+
+                TestObject obj = cacheAsync.<TestObject>future().get();
+
+                assertEquals(i, obj.val);
+
+                tx.commit();
+            }
+        }
+
+        IgniteCache<Integer, PortableObject> kpc = keepPortableCache();
+        IgniteCache<Integer, PortableObject> cachePortableAsync = kpc.withAsync();
+
+        for (int i = 0; i < ENTRY_CNT; i++) {
+            try (Transaction tx = grid(0).transactions().txStart(PESSIMISTIC, REPEATABLE_READ)) {
+                cachePortableAsync.get(i);
+
+                PortableObject po = cachePortableAsync.<PortableObject>future().get();
+
+                assertEquals(i, (int)po.field("val"));
+
+                tx.commit();
+            }
+        }
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testGetAll() throws Exception {
+        IgniteCache<Integer, TestObject> c = jcache(0);
+
+        for (int i = 0; i < ENTRY_CNT; i++)
+            c.put(i, new TestObject(i));
+
+        for (int i = 0; i < ENTRY_CNT; ) {
+            Set<Integer> keys = new HashSet<>();
+
+            for (int j = 0; j < 10; j++)
+                keys.add(i++);
+
+            Map<Integer, TestObject> objs = c.getAll(keys);
+
+            assertEquals(10, objs.size());
+
+            for (Map.Entry<Integer, TestObject> e : objs.entrySet())
+                assertEquals(e.getKey().intValue(), e.getValue().val);
+        }
+
+        IgniteCache<Integer, PortableObject> kpc = keepPortableCache();
+
+        for (int i = 0; i < ENTRY_CNT; ) {
+            Set<Integer> keys = new HashSet<>();
+
+            for (int j = 0; j < 10; j++)
+                keys.add(i++);
+
+            Map<Integer, PortableObject> objs = kpc.getAll(keys);
+
+            assertEquals(10, objs.size());
+
+            for (Map.Entry<Integer, PortableObject> e : objs.entrySet())
+                assertEquals(new Integer(e.getKey().intValue()), e.getValue().field("val"));
+        }
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testGetAllAsync() throws Exception {
+        IgniteCache<Integer, TestObject> c = jcache(0);
+
+        IgniteCache<Integer, TestObject> cacheAsync = c.withAsync();
+
+        for (int i = 0; i < ENTRY_CNT; i++)
+            c.put(i, new TestObject(i));
+
+        for (int i = 0; i < ENTRY_CNT; ) {
+            Set<Integer> keys = new HashSet<>();
+
+            for (int j = 0; j < 10; j++)
+                keys.add(i++);
+
+            cacheAsync.getAll(keys);
+
+            Map<Integer, TestObject> objs = cacheAsync.<Map<Integer, TestObject>>future().get();
+
+            assertEquals(10, objs.size());
+
+            for (Map.Entry<Integer, TestObject> e : objs.entrySet())
+                assertEquals(e.getKey().intValue(), e.getValue().val);
+        }
+
+        IgniteCache<Integer, PortableObject> kpc = keepPortableCache();
+        IgniteCache<Integer, PortableObject> cachePortableAsync = kpc.withAsync();
+
+        for (int i = 0; i < ENTRY_CNT; ) {
+            Set<Integer> keys = new HashSet<>();
+
+            for (int j = 0; j < 10; j++)
+                keys.add(i++);
+
+
+            cachePortableAsync.getAll(keys);
+
+            Map<Integer, PortableObject> objs = cachePortableAsync.<Map<Integer, PortableObject>>future().get();
+
+            assertEquals(10, objs.size());
+
+            for (Map.Entry<Integer, PortableObject> e : objs.entrySet())
+                assertEquals(new Integer(e.getKey().intValue()), e.getValue().field("val"));
+        }
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testGetAllTx() throws Exception {
+        if (atomicityMode() != TRANSACTIONAL)
+            return;
+
+        IgniteCache<Integer, TestObject> c = jcache(0);
+
+        for (int i = 0; i < ENTRY_CNT; i++)
+            c.put(i, new TestObject(i));
+
+        for (int i = 0; i < ENTRY_CNT; ) {
+            Set<Integer> keys = new HashSet<>();
+
+            for (int j = 0; j < 10; j++)
+                keys.add(i++);
+
+            try (Transaction tx = grid(0).transactions().txStart(PESSIMISTIC, REPEATABLE_READ)) {
+                Map<Integer, TestObject> objs = c.getAll(keys);
+
+                assertEquals(10, objs.size());
+
+                for (Map.Entry<Integer, TestObject> e : objs.entrySet())
+                    assertEquals(e.getKey().intValue(), e.getValue().val);
+
+                tx.commit();
+            }
+
+            try (Transaction tx = grid(0).transactions().txStart(PESSIMISTIC, READ_COMMITTED)) {
+                Map<Integer, TestObject> objs = c.getAll(keys);
+
+                assertEquals(10, objs.size());
+
+                for (Map.Entry<Integer, TestObject> e : objs.entrySet())
+                    assertEquals(e.getKey().intValue(), e.getValue().val);
+
+                tx.commit();
+            }
+        }
+
+        IgniteCache<Integer, PortableObject> kpc = keepPortableCache();
+
+        for (int i = 0; i < ENTRY_CNT; ) {
+            Set<Integer> keys = new HashSet<>();
+
+            for (int j = 0; j < 10; j++)
+                keys.add(i++);
+
+            try (Transaction tx = grid(0).transactions().txStart(PESSIMISTIC, REPEATABLE_READ)) {
+                Map<Integer, PortableObject> objs = kpc.getAll(keys);
+
+                assertEquals(10, objs.size());
+
+                for (Map.Entry<Integer, PortableObject> e : objs.entrySet())
+                    assertEquals(new Integer(e.getKey().intValue()), e.getValue().field("val"));
+
+                tx.commit();
+            }
+
+            try (Transaction tx = grid(0).transactions().txStart(PESSIMISTIC, READ_COMMITTED)) {
+                Map<Integer, PortableObject> objs = kpc.getAll(keys);
+
+                assertEquals(10, objs.size());
+
+                for (Map.Entry<Integer, PortableObject> e : objs.entrySet())
+                    assertEquals(new Integer(e.getKey().intValue()), e.getValue().field("val"));
+
+                tx.commit();
+            }
+        }
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testGetAllAsyncTx() throws Exception {
+        if (atomicityMode() != TRANSACTIONAL)
+            return;
+
+        IgniteCache<Integer, TestObject> c = jcache(0);
+        IgniteCache<Integer, TestObject> cacheAsync = c.withAsync();
+
+        for (int i = 0; i < ENTRY_CNT; i++)
+            c.put(i, new TestObject(i));
+
+        for (int i = 0; i < ENTRY_CNT; ) {
+            Set<Integer> keys = new HashSet<>();
+
+            for (int j = 0; j < 10; j++)
+                keys.add(i++);
+
+            try (Transaction tx = grid(0).transactions().txStart(PESSIMISTIC, REPEATABLE_READ)) {
+                cacheAsync.getAll(keys);
+
+                Map<Integer, TestObject> objs = cacheAsync.<Map<Integer, TestObject>>future().get();
+
+                assertEquals(10, objs.size());
+
+                for (Map.Entry<Integer, TestObject> e : objs.entrySet())
+                    assertEquals(e.getKey().intValue(), e.getValue().val);
+
+                tx.commit();
+            }
+        }
+
+        IgniteCache<Integer, PortableObject> cache = keepPortableCache();
+
+        for (int i = 0; i < ENTRY_CNT; ) {
+            Set<Integer> keys = new HashSet<>();
+
+            for (int j = 0; j < 10; j++)
+                keys.add(i++);
+
+            IgniteCache<Integer, PortableObject> asyncCache = cache.withAsync();
+
+            try (Transaction tx = grid(0).transactions().txStart(PESSIMISTIC, REPEATABLE_READ)) {
+                asyncCache.getAll(keys);
+
+                Map<Integer, PortableObject> objs = asyncCache.<Map<Integer, PortableObject>>future().get();
+
+                assertEquals(10, objs.size());
+
+                for (Map.Entry<Integer, PortableObject> e : objs.entrySet())
+                    assertEquals(new Integer(e.getKey().intValue()), e.getValue().field("val"));
+
+                tx.commit();
+            }
+        }
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testLoadCache() throws Exception {
+        for (int i = 0; i < gridCount(); i++)
+            jcache(i).localLoadCache(null);
+
+        IgniteCache<Integer, TestObject> cache = jcache(0);
+
+        assertEquals(3, cache.size(CachePeekMode.PRIMARY));
+
+        assertEquals(1, cache.get(1).val);
+        assertEquals(2, cache.get(2).val);
+        assertEquals(3, cache.get(3).val);
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testLoadCacheAsync() throws Exception {
+        for (int i = 0; i < gridCount(); i++) {
+            IgniteCache<Object, Object> jcache = jcache(i).withAsync();
+
+            jcache.loadCache(null);
+
+            jcache.future().get();
+        }
+
+        IgniteCache<Integer, TestObject> cache = jcache(0);
+
+        assertEquals(3, cache.size(CachePeekMode.PRIMARY));
+
+        assertEquals(1, cache.get(1).val);
+        assertEquals(2, cache.get(2).val);
+        assertEquals(3, cache.get(3).val);
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testLoadCacheFilteredAsync() throws Exception {
+        for (int i = 0; i < gridCount(); i++) {
+            IgniteCache<Integer, TestObject> c = this.<Integer, TestObject>jcache(i).withAsync();
+
+            c.loadCache(new P2<Integer, TestObject>() {
+                @Override public boolean apply(Integer key, TestObject val) {
+                    return val.val < 3;
+                }
+            });
+
+            c.future().get();
+        }
+
+        IgniteCache<Integer, TestObject> cache = jcache(0);
+
+        assertEquals(2, cache.size(CachePeekMode.PRIMARY));
+
+        assertEquals(1, cache.get(1).val);
+        assertEquals(2, cache.get(2).val);
+
+        assertNull(cache.get(3));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testTransform() throws Exception {
+        IgniteCache<Integer, PortableObject> c = keepPortableCache();
+
+        checkTransform(primaryKey(c));
+
+        if (cacheMode() != CacheMode.LOCAL) {
+            checkTransform(backupKey(c));
+
+            if (nearConfiguration() != null)
+                checkTransform(nearKey(c));
+        }
+    }
+
+    /**
+     * @return Cache with keep portable flag.
+     */
+    private <K, V> IgniteCache<K, V> keepPortableCache() {
+        return ignite(0).cache(null).withKeepPortable();
+    }
+
+    /**
+     * @param key Key.
+     * @throws Exception If failed.
+     */
+    private void checkTransform(Integer key) throws Exception {
+        log.info("Transform: " + key);
+
+        IgniteCache<Integer, PortableObject> c = keepPortableCache();
+
+        try {
+            c.invoke(key, new EntryProcessor<Integer, PortableObject, Void>() {
+                @Override public Void process(MutableEntry<Integer, PortableObject> e, Object... args) {
+                    PortableObject val = e.getValue();
+
+                    assertNull("Unexpected value: " + val, val);
+
+                    return null;
+                }
+            });
+
+            jcache(0).put(key, new TestObject(1));
+
+            c.invoke(key, new EntryProcessor<Integer, PortableObject, Void>() {
+                @Override public Void process(MutableEntry<Integer, PortableObject> e, Object... args) {
+                    PortableObject val = e.getValue();
+
+                    assertNotNull("Unexpected value: " + val, val);
+
+                    assertEquals(new Integer(1), val.field("val"));
+
+                    Ignite ignite = e.unwrap(Ignite.class);
+
+                    IgnitePortables portables = ignite.portables();
+
+                    PortableBuilder builder = portables.builder(val);
+
+                    builder.setField("val", 2);
+
+                    e.setValue(builder.build());
+
+                    return null;
+                }
+            });
+
+            PortableObject obj = c.get(key);
+
+            assertEquals(new Integer(2), obj.field("val"));
+
+            c.invoke(key, new EntryProcessor<Integer, PortableObject, Void>() {
+                @Override public Void process(MutableEntry<Integer, PortableObject> e, Object... args) {
+                    PortableObject val = e.getValue();
+
+                    assertNotNull("Unexpected value: " + val, val);
+
+                    assertEquals(new Integer(2), val.field("val"));
+
+                    e.setValue(val);
+
+                    return null;
+                }
+            });
+
+            obj = c.get(key);
+
+            assertEquals(new Integer(2), obj.field("val"));
+
+            c.invoke(key, new EntryProcessor<Integer, PortableObject, Void>() {
+                @Override public Void process(MutableEntry<Integer, PortableObject> e, Object... args) {
+                    PortableObject val = e.getValue();
+
+                    assertNotNull("Unexpected value: " + val, val);
+
+                    assertEquals(new Integer(2), val.field("val"));
+
+                    e.remove();
+
+                    return null;
+                }
+            });
+
+            assertNull(c.get(key));
+        }
+        finally {
+            c.remove(key);
+        }
+    }
+
+    /**
+     *
+     */
+    private static class TestObject implements PortableMarshalAware {
+        /** */
+        private int val;
+
+        /**
+         */
+        private TestObject() {
+            // No-op.
+        }
+
+        /**
+         * @param val Value.
+         */
+        private TestObject(int val) {
+            this.val = val;
+        }
+
+        /** {@inheritDoc} */
+        @Override public void writePortable(PortableWriter writer) throws PortableException {
+            writer.writeInt("val", val);
+        }
+
+        /** {@inheritDoc} */
+        @Override public void readPortable(PortableReader reader) throws PortableException {
+            val = reader.readInt("val");
+        }
+    }
+
+    /**
+     *
+     */
+    private static class TestReferenceObject implements PortableMarshalAware {
+        /** */
+        private TestReferenceObject obj;
+
+        /**
+         */
+        private TestReferenceObject() {
+            // No-op.
+        }
+
+        /**
+         * @param obj Object.
+         */
+        private TestReferenceObject(TestReferenceObject obj) {
+            this.obj = obj;
+        }
+
+        /** {@inheritDoc} */
+        @Override public void writePortable(PortableWriter writer) throws PortableException {
+            writer.writeObject("obj", obj);
+        }
+
+        /** {@inheritDoc} */
+        @Override public void readPortable(PortableReader reader) throws PortableException {
+            obj = reader.readObject("obj");
+        }
+    }
+
+    /**
+     *
+     */
+    private static class TestStore extends CacheStoreAdapter<Integer, Object> {
+        /** {@inheritDoc} */
+        @Override public void loadCache(IgniteBiInClosure<Integer, Object> clo, Object... args) {
+            for (int i = 1; i <= 3; i++)
+                clo.apply(i, new TestObject(i));
+        }
+
+        /** {@inheritDoc} */
+        @Nullable @Override public Object load(Integer key) {
+            return null;
+        }
+
+        /** {@inheritDoc} */
+        @Override public void write(Cache.Entry<? extends Integer, ?> e) {
+            // No-op.
+        }
+
+        /** {@inheritDoc} */
+        @Override public void delete(Object key) {
+            // No-op.
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/GridCachePortableStoreAbstractSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/GridCachePortableStoreAbstractSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/GridCachePortableStoreAbstractSelfTest.java
new file mode 100644
index 0000000..d224349
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/GridCachePortableStoreAbstractSelfTest.java
@@ -0,0 +1,294 @@
+/*
+ * 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.portable;
+
+import org.apache.ignite.cache.store.*;
+import org.apache.ignite.configuration.*;
+import org.apache.ignite.marshaller.portable.*;
+import org.apache.ignite.spi.discovery.tcp.*;
+import org.apache.ignite.spi.discovery.tcp.ipfinder.*;
+import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.*;
+import org.apache.ignite.testframework.junits.common.*;
+
+import com.google.common.collect.*;
+import org.jetbrains.annotations.*;
+import org.jsr166.*;
+
+import javax.cache.*;
+import java.util.*;
+
+/**
+ * Tests for cache store with portables.
+ */
+public abstract class GridCachePortableStoreAbstractSelfTest extends GridCommonAbstractTest {
+    /** */
+    private static final TcpDiscoveryIpFinder IP_FINDER = new TcpDiscoveryVmIpFinder(true);
+
+    /** */
+    private static final TestStore STORE = new TestStore();
+
+    /** {@inheritDoc} */
+    @SuppressWarnings("unchecked")
+    @Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception {
+        IgniteConfiguration cfg = super.getConfiguration(gridName);
+
+        PortableMarshaller marsh = new PortableMarshaller();
+
+        marsh.setClassNames(Arrays.asList(Key.class.getName(), Value.class.getName()));
+
+        cfg.setMarshaller(marsh);
+
+        CacheConfiguration cacheCfg = new CacheConfiguration();
+
+        cacheCfg.setCacheStoreFactory(singletonFactory(STORE));
+        cacheCfg.setKeepPortableInStore(keepPortableInStore());
+        cacheCfg.setReadThrough(true);
+        cacheCfg.setWriteThrough(true);
+        cacheCfg.setLoadPreviousValue(true);
+
+        cfg.setCacheConfiguration(cacheCfg);
+
+        TcpDiscoverySpi disco = new TcpDiscoverySpi();
+
+        disco.setIpFinder(IP_FINDER);
+
+        cfg.setDiscoverySpi(disco);
+
+        return cfg;
+    }
+
+    /**
+     * @return Keep portables in store flag.
+     */
+    protected abstract boolean keepPortableInStore();
+
+    /** {@inheritDoc} */
+    @Override protected void beforeTestsStarted() throws Exception {
+        startGrid();
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void afterTestsStopped() throws Exception {
+        stopGrid();
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void beforeTest() throws Exception {
+        STORE.map().clear();
+
+        jcache().clear();
+
+        assert jcache().size() == 0;
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testPut() throws Exception {
+        jcache().put(new Key(1), new Value(1));
+
+        checkMap(STORE.map(), 1);
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testPutAll() throws Exception {
+        Map<Object, Object> map = new HashMap<>();
+
+        for (int i = 1; i <= 3; i++)
+            map.put(new Key(i), new Value(i));
+
+        jcache().putAll(map);
+
+        checkMap(STORE.map(), 1, 2, 3);
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testLoad() throws Exception {
+        populateMap(STORE.map(), 1);
+
+        Object val = jcache().get(new Key(1));
+
+        assertTrue(String.valueOf(val), val instanceof Value);
+
+        assertEquals(1, ((Value)val).index());
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testLoadAll() throws Exception {
+        populateMap(STORE.map(), 1, 2, 3);
+
+        Set<Object> keys = new HashSet<>();
+
+        for (int i = 1; i <= 3; i++)
+            keys.add(new Key(i));
+
+        Map<Object, Object> res = jcache().getAll(keys);
+
+        assertEquals(3, res.size());
+
+        for (int i = 1; i <= 3; i++) {
+            Object val = res.get(new Key(i));
+
+            assertTrue(String.valueOf(val), val instanceof Value);
+
+            assertEquals(i, ((Value)val).index());
+        }
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testRemove() throws Exception {
+        for (int i = 1; i <= 3; i++)
+            jcache().put(new Key(i), new Value(i));
+
+        jcache().remove(new Key(1));
+
+        checkMap(STORE.map(), 2, 3);
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testRemoveAll() throws Exception {
+        for (int i = 1; i <= 3; i++)
+            jcache().put(new Key(i), new Value(i));
+
+        jcache().removeAll(ImmutableSet.of(new Key(1), new Key(2)));
+
+        checkMap(STORE.map(), 3);
+    }
+
+    /**
+     * @param map Map.
+     * @param idxs Indexes.
+     */
+    protected abstract void populateMap(Map<Object, Object> map, int... idxs);
+
+    /**
+     * @param map Map.
+     * @param idxs Indexes.
+     */
+    protected abstract void checkMap(Map<Object, Object> map, int... idxs);
+
+    /**
+     */
+    protected static class Key {
+        /** */
+        private int idx;
+
+        /**
+         * @param idx Index.
+         */
+        public Key(int idx) {
+            this.idx = idx;
+        }
+
+        /**
+         * @return Index.
+         */
+        int index() {
+            return idx;
+        }
+
+        /** {@inheritDoc} */
+        @Override public boolean equals(Object o) {
+            if (this == o)
+                return true;
+
+            if (o == null || getClass() != o.getClass())
+                return false;
+
+            Key key = (Key)o;
+
+            return idx == key.idx;
+        }
+
+        /** {@inheritDoc} */
+        @Override public int hashCode() {
+            return idx;
+        }
+
+        /** {@inheritDoc} */
+        @Override public String toString() {
+            return "Key [idx=" + idx + ']';
+        }
+    }
+
+    /**
+     */
+    protected static class Value {
+        /** */
+        private int idx;
+
+        /**
+         * @param idx Index.
+         */
+        public Value(int idx) {
+            this.idx = idx;
+        }
+
+        /**
+         * @return Index.
+         */
+        int index() {
+            return idx;
+        }
+
+        /** {@inheritDoc} */
+        @Override public String toString() {
+            return "Value [idx=" + idx + ']';
+        }
+    }
+
+    /**
+     *
+     */
+    private static class TestStore extends CacheStoreAdapter<Object, Object> {
+        /** */
+        private final Map<Object, Object> map = new ConcurrentHashMap8<>();
+
+        /** {@inheritDoc} */
+        @Nullable @Override public Object load(Object key) {
+            return map.get(key);
+        }
+
+        /** {@inheritDoc} */
+        @Override public void write(Cache.Entry<?, ?> e) {
+            map.put(e.getKey(), e.getValue());
+        }
+
+        /** {@inheritDoc} */
+        @Override public void delete(Object key) {
+            map.remove(key);
+        }
+
+        /**
+         * @return Map.
+         */
+        Map<Object, Object> map() {
+            return map;
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/GridCachePortableStoreObjectsSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/GridCachePortableStoreObjectsSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/GridCachePortableStoreObjectsSelfTest.java
new file mode 100644
index 0000000..830978f
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/GridCachePortableStoreObjectsSelfTest.java
@@ -0,0 +1,55 @@
+/*
+ * 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.portable;
+
+import java.util.*;
+
+/**
+ * Tests for cache store with portables.
+ */
+public class GridCachePortableStoreObjectsSelfTest extends GridCachePortableStoreAbstractSelfTest {
+    /** {@inheritDoc} */
+    @Override protected boolean keepPortableInStore() {
+        return false;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void populateMap(Map<Object, Object> map, int... idxs) {
+        assert map != null;
+        assert idxs != null;
+
+        for (int idx : idxs)
+            map.put(new Key(idx), new Value(idx));
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void checkMap(Map<Object, Object> map, int... idxs) {
+        assert map != null;
+        assert idxs != null;
+
+        assertEquals(idxs.length, map.size());
+
+        for (int idx : idxs) {
+            Object val = map.get(new Key(idx));
+
+            assertTrue(String.valueOf(val), val instanceof Value);
+
+            assertEquals(idx, ((Value)val).index());
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/GridCachePortableStorePortablesSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/GridCachePortableStorePortablesSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/GridCachePortableStorePortablesSelfTest.java
new file mode 100644
index 0000000..9df6d18
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/GridCachePortableStorePortablesSelfTest.java
@@ -0,0 +1,67 @@
+/*
+ * 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.portable;
+
+import org.apache.ignite.portable.*;
+
+import java.util.*;
+
+/**
+ * Tests for cache store with portables.
+ */
+public class GridCachePortableStorePortablesSelfTest extends GridCachePortableStoreAbstractSelfTest {
+    /** {@inheritDoc} */
+    @Override protected boolean keepPortableInStore() {
+        return true;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void populateMap(Map<Object, Object> map, int... idxs) {
+        assert map != null;
+        assert idxs != null;
+
+        for (int idx : idxs)
+            map.put(portable(new Key(idx)), portable(new Value(idx)));
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void checkMap(Map<Object, Object> map, int... idxs) {
+        assert map != null;
+        assert idxs != null;
+
+        assertEquals(idxs.length, map.size());
+
+        for (int idx : idxs) {
+            Object val = map.get(portable(new Key(idx)));
+
+            assertTrue(String.valueOf(val), val instanceof PortableObject);
+
+            PortableObject po = (PortableObject)val;
+
+            assertEquals("Value", po.metaData().typeName());
+            assertEquals(new Integer(idx), po.field("idx"));
+        }
+    }
+
+    /**
+     * @param obj Object.
+     * @return Portable object.
+     */
+    private Object portable(Object obj) {
+        return grid().portables().toPortable(obj);
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/GridPortableCacheEntryMemorySizeSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/GridPortableCacheEntryMemorySizeSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/GridPortableCacheEntryMemorySizeSelfTest.java
new file mode 100644
index 0000000..37d7ad0
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/GridPortableCacheEntryMemorySizeSelfTest.java
@@ -0,0 +1,52 @@
+/*
+ * 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.portable;
+
+import org.apache.ignite.*;
+import org.apache.ignite.internal.portable.*;
+import org.apache.ignite.internal.processors.cache.*;
+import org.apache.ignite.internal.util.*;
+import org.apache.ignite.marshaller.*;
+import org.apache.ignite.marshaller.portable.*;
+import org.apache.ignite.portable.*;
+
+/**
+ *
+ */
+public class GridPortableCacheEntryMemorySizeSelfTest extends GridCacheEntryMemorySizeSelfTest {
+    /** {@inheritDoc} */
+    @Override protected Marshaller createMarshaller() throws IgniteCheckedException {
+        PortableMarshaller marsh = new PortableMarshaller();
+
+        marsh.setContext(new MarshallerContextTestImpl(null));
+
+        PortableContext pCtx = new PortableContext(new PortableMetaDataHandler() {
+            @Override public void addMeta(int typeId, PortableMetadata meta) throws PortableException {
+                // No-op
+            }
+
+            @Override public PortableMetadata metadata(int typeId) throws PortableException {
+                return null;
+            }
+        }, null);
+
+        IgniteUtils.invoke(PortableMarshaller.class, marsh, "setPortableContext", pCtx);
+
+        return marsh;
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/GridPortableDuplicateIndexObjectsAbstractSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/GridPortableDuplicateIndexObjectsAbstractSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/GridPortableDuplicateIndexObjectsAbstractSelfTest.java
new file mode 100644
index 0000000..dcf9a62
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/GridPortableDuplicateIndexObjectsAbstractSelfTest.java
@@ -0,0 +1,153 @@
+/*
+ * 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.portable;
+
+import org.apache.ignite.*;
+import org.apache.ignite.cache.*;
+import org.apache.ignite.cache.query.*;
+import org.apache.ignite.configuration.*;
+import org.apache.ignite.internal.processors.cache.*;
+import org.apache.ignite.internal.util.typedef.*;
+import org.apache.ignite.marshaller.portable.*;
+import org.apache.ignite.portable.*;
+
+import java.util.*;
+
+/**
+ * Tests that portable object is the same in cache entry and in index.
+ */
+public abstract class GridPortableDuplicateIndexObjectsAbstractSelfTest extends GridCacheAbstractSelfTest {
+    /** {@inheritDoc} */
+    @Override protected int gridCount() {
+        return 1;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception {
+        IgniteConfiguration cfg = super.getConfiguration(gridName);
+
+        PortableMarshaller marsh = new PortableMarshaller();
+
+        marsh.setClassNames(Collections.singletonList(TestPortable.class.getName()));
+
+        cfg.setMarshaller(marsh);
+
+        return cfg;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected CacheConfiguration cacheConfiguration(String gridName) throws Exception {
+        CacheConfiguration ccfg = super.cacheConfiguration(gridName);
+
+        ccfg.setCopyOnRead(false);
+
+        CacheTypeMetadata meta = new CacheTypeMetadata();
+
+        meta.setKeyType(Integer.class);
+        meta.setValueType(TestPortable.class.getName());
+
+        Map<String, Class<?>> idx = new HashMap<>();
+
+        idx.put("fieldOne", String.class);
+        idx.put("fieldTwo", Integer.class);
+
+        meta.setAscendingFields(idx);
+
+        ccfg.setTypeMetadata(Collections.singletonList(meta));
+
+        return ccfg;
+    }
+
+    /** {@inheritDoc} */
+    @Override public abstract CacheAtomicityMode atomicityMode();
+
+    /** {@inheritDoc} */
+    @Override public abstract CacheMode cacheMode();
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testIndexReferences() throws Exception {
+        IgniteCache<Integer, TestPortable> cache = grid(0).cache(null);
+
+        String fieldOneVal = "123";
+        int fieldTwoVal = 123;
+        int key = 0;
+
+        cache.put(key, new TestPortable(fieldOneVal, fieldTwoVal));
+
+        IgniteCache<Integer, PortableObject> prj = grid(0).cache(null).withKeepPortable();
+
+        PortableObject cacheVal = prj.get(key);
+
+        assertEquals(fieldOneVal, cacheVal.field("fieldOne"));
+        assertEquals(new Integer(fieldTwoVal), cacheVal.field("fieldTwo"));
+
+        List<?> row = F.first(prj.query(new SqlFieldsQuery("select _val from " +
+            "TestPortable where _key = ?").setArgs(key)).getAll());
+
+        assertEquals(1, row.size());
+
+        PortableObject qryVal = (PortableObject)row.get(0);
+
+        assertEquals(fieldOneVal, qryVal.field("fieldOne"));
+        assertEquals(new Integer(fieldTwoVal), qryVal.field("fieldTwo"));
+        assertSame(cacheVal, qryVal);
+    }
+
+    /**
+     * Test portable object.
+     */
+    private static class TestPortable {
+        /** */
+        private String fieldOne;
+
+        /** */
+        private int fieldTwo;
+
+        /**
+         *
+         */
+        private TestPortable() {
+            // No-op.
+        }
+
+        /**
+         * @param fieldOne Field one.
+         * @param fieldTwo Field two.
+         */
+        private TestPortable(String fieldOne, int fieldTwo) {
+            this.fieldOne = fieldOne;
+            this.fieldTwo = fieldTwo;
+        }
+
+        /**
+         * @return Field one.
+         */
+        public String fieldOne() {
+            return fieldOne;
+        }
+
+        /**
+         * @return Field two.
+         */
+        public int fieldTwo() {
+            return fieldTwo;
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/datastreaming/DataStreamProcessorPortableSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/datastreaming/DataStreamProcessorPortableSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/datastreaming/DataStreamProcessorPortableSelfTest.java
new file mode 100644
index 0000000..580ff13
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/datastreaming/DataStreamProcessorPortableSelfTest.java
@@ -0,0 +1,67 @@
+/*
+ * 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.portable.datastreaming;
+
+import org.apache.ignite.*;
+import org.apache.ignite.configuration.*;
+import org.apache.ignite.internal.processors.datastreamer.*;
+import org.apache.ignite.marshaller.portable.*;
+import org.apache.ignite.portable.*;
+import org.apache.ignite.spi.discovery.tcp.*;
+import org.apache.ignite.stream.*;
+
+import java.util.*;
+
+/**
+ *
+ */
+public class DataStreamProcessorPortableSelfTest extends DataStreamProcessorSelfTest {
+    /** {@inheritDoc} */
+    @Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception {
+        IgniteConfiguration cfg = super.getConfiguration(gridName);
+
+        PortableMarshaller marsh = new PortableMarshaller();
+
+        cfg.setMarshaller(marsh);
+
+        return cfg;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected StreamReceiver<String, TestObject> getStreamReceiver() {
+        return new TestDataReceiver();
+    }
+
+    /**
+     *
+     */
+    private static class TestDataReceiver implements StreamReceiver<String, TestObject> {
+        /** {@inheritDoc} */
+        @Override public void receive(IgniteCache<String, TestObject> cache,
+            Collection<Map.Entry<String, TestObject>> entries) {
+            for (Map.Entry<String, TestObject> e : entries) {
+                assertTrue(e.getKey() instanceof String);
+                assertTrue(e.getValue() instanceof PortableObject);
+
+                TestObject obj = ((PortableObject)e.getValue()).deserialize();
+
+                cache.put(e.getKey(), new TestObject(obj.val + 1));
+            }
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/datastreaming/GridDataStreamerImplSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/datastreaming/GridDataStreamerImplSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/datastreaming/GridDataStreamerImplSelfTest.java
new file mode 100644
index 0000000..2d8e34b
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/datastreaming/GridDataStreamerImplSelfTest.java
@@ -0,0 +1,338 @@
+/*
+ * 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.portable.datastreaming;
+
+import org.apache.ignite.*;
+import org.apache.ignite.cache.*;
+import org.apache.ignite.cluster.*;
+import org.apache.ignite.configuration.*;
+import org.apache.ignite.internal.processors.cache.*;
+import org.apache.ignite.internal.util.typedef.*;
+import org.apache.ignite.internal.util.typedef.internal.*;
+import org.apache.ignite.marshaller.portable.*;
+import org.apache.ignite.portable.*;
+import org.apache.ignite.spi.discovery.tcp.*;
+import org.apache.ignite.spi.discovery.tcp.ipfinder.*;
+import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.*;
+import org.apache.ignite.testframework.junits.common.*;
+
+import java.io.*;
+import java.util.*;
+
+import static org.apache.ignite.cache.CacheMode.*;
+import static org.apache.ignite.cache.CacheWriteSynchronizationMode.*;
+
+/**
+ * Tests for {@code IgniteDataStreamerImpl}.
+ */
+public class GridDataStreamerImplSelfTest extends GridCommonAbstractTest {
+    /** IP finder. */
+    private static final TcpDiscoveryIpFinder IP_FINDER = new TcpDiscoveryVmIpFinder(true);
+
+    /** Number of keys to load via data streamer. */
+    private static final int KEYS_COUNT = 1000;
+
+    /** Flag indicating should be cache configured with portables or not.  */
+    private static boolean portables;
+
+    /** {@inheritDoc} */
+    @Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception {
+        IgniteConfiguration cfg = super.getConfiguration(gridName);
+
+        TcpDiscoverySpi discoSpi = new TcpDiscoverySpi();
+        discoSpi.setIpFinder(IP_FINDER);
+
+        cfg.setDiscoverySpi(discoSpi);
+
+        if (portables) {
+            PortableMarshaller marsh = new PortableMarshaller();
+
+            cfg.setMarshaller(marsh);
+        }
+
+        cfg.setCacheConfiguration(cacheConfiguration());
+
+        return cfg;
+    }
+
+    /**
+     * Gets cache configuration.
+     *
+     * @return Cache configuration.
+     */
+    private CacheConfiguration cacheConfiguration() {
+        CacheConfiguration cacheCfg = defaultCacheConfiguration();
+
+        cacheCfg.setCacheMode(PARTITIONED);
+        cacheCfg.setNearConfiguration(null);
+        cacheCfg.setBackups(0);
+        cacheCfg.setWriteSynchronizationMode(FULL_SYNC);
+
+        return cacheCfg;
+    }
+
+    /**
+     * Data streamer should correctly load entries from HashMap in case of grids with more than one node
+     *  and with GridOptimizedMarshaller that requires serializable.
+     *
+     * @throws Exception If failed.
+     */
+    public void testAddDataFromMap() throws Exception {
+        try {
+            portables = false;
+
+            startGrids(2);
+
+            awaitPartitionMapExchange();
+
+            Ignite g0 = grid(0);
+
+            IgniteDataStreamer<Integer, String> dataLdr = g0.dataStreamer(null);
+
+            Map<Integer, String> map = U.newHashMap(KEYS_COUNT);
+
+            for (int i = 0; i < KEYS_COUNT; i ++)
+                map.put(i, String.valueOf(i));
+
+            dataLdr.addData(map);
+
+            dataLdr.close();
+
+            checkDistribution(grid(0));
+
+            checkDistribution(grid(1));
+
+            // Check several random keys in cache.
+            Random rnd = new Random();
+
+            IgniteCache<Integer, String> c0 = g0.cache(null);
+
+            for (int i = 0; i < 100; i ++) {
+                Integer k = rnd.nextInt(KEYS_COUNT);
+
+                String v = c0.get(k);
+
+                assertEquals(k.toString(), v);
+            }
+        }
+        finally {
+            G.stopAll(true);
+        }
+    }
+
+    /**
+     * Data streamer should add portable object that weren't registered explicitly.
+     *
+     * @throws Exception If failed.
+     */
+    public void testAddMissingPortable() throws Exception {
+        try {
+            portables = true;
+
+            startGrids(2);
+
+            awaitPartitionMapExchange();
+
+            Ignite g0 = grid(0);
+
+            IgniteDataStreamer<Integer, TestObject2> dataLdr = g0.dataStreamer(null);
+
+            dataLdr.perNodeBufferSize(1);
+            dataLdr.autoFlushFrequency(1L);
+
+            Map<Integer, TestObject2> map = U.newHashMap(KEYS_COUNT);
+
+            for (int i = 0; i < KEYS_COUNT; i ++)
+                map.put(i, new TestObject2(i));
+
+            dataLdr.addData(map).get();
+
+            dataLdr.close();
+        }
+        finally {
+            G.stopAll(true);
+        }
+    }
+
+    /**
+     * Data streamer should correctly load portable entries from HashMap in case of grids with more than one node
+     *  and with GridOptimizedMarshaller that requires serializable.
+     *
+     * @throws Exception If failed.
+     */
+    public void testAddPortableDataFromMap() throws Exception {
+        try {
+            portables = true;
+
+            startGrids(2);
+
+            awaitPartitionMapExchange();
+
+            Ignite g0 = grid(0);
+
+            IgniteDataStreamer<Integer, TestObject> dataLdr = g0.dataStreamer(null);
+
+            Map<Integer, TestObject> map = U.newHashMap(KEYS_COUNT);
+
+            for (int i = 0; i < KEYS_COUNT; i ++)
+                map.put(i, new TestObject(i));
+
+            dataLdr.addData(map);
+
+            dataLdr.close(false);
+
+            checkDistribution(grid(0));
+
+            checkDistribution(grid(1));
+
+            // Read random keys. Take values as TestObject.
+            Random rnd = new Random();
+
+            IgniteCache<Integer, TestObject> c = g0.cache(null);
+
+            for (int i = 0; i < 100; i ++) {
+                Integer k = rnd.nextInt(KEYS_COUNT);
+
+                TestObject v = c.get(k);
+
+                assertEquals(k, v.val());
+            }
+
+            // Read random keys. Take values as PortableObject.
+            IgniteCache<Integer, PortableObject> c2 = ((IgniteCacheProxy)c).keepPortable();
+
+            for (int i = 0; i < 100; i ++) {
+                Integer k = rnd.nextInt(KEYS_COUNT);
+
+                PortableObject v = c2.get(k);
+
+                assertEquals(k, v.field("val"));
+            }
+        }
+        finally {
+            G.stopAll(true);
+        }
+    }
+
+    /**
+     * Check that keys correctly destributed by nodes after data streamer.
+     *
+     * @param g Grid to check.
+     */
+    private void checkDistribution(Ignite g) {
+        ClusterNode n = g.cluster().localNode();
+        IgniteCache c = g.cache(null);
+
+        // Check that data streamer correctly split data by nodes.
+        for (int i = 0; i < KEYS_COUNT; i ++) {
+            if (g.affinity(null).isPrimary(n, i))
+                assertNotNull(c.localPeek(i, CachePeekMode.ONHEAP));
+            else
+                assertNull(c.localPeek(i, CachePeekMode.ONHEAP));
+        }
+    }
+
+    /**
+     */
+    private static class TestObject implements PortableMarshalAware, Serializable {
+        /** */
+        private int val;
+
+        /**
+         *
+         */
+        private TestObject() {
+            // No-op.
+        }
+
+        /**
+         * @param val Value.
+         */
+        private TestObject(int val) {
+            this.val = val;
+        }
+
+        public Integer val() {
+            return val;
+        }
+
+        /** {@inheritDoc} */
+        @Override public int hashCode() {
+            return val;
+        }
+
+        /** {@inheritDoc} */
+        @Override public boolean equals(Object obj) {
+            return obj instanceof TestObject && ((TestObject)obj).val == val;
+        }
+
+        /** {@inheritDoc} */
+        @Override public void writePortable(PortableWriter writer) throws PortableException {
+            writer.writeInt("val", val);
+        }
+
+        /** {@inheritDoc} */
+        @Override public void readPortable(PortableReader reader) throws PortableException {
+            val = reader.readInt("val");
+        }
+    }
+
+    /**
+     */
+    private static class TestObject2 implements PortableMarshalAware, Serializable {
+        /** */
+        private int val;
+
+        /**
+         */
+        private TestObject2() {
+            // No-op.
+        }
+
+        /**
+         * @param val Value.
+         */
+        private TestObject2(int val) {
+            this.val = val;
+        }
+
+        public Integer val() {
+            return val;
+        }
+
+        /** {@inheritDoc} */
+        @Override public int hashCode() {
+            return val;
+        }
+
+        /** {@inheritDoc} */
+        @Override public boolean equals(Object obj) {
+            return obj instanceof TestObject2 && ((TestObject2)obj).val == val;
+        }
+
+        /** {@inheritDoc} */
+        @Override public void writePortable(PortableWriter writer) throws PortableException {
+            writer.writeInt("val", val);
+        }
+
+        /** {@inheritDoc} */
+        @Override public void readPortable(PortableReader reader) throws PortableException {
+            val = reader.readInt("val");
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCacheAffinityRoutingPortableSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCacheAffinityRoutingPortableSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCacheAffinityRoutingPortableSelfTest.java
new file mode 100644
index 0000000..c7c0900
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCacheAffinityRoutingPortableSelfTest.java
@@ -0,0 +1,48 @@
+/*
+ * 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.portable.distributed.dht;
+
+import org.apache.ignite.configuration.*;
+import org.apache.ignite.internal.processors.cache.*;
+import org.apache.ignite.marshaller.portable.*;
+import org.apache.ignite.portable.*;
+
+import java.util.*;
+
+/**
+ *
+ */
+public class GridCacheAffinityRoutingPortableSelfTest extends GridCacheAffinityRoutingSelfTest {
+    /** {@inheritDoc} */
+    @Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception {
+        IgniteConfiguration cfg = super.getConfiguration(gridName);
+
+        PortableTypeConfiguration typeCfg = new PortableTypeConfiguration();
+
+        typeCfg.setClassName(AffinityTestKey.class.getName());
+        typeCfg.setAffinityKeyFieldName("affKey");
+
+        PortableMarshaller marsh = new PortableMarshaller();
+
+        marsh.setTypeConfigurations(Collections.singleton(typeCfg));
+
+        cfg.setMarshaller(marsh);
+
+        return cfg;
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCacheAtomicPartitionedOnlyPortableDataStreamerMultiNodeSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCacheAtomicPartitionedOnlyPortableDataStreamerMultiNodeSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCacheAtomicPartitionedOnlyPortableDataStreamerMultiNodeSelfTest.java
new file mode 100644
index 0000000..f69ede1
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCacheAtomicPartitionedOnlyPortableDataStreamerMultiNodeSelfTest.java
@@ -0,0 +1,29 @@
+/*
+ * 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.portable.distributed.dht;
+
+/**
+ *
+ */
+public class GridCacheAtomicPartitionedOnlyPortableDataStreamerMultiNodeSelfTest extends
+    GridCacheAtomicPartitionedOnlyPortableDataStreamerMultithreadedSelfTest {
+    /** {@inheritDoc} */
+    @Override protected int gridCount() {
+        return 4;
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCacheAtomicPartitionedOnlyPortableDataStreamerMultithreadedSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCacheAtomicPartitionedOnlyPortableDataStreamerMultithreadedSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCacheAtomicPartitionedOnlyPortableDataStreamerMultithreadedSelfTest.java
new file mode 100644
index 0000000..3d14447
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCacheAtomicPartitionedOnlyPortableDataStreamerMultithreadedSelfTest.java
@@ -0,0 +1,46 @@
+/*
+ * 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.portable.distributed.dht;
+
+import org.apache.ignite.cache.*;
+import org.apache.ignite.configuration.*;
+import org.apache.ignite.internal.processors.cache.portable.*;
+
+import static org.apache.ignite.cache.CacheAtomicityMode.*;
+import static org.apache.ignite.cache.CacheMode.*;
+
+/**
+ *
+ */
+public class GridCacheAtomicPartitionedOnlyPortableDataStreamerMultithreadedSelfTest extends
+    GridCachePortableObjectsAbstractDataStreamerSelfTest {
+    /** {@inheritDoc} */
+    @Override protected CacheMode cacheMode() {
+        return PARTITIONED;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected CacheAtomicityMode atomicityMode() {
+        return ATOMIC;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected NearCacheConfiguration nearConfiguration() {
+        return null;
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCacheAtomicPartitionedOnlyPortableMultiNodeSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCacheAtomicPartitionedOnlyPortableMultiNodeSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCacheAtomicPartitionedOnlyPortableMultiNodeSelfTest.java
new file mode 100644
index 0000000..94836db
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCacheAtomicPartitionedOnlyPortableMultiNodeSelfTest.java
@@ -0,0 +1,28 @@
+/*
+ * 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.portable.distributed.dht;
+
+/**
+ *
+ */
+public class GridCacheAtomicPartitionedOnlyPortableMultiNodeSelfTest extends
+    GridCacheAtomicPartitionedOnlyPortableMultithreadedSelfTest {
+    /** {@inheritDoc} */
+    @Override protected int gridCount() {
+        return 4;
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCacheAtomicPartitionedOnlyPortableMultithreadedSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCacheAtomicPartitionedOnlyPortableMultithreadedSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCacheAtomicPartitionedOnlyPortableMultithreadedSelfTest.java
new file mode 100644
index 0000000..9e0ebeb
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCacheAtomicPartitionedOnlyPortableMultithreadedSelfTest.java
@@ -0,0 +1,46 @@
+/*
+ * 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.portable.distributed.dht;
+
+import org.apache.ignite.cache.*;
+import org.apache.ignite.configuration.*;
+import org.apache.ignite.internal.processors.cache.portable.*;
+
+import static org.apache.ignite.cache.CacheAtomicityMode.*;
+import static org.apache.ignite.cache.CacheMode.*;
+
+/**
+ *
+ */
+public class GridCacheAtomicPartitionedOnlyPortableMultithreadedSelfTest extends
+    GridCachePortableObjectsAbstractMultiThreadedSelfTest {
+    /** {@inheritDoc} */
+    @Override protected CacheMode cacheMode() {
+        return PARTITIONED;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected CacheAtomicityMode atomicityMode() {
+        return ATOMIC;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected NearCacheConfiguration nearConfiguration() {
+        return null;
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCacheMemoryModePortableSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCacheMemoryModePortableSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCacheMemoryModePortableSelfTest.java
new file mode 100644
index 0000000..0160fb1
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/portable/distributed/dht/GridCacheMemoryModePortableSelfTest.java
@@ -0,0 +1,36 @@
+/*
+ * 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.portable.distributed.dht;
+
+import org.apache.ignite.configuration.*;
+import org.apache.ignite.internal.processors.cache.*;
+import org.apache.ignite.marshaller.portable.*;
+
+/**
+ * Memory models test.
+ */
+public class GridCacheMemoryModePortableSelfTest extends GridCacheMemoryModeSelfTest {
+    /** {@inheritDoc} */
+    @Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception {
+        IgniteConfiguration cfg = super.getConfiguration(gridName);
+
+        cfg.setMarshaller(new PortableMarshaller());
+
+        return cfg;
+    }
+}


[25/59] [abbrv] ignite git commit: IGNITE-1281 Fixed direct marshalling logic for last-removed field. Closes #32

Posted by vk...@apache.org.
IGNITE-1281 Fixed direct marshalling logic for last-removed field. Closes #32


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

Branch: refs/heads/ignite-884
Commit: 89e94b6308ee0b4c47e8d72417e238f8eb4a59a2
Parents: 3d0dac6
Author: Alexey Goncharuk <ag...@apache.org>
Authored: Tue Aug 25 16:40:59 2015 -0700
Committer: Alexey Goncharuk <ag...@gridgain.com>
Committed: Tue Aug 25 16:40:59 2015 -0700

----------------------------------------------------------------------
 .../ignite/codegen/MessageCodeGenerator.java    | 30 +++++++++++++-------
 .../ignite/internal/GridJobCancelRequest.java   |  2 +-
 .../ignite/internal/GridJobExecuteRequest.java  |  2 +-
 .../ignite/internal/GridJobExecuteResponse.java |  2 +-
 .../ignite/internal/GridJobSiblingsRequest.java |  2 +-
 .../internal/GridJobSiblingsResponse.java       |  2 +-
 .../ignite/internal/GridTaskCancelRequest.java  |  2 +-
 .../ignite/internal/GridTaskSessionRequest.java |  2 +-
 .../internal/direct/DirectByteBufferStream.java |  2 +-
 .../internal/direct/DirectMessageReader.java    |  6 ++++
 .../checkpoint/GridCheckpointRequest.java       |  2 +-
 .../managers/communication/GridIoManager.java   |  2 +-
 .../managers/communication/GridIoMessage.java   |  8 ++----
 .../communication/GridIoUserMessage.java        |  2 +-
 .../deployment/GridDeploymentInfoBean.java      |  2 +-
 .../deployment/GridDeploymentRequest.java       |  2 +-
 .../deployment/GridDeploymentResponse.java      |  2 +-
 .../eventstorage/GridEventStorageMessage.java   |  2 +-
 .../affinity/AffinityTopologyVersion.java       |  2 +-
 .../cache/CacheEntryInfoCollection.java         |  2 +-
 .../cache/CacheEntryPredicateAdapter.java       |  2 +-
 .../cache/CacheEntryPredicateContainsValue.java |  2 +-
 .../cache/CacheEntrySerializablePredicate.java  |  2 +-
 .../processors/cache/CacheEvictionEntry.java    |  2 +-
 .../cache/CacheInvokeDirectResult.java          |  2 +-
 .../processors/cache/CacheObjectAdapter.java    |  2 +-
 .../cache/CacheObjectByteArrayImpl.java         |  2 +-
 .../processors/cache/GridCacheEntryInfo.java    |  2 +-
 .../cache/GridCacheEvictionRequest.java         |  2 +-
 .../cache/GridCacheEvictionResponse.java        |  2 +-
 .../processors/cache/GridCacheMessage.java      |  2 +-
 .../processors/cache/GridCacheReturn.java       |  2 +-
 .../distributed/GridCacheTtlUpdateRequest.java  |  3 +-
 .../distributed/GridCacheTxRecoveryRequest.java |  2 +-
 .../GridCacheTxRecoveryResponse.java            |  2 +-
 .../distributed/GridDistributedBaseMessage.java |  2 +-
 .../distributed/GridDistributedLockRequest.java |  2 +-
 .../GridDistributedLockResponse.java            |  2 +-
 .../GridDistributedTxFinishRequest.java         |  8 ++----
 .../GridDistributedTxFinishResponse.java        |  2 +-
 .../GridDistributedTxPrepareRequest.java        |  8 ++----
 .../GridDistributedTxPrepareResponse.java       |  2 +-
 .../GridDistributedUnlockRequest.java           |  2 +-
 .../dht/GridDhtAffinityAssignmentRequest.java   |  2 +-
 .../dht/GridDhtAffinityAssignmentResponse.java  |  2 +-
 .../distributed/dht/GridDhtLockRequest.java     |  6 ++--
 .../distributed/dht/GridDhtLockResponse.java    |  2 +-
 .../distributed/dht/GridDhtTxFinishRequest.java |  2 +-
 .../dht/GridDhtTxFinishResponse.java            |  2 +-
 .../dht/GridDhtTxPrepareRequest.java            |  2 +-
 .../dht/GridDhtTxPrepareResponse.java           |  2 +-
 .../distributed/dht/GridDhtUnlockRequest.java   |  2 +-
 .../GridDhtAtomicDeferredUpdateResponse.java    |  2 +-
 .../dht/atomic/GridDhtAtomicUpdateRequest.java  |  2 +-
 .../dht/atomic/GridDhtAtomicUpdateResponse.java |  2 +-
 .../dht/atomic/GridNearAtomicUpdateRequest.java |  2 +-
 .../atomic/GridNearAtomicUpdateResponse.java    |  2 +-
 .../dht/preloader/GridDhtForceKeysRequest.java  |  3 +-
 .../dht/preloader/GridDhtForceKeysResponse.java |  4 +--
 .../GridDhtPartitionDemandMessage.java          |  2 +-
 .../preloader/GridDhtPartitionExchangeId.java   |  2 +-
 .../GridDhtPartitionSupplyMessage.java          |  2 +-
 .../GridDhtPartitionsAbstractMessage.java       |  2 +-
 .../preloader/GridDhtPartitionsFullMessage.java |  2 +-
 .../GridDhtPartitionsSingleMessage.java         |  2 +-
 .../GridDhtPartitionsSingleRequest.java         |  2 +-
 .../distributed/near/CacheVersionedValue.java   |  2 +-
 .../distributed/near/GridNearGetRequest.java    |  2 +-
 .../distributed/near/GridNearGetResponse.java   |  2 +-
 .../distributed/near/GridNearLockRequest.java   |  2 +-
 .../distributed/near/GridNearLockResponse.java  |  2 +-
 .../near/GridNearTxFinishRequest.java           |  2 +-
 .../near/GridNearTxFinishResponse.java          |  2 +-
 .../near/GridNearTxPrepareRequest.java          |  2 +-
 .../near/GridNearTxPrepareResponse.java         |  2 +-
 .../distributed/near/GridNearUnlockRequest.java |  2 +-
 .../cache/query/GridCacheQueryRequest.java      |  2 +-
 .../cache/query/GridCacheQueryResponse.java     |  2 +-
 .../cache/query/GridCacheSqlQuery.java          |  9 ++++--
 .../continuous/CacheContinuousQueryEntry.java   |  2 +-
 .../cache/transactions/IgniteTxEntry.java       |  2 +-
 .../cache/transactions/IgniteTxKey.java         |  2 +-
 .../cache/transactions/TxEntryValueHolder.java  |  2 +-
 .../version/GridCacheRawVersionedEntry.java     |  2 +-
 .../cache/version/GridCacheVersion.java         |  2 +-
 .../cache/version/GridCacheVersionEx.java       |  2 +-
 .../clock/GridClockDeltaSnapshotMessage.java    |  2 +-
 .../processors/clock/GridClockDeltaVersion.java |  2 +-
 .../continuous/GridContinuousMessage.java       |  2 +-
 .../datastreamer/DataStreamerEntry.java         |  2 +-
 .../datastreamer/DataStreamerRequest.java       |  2 +-
 .../datastreamer/DataStreamerResponse.java      |  2 +-
 .../processors/igfs/IgfsAckMessage.java         |  2 +-
 .../internal/processors/igfs/IgfsBlockKey.java  |  2 +-
 .../processors/igfs/IgfsBlocksMessage.java      |  2 +-
 .../igfs/IgfsCommunicationMessage.java          |  2 +-
 .../processors/igfs/IgfsDeleteMessage.java      |  2 +-
 .../processors/igfs/IgfsFileAffinityRange.java  |  9 ++++--
 .../igfs/IgfsFragmentizerRequest.java           |  2 +-
 .../igfs/IgfsFragmentizerResponse.java          |  2 +-
 .../processors/igfs/IgfsSyncMessage.java        |  2 +-
 .../messages/GridQueryCancelRequest.java        |  2 +-
 .../twostep/messages/GridQueryFailResponse.java |  2 +-
 .../messages/GridQueryNextPageRequest.java      |  2 +-
 .../messages/GridQueryNextPageResponse.java     |  3 +-
 .../h2/twostep/messages/GridQueryRequest.java   |  5 +++-
 .../handlers/task/GridTaskResultRequest.java    |  2 +-
 .../handlers/task/GridTaskResultResponse.java   |  2 +-
 .../ignite/internal/util/GridByteArrayList.java |  2 +-
 .../ignite/internal/util/GridLongList.java      |  2 +-
 .../internal/util/nio/GridDirectParser.java     |  2 +-
 .../communication/MessageFormatter.java         |  3 +-
 .../extensions/communication/MessageReader.java | 13 +++++++++
 .../org/apache/ignite/spi/IgniteSpiAdapter.java |  2 +-
 .../jobstealing/JobStealingRequest.java         |  2 +-
 .../communication/tcp/TcpCommunicationSpi.java  |  8 +++---
 .../testframework/GridSpiTestContext.java       |  2 +-
 117 files changed, 176 insertions(+), 152 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/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 0540148..cdbbd9e 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
@@ -142,6 +142,8 @@ public class MessageCodeGenerator {
 
         MessageCodeGenerator gen = new MessageCodeGenerator(srcDir);
 
+        gen.generateAll(true);
+
 //        gen.generateAndWrite(DataStreamerEntry.class);
 
 //        gen.generateAndWrite(GridDistributedLockRequest.class);
@@ -213,14 +215,19 @@ public class MessageCodeGenerator {
         Collection<Class<? extends Message>> classes = classes();
 
         for (Class<? extends Message> cls : classes) {
-            boolean isAbstract = Modifier.isAbstract(cls.getModifiers());
+            try {
+                boolean isAbstract = Modifier.isAbstract(cls.getModifiers());
 
-            System.out.println("Processing class: " + cls.getName() + (isAbstract ? " (abstract)" : ""));
+                System.out.println("Processing class: " + cls.getName() + (isAbstract ? " (abstract)" : ""));
 
-            if (write)
-                generateAndWrite(cls);
-            else
-                generate(cls);
+                if (write)
+                    generateAndWrite(cls);
+                else
+                    generate(cls);
+            }
+            catch (IllegalStateException e) {
+                System.out.println("Will skip class generation [cls=" + cls + ", err=" + e.getMessage() + ']');
+            }
         }
     }
 
@@ -370,8 +377,8 @@ public class MessageCodeGenerator {
 
         indent--;
 
-        finish(write);
-        finish(read);
+        finish(write, null);
+        finish(read, cls.getSimpleName());
     }
 
     /**
@@ -460,7 +467,7 @@ public class MessageCodeGenerator {
     /**
      * @param code Code lines.
      */
-    private void finish(Collection<String> code) {
+    private void finish(Collection<String> code, String readClsName) {
         assert code != null;
 
         if (!fields.isEmpty()) {
@@ -468,7 +475,10 @@ public class MessageCodeGenerator {
             code.add(EMPTY);
         }
 
-        code.add(builder().a("return true;").toString());
+        if (readClsName == null)
+            code.add(builder().a("return true;").toString());
+        else
+            code.add(builder().a("return reader.afterMessageRead(").a(readClsName).a(".class);").toString());
     }
 
     /**

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/GridJobCancelRequest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/GridJobCancelRequest.java b/modules/core/src/main/java/org/apache/ignite/internal/GridJobCancelRequest.java
index 005fff0..9766171 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/GridJobCancelRequest.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/GridJobCancelRequest.java
@@ -178,7 +178,7 @@ public class GridJobCancelRequest implements Message {
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridJobCancelRequest.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/GridJobExecuteRequest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/GridJobExecuteRequest.java b/modules/core/src/main/java/org/apache/ignite/internal/GridJobExecuteRequest.java
index 617762c..667f620 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/GridJobExecuteRequest.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/GridJobExecuteRequest.java
@@ -738,7 +738,7 @@ public class GridJobExecuteRequest implements Message {
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridJobExecuteRequest.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/GridJobExecuteResponse.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/GridJobExecuteResponse.java b/modules/core/src/main/java/org/apache/ignite/internal/GridJobExecuteResponse.java
index 459ba76..be1f929 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/GridJobExecuteResponse.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/GridJobExecuteResponse.java
@@ -329,7 +329,7 @@ public class GridJobExecuteResponse implements Message {
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridJobExecuteResponse.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/GridJobSiblingsRequest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/GridJobSiblingsRequest.java b/modules/core/src/main/java/org/apache/ignite/internal/GridJobSiblingsRequest.java
index 36fc1dd..71fe5a7 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/GridJobSiblingsRequest.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/GridJobSiblingsRequest.java
@@ -138,7 +138,7 @@ public class GridJobSiblingsRequest implements Message {
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridJobSiblingsRequest.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/GridJobSiblingsResponse.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/GridJobSiblingsResponse.java b/modules/core/src/main/java/org/apache/ignite/internal/GridJobSiblingsResponse.java
index c558f74..6ca0586 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/GridJobSiblingsResponse.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/GridJobSiblingsResponse.java
@@ -117,7 +117,7 @@ public class GridJobSiblingsResponse implements Message {
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridJobSiblingsResponse.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/GridTaskCancelRequest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/GridTaskCancelRequest.java b/modules/core/src/main/java/org/apache/ignite/internal/GridTaskCancelRequest.java
index a2a0e6c..32e082f 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/GridTaskCancelRequest.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/GridTaskCancelRequest.java
@@ -101,7 +101,7 @@ public class GridTaskCancelRequest implements Message {
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridTaskCancelRequest.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/GridTaskSessionRequest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/GridTaskSessionRequest.java b/modules/core/src/main/java/org/apache/ignite/internal/GridTaskSessionRequest.java
index b150a60..42e1506 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/GridTaskSessionRequest.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/GridTaskSessionRequest.java
@@ -166,7 +166,7 @@ public class GridTaskSessionRequest implements Message {
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridTaskSessionRequest.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/direct/DirectByteBufferStream.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/direct/DirectByteBufferStream.java b/modules/core/src/main/java/org/apache/ignite/internal/direct/DirectByteBufferStream.java
index 120350b..02b6be9 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/direct/DirectByteBufferStream.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/direct/DirectByteBufferStream.java
@@ -945,7 +945,7 @@ public class DirectByteBufferStream {
             msg = type == Byte.MIN_VALUE ? null : msgFactory.create(type);
 
             if (msg != null)
-                reader = msgFormatter.reader(msgFactory);
+                reader = msgFormatter.reader(msgFactory, msg.getClass());
 
             msgTypeDone = true;
         }

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/direct/DirectMessageReader.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/direct/DirectMessageReader.java b/modules/core/src/main/java/org/apache/ignite/internal/direct/DirectMessageReader.java
index 669ace1..91fb43f 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/direct/DirectMessageReader.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/direct/DirectMessageReader.java
@@ -55,6 +55,12 @@ public class DirectMessageReader implements MessageReader {
         return true;
     }
 
+    /** {@inheritDoc}
+     * @param msgCls*/
+    @Override public boolean afterMessageRead(Class<? extends Message> msgCls) {
+        return true;
+    }
+
     /** {@inheritDoc} */
     @Override public byte readByte(String name) {
         byte val = stream.readByte();

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/managers/checkpoint/GridCheckpointRequest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/managers/checkpoint/GridCheckpointRequest.java b/modules/core/src/main/java/org/apache/ignite/internal/managers/checkpoint/GridCheckpointRequest.java
index 8f97bf1..fdc3ee6 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/managers/checkpoint/GridCheckpointRequest.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/managers/checkpoint/GridCheckpointRequest.java
@@ -152,7 +152,7 @@ public class GridCheckpointRequest implements Message {
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridCheckpointRequest.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/managers/communication/GridIoManager.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/managers/communication/GridIoManager.java b/modules/core/src/main/java/org/apache/ignite/internal/managers/communication/GridIoManager.java
index 85e8421..6698f4f 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/managers/communication/GridIoManager.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/managers/communication/GridIoManager.java
@@ -235,7 +235,7 @@ public class GridIoManager extends GridManagerAdapter<CommunicationSpi<Serializa
                     return new DirectMessageWriter();
                 }
 
-                @Override public MessageReader reader(MessageFactory factory) {
+                @Override public MessageReader reader(MessageFactory factory, Class<? extends Message> msgCls) {
                     return new DirectMessageReader(msgFactory, this);
                 }
             };

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/managers/communication/GridIoMessage.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/managers/communication/GridIoMessage.java b/modules/core/src/main/java/org/apache/ignite/internal/managers/communication/GridIoMessage.java
index 6cf1ae5..844b62b 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/managers/communication/GridIoMessage.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/managers/communication/GridIoMessage.java
@@ -261,15 +261,11 @@ public class GridIoMessage implements Message {
                 reader.incrementState();
 
             case 2:
-                byte plc0;
-
-                plc0 = reader.readByte("plc");
+                plc = reader.readByte("plc");
 
                 if (!reader.isLastRead())
                     return false;
 
-                plc = plc0;
-
                 reader.incrementState();
 
             case 3:
@@ -306,7 +302,7 @@ public class GridIoMessage implements Message {
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridIoMessage.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/managers/communication/GridIoUserMessage.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/managers/communication/GridIoUserMessage.java b/modules/core/src/main/java/org/apache/ignite/internal/managers/communication/GridIoUserMessage.java
index 05b9181..dff4197 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/managers/communication/GridIoUserMessage.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/managers/communication/GridIoUserMessage.java
@@ -331,7 +331,7 @@ public class GridIoUserMessage implements Message {
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridIoUserMessage.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/managers/deployment/GridDeploymentInfoBean.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/managers/deployment/GridDeploymentInfoBean.java b/modules/core/src/main/java/org/apache/ignite/internal/managers/deployment/GridDeploymentInfoBean.java
index a62d4da..28ad0aa 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/managers/deployment/GridDeploymentInfoBean.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/managers/deployment/GridDeploymentInfoBean.java
@@ -237,7 +237,7 @@ public class GridDeploymentInfoBean implements Message, GridDeploymentInfo, Exte
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridDeploymentInfoBean.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/managers/deployment/GridDeploymentRequest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/managers/deployment/GridDeploymentRequest.java b/modules/core/src/main/java/org/apache/ignite/internal/managers/deployment/GridDeploymentRequest.java
index a6d80bb..1eec2c3 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/managers/deployment/GridDeploymentRequest.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/managers/deployment/GridDeploymentRequest.java
@@ -252,7 +252,7 @@ public class GridDeploymentRequest implements Message {
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridDeploymentRequest.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/managers/deployment/GridDeploymentResponse.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/managers/deployment/GridDeploymentResponse.java b/modules/core/src/main/java/org/apache/ignite/internal/managers/deployment/GridDeploymentResponse.java
index 175e85f..f91bf27 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/managers/deployment/GridDeploymentResponse.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/managers/deployment/GridDeploymentResponse.java
@@ -174,7 +174,7 @@ public class GridDeploymentResponse implements Message {
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridDeploymentResponse.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/managers/eventstorage/GridEventStorageMessage.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/managers/eventstorage/GridEventStorageMessage.java b/modules/core/src/main/java/org/apache/ignite/internal/managers/eventstorage/GridEventStorageMessage.java
index 6f18aa6..dc80832 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/managers/eventstorage/GridEventStorageMessage.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/managers/eventstorage/GridEventStorageMessage.java
@@ -417,7 +417,7 @@ public class GridEventStorageMessage implements Message {
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridEventStorageMessage.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/affinity/AffinityTopologyVersion.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/affinity/AffinityTopologyVersion.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/affinity/AffinityTopologyVersion.java
index 650c047..40dc64d 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/affinity/AffinityTopologyVersion.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/affinity/AffinityTopologyVersion.java
@@ -177,7 +177,7 @@ public class AffinityTopologyVersion implements Comparable<AffinityTopologyVersi
 
         }
 
-        return true;
+        return reader.afterMessageRead(AffinityTopologyVersion.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheEntryInfoCollection.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheEntryInfoCollection.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheEntryInfoCollection.java
index 52158f0..e346ec2 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheEntryInfoCollection.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheEntryInfoCollection.java
@@ -96,7 +96,7 @@ public class CacheEntryInfoCollection implements Message {
 
         }
 
-        return true;
+        return reader.afterMessageRead(CacheEntryInfoCollection.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheEntryPredicateAdapter.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheEntryPredicateAdapter.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheEntryPredicateAdapter.java
index c5b20b4..6253fcf 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheEntryPredicateAdapter.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheEntryPredicateAdapter.java
@@ -64,7 +64,7 @@ public abstract class CacheEntryPredicateAdapter implements CacheEntryPredicate
         if (!reader.beforeMessageRead())
             return false;
 
-        return true;
+        return reader.afterMessageRead(CacheEntryPredicateAdapter.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheEntryPredicateContainsValue.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheEntryPredicateContainsValue.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheEntryPredicateContainsValue.java
index c9fdf9f..03ff850 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheEntryPredicateContainsValue.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheEntryPredicateContainsValue.java
@@ -118,7 +118,7 @@ public class CacheEntryPredicateContainsValue extends CacheEntryPredicateAdapter
 
         }
 
-        return true;
+        return reader.afterMessageRead(CacheEntryPredicateContainsValue.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheEntrySerializablePredicate.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheEntrySerializablePredicate.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheEntrySerializablePredicate.java
index 0c07bfd..23ec70a 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheEntrySerializablePredicate.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheEntrySerializablePredicate.java
@@ -137,7 +137,7 @@ public class CacheEntrySerializablePredicate implements CacheEntryPredicate {
 
         }
 
-        return true;
+        return reader.afterMessageRead(CacheEntrySerializablePredicate.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheEvictionEntry.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheEvictionEntry.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheEvictionEntry.java
index 6d3ad5e..434a241 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheEvictionEntry.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheEvictionEntry.java
@@ -172,7 +172,7 @@ public class CacheEvictionEntry implements Message {
 
         }
 
-        return true;
+        return reader.afterMessageRead(CacheEvictionEntry.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheInvokeDirectResult.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheInvokeDirectResult.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheInvokeDirectResult.java
index 7b153d3..7b3a998e 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheInvokeDirectResult.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheInvokeDirectResult.java
@@ -198,7 +198,7 @@ public class CacheInvokeDirectResult implements Message {
 
         }
 
-        return true;
+        return reader.afterMessageRead(CacheInvokeDirectResult.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheObjectAdapter.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheObjectAdapter.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheObjectAdapter.java
index 173483d..6b2f46d 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheObjectAdapter.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheObjectAdapter.java
@@ -80,7 +80,7 @@ public abstract class CacheObjectAdapter implements CacheObject, Externalizable
 
         }
 
-        return true;
+        return reader.afterMessageRead(CacheObjectAdapter.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheObjectByteArrayImpl.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheObjectByteArrayImpl.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheObjectByteArrayImpl.java
index 96b838c..ecd4c43 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheObjectByteArrayImpl.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheObjectByteArrayImpl.java
@@ -126,7 +126,7 @@ public class CacheObjectByteArrayImpl implements CacheObject, Externalizable {
 
         }
 
-        return true;
+        return reader.afterMessageRead(CacheObjectByteArrayImpl.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheEntryInfo.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheEntryInfo.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheEntryInfo.java
index 4845635..3303cfc 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheEntryInfo.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheEntryInfo.java
@@ -317,7 +317,7 @@ public class GridCacheEntryInfo implements Message {
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridCacheEntryInfo.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheEvictionRequest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheEvictionRequest.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheEvictionRequest.java
index fba0771..3097114 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheEvictionRequest.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheEvictionRequest.java
@@ -220,7 +220,7 @@ public class GridCacheEvictionRequest extends GridCacheMessage implements GridCa
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridCacheEvictionRequest.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheEvictionResponse.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheEvictionResponse.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheEvictionResponse.java
index cd10e11..94a3e60 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheEvictionResponse.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheEvictionResponse.java
@@ -198,7 +198,7 @@ public class GridCacheEvictionResponse extends GridCacheMessage {
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridCacheEvictionResponse.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheMessage.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheMessage.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheMessage.java
index 8ebce35..67ac33d 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheMessage.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheMessage.java
@@ -635,7 +635,7 @@ public abstract class GridCacheMessage implements Message {
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridCacheMessage.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/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 743d42c..073dd2e 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
@@ -425,7 +425,7 @@ public class GridCacheReturn implements Externalizable, Message {
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridCacheReturn.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridCacheTtlUpdateRequest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridCacheTtlUpdateRequest.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridCacheTtlUpdateRequest.java
index 3ff7aa8..4c98c73 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridCacheTtlUpdateRequest.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridCacheTtlUpdateRequest.java
@@ -25,7 +25,6 @@ import org.apache.ignite.internal.processors.cache.version.*;
 import org.apache.ignite.internal.util.tostring.*;
 import org.apache.ignite.internal.util.typedef.internal.*;
 import org.apache.ignite.plugin.extensions.communication.*;
-import org.jetbrains.annotations.*;
 
 import java.nio.*;
 import java.util.*;
@@ -305,7 +304,7 @@ public class GridCacheTtlUpdateRequest extends GridCacheMessage {
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridCacheTtlUpdateRequest.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridCacheTxRecoveryRequest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridCacheTxRecoveryRequest.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridCacheTxRecoveryRequest.java
index 2f49ef4..07aecee 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridCacheTxRecoveryRequest.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridCacheTxRecoveryRequest.java
@@ -241,7 +241,7 @@ public class GridCacheTxRecoveryRequest extends GridDistributedBaseMessage {
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridCacheTxRecoveryRequest.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridCacheTxRecoveryResponse.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridCacheTxRecoveryResponse.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridCacheTxRecoveryResponse.java
index 99b676a..6218da6 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridCacheTxRecoveryResponse.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridCacheTxRecoveryResponse.java
@@ -162,7 +162,7 @@ public class GridCacheTxRecoveryResponse extends GridDistributedBaseMessage {
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridCacheTxRecoveryResponse.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedBaseMessage.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedBaseMessage.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedBaseMessage.java
index 7b84f32..3292583 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedBaseMessage.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedBaseMessage.java
@@ -275,7 +275,7 @@ public abstract class GridDistributedBaseMessage extends GridCacheMessage implem
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridDistributedBaseMessage.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedLockRequest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedLockRequest.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedLockRequest.java
index ecf3259..8bcf813 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedLockRequest.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedLockRequest.java
@@ -525,7 +525,7 @@ public class GridDistributedLockRequest extends GridDistributedBaseMessage {
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridDistributedLockRequest.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedLockResponse.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedLockResponse.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedLockResponse.java
index 295506a..de5eb63 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedLockResponse.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedLockResponse.java
@@ -303,7 +303,7 @@ public class GridDistributedLockResponse extends GridDistributedBaseMessage {
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridDistributedLockResponse.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedTxFinishRequest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedTxFinishRequest.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedTxFinishRequest.java
index 7a84f9a..63f7f16 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedTxFinishRequest.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedTxFinishRequest.java
@@ -359,15 +359,11 @@ public class GridDistributedTxFinishRequest extends GridDistributedBaseMessage {
                 reader.incrementState();
 
             case 12:
-                byte plcOrd;
-
-                plcOrd = reader.readByte("plc");
+                plc = reader.readByte("plc");
 
                 if (!reader.isLastRead())
                     return false;
 
-                plc = plcOrd;
-
                 reader.incrementState();
 
             case 13:
@@ -412,7 +408,7 @@ public class GridDistributedTxFinishRequest extends GridDistributedBaseMessage {
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridDistributedTxFinishRequest.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedTxFinishResponse.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedTxFinishResponse.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedTxFinishResponse.java
index b016cdd..88b8c71 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedTxFinishResponse.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedTxFinishResponse.java
@@ -134,7 +134,7 @@ public class GridDistributedTxFinishResponse extends GridCacheMessage {
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridDistributedTxFinishResponse.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedTxPrepareRequest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedTxPrepareRequest.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedTxPrepareRequest.java
index 20aa833..25f267d 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedTxPrepareRequest.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedTxPrepareRequest.java
@@ -502,15 +502,11 @@ public class GridDistributedTxPrepareRequest extends GridDistributedBaseMessage
                 reader.incrementState();
 
             case 13:
-                byte plcOrd;
-
-                plcOrd = reader.readByte("plc");
+                plc = reader.readByte("plc");
 
                 if (!reader.isLastRead())
                     return false;
 
-                plc = plcOrd;
-
                 reader.incrementState();
 
             case 14:
@@ -579,7 +575,7 @@ public class GridDistributedTxPrepareRequest extends GridDistributedBaseMessage
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridDistributedTxPrepareRequest.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedTxPrepareResponse.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedTxPrepareResponse.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedTxPrepareResponse.java
index f920e48..0f74780 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedTxPrepareResponse.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedTxPrepareResponse.java
@@ -151,7 +151,7 @@ public class GridDistributedTxPrepareResponse extends GridDistributedBaseMessage
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridDistributedTxPrepareResponse.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedUnlockRequest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedUnlockRequest.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedUnlockRequest.java
index 7f31b06..a88ca6b 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedUnlockRequest.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedUnlockRequest.java
@@ -138,7 +138,7 @@ public class GridDistributedUnlockRequest extends GridDistributedBaseMessage {
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridDistributedUnlockRequest.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtAffinityAssignmentRequest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtAffinityAssignmentRequest.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtAffinityAssignmentRequest.java
index 2f3fa23..c3025e3 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtAffinityAssignmentRequest.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtAffinityAssignmentRequest.java
@@ -125,7 +125,7 @@ public class GridDhtAffinityAssignmentRequest extends GridCacheMessage {
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridDhtAffinityAssignmentRequest.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtAffinityAssignmentResponse.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtAffinityAssignmentResponse.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtAffinityAssignmentResponse.java
index 4fc1b87..67919b3 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtAffinityAssignmentResponse.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtAffinityAssignmentResponse.java
@@ -199,7 +199,7 @@ public class GridDhtAffinityAssignmentResponse extends GridCacheMessage {
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridDhtAffinityAssignmentResponse.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtLockRequest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtLockRequest.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtLockRequest.java
index 7ce38f7..de4c9ef 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtLockRequest.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtLockRequest.java
@@ -465,9 +465,7 @@ public class GridDhtLockRequest extends GridDistributedLockRequest {
                 reader.incrementState();
 
             case 25:
-                ownedValues = reader.readObjectArray("ownedValues",
-                                                     MessageCollectionItemType.MSG,
-                                                     GridCacheVersion.class);
+                ownedValues = reader.readObjectArray("ownedValues", MessageCollectionItemType.MSG, GridCacheVersion.class);
 
                 if (!reader.isLastRead())
                     return false;
@@ -508,7 +506,7 @@ public class GridDhtLockRequest extends GridDistributedLockRequest {
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridDhtLockRequest.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtLockResponse.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtLockResponse.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtLockResponse.java
index 8c9f32c..505a63c 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtLockResponse.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtLockResponse.java
@@ -268,7 +268,7 @@ public class GridDhtLockResponse extends GridDistributedLockResponse {
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridDhtLockResponse.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtTxFinishRequest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtTxFinishRequest.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtTxFinishRequest.java
index fe72b24..f2b5317 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtTxFinishRequest.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtTxFinishRequest.java
@@ -385,7 +385,7 @@ public class GridDhtTxFinishRequest extends GridDistributedTxFinishRequest {
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridDhtTxFinishRequest.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtTxFinishResponse.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtTxFinishResponse.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtTxFinishResponse.java
index 5eff453..c6ac483 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtTxFinishResponse.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtTxFinishResponse.java
@@ -115,7 +115,7 @@ public class GridDhtTxFinishResponse extends GridDistributedTxFinishResponse {
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridDhtTxFinishResponse.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtTxPrepareRequest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtTxPrepareRequest.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtTxPrepareRequest.java
index 909080d..7a7769d 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtTxPrepareRequest.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtTxPrepareRequest.java
@@ -533,7 +533,7 @@ public class GridDhtTxPrepareRequest extends GridDistributedTxPrepareRequest {
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridDhtTxPrepareRequest.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtTxPrepareResponse.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtTxPrepareResponse.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtTxPrepareResponse.java
index bcf7f8b..da03521 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtTxPrepareResponse.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtTxPrepareResponse.java
@@ -345,7 +345,7 @@ public class GridDhtTxPrepareResponse extends GridDistributedTxPrepareResponse {
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridDhtTxPrepareResponse.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtUnlockRequest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtUnlockRequest.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtUnlockRequest.java
index f7f8167..eedcdb4 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtUnlockRequest.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtUnlockRequest.java
@@ -142,7 +142,7 @@ public class GridDhtUnlockRequest extends GridDistributedUnlockRequest {
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridDhtUnlockRequest.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridDhtAtomicDeferredUpdateResponse.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridDhtAtomicDeferredUpdateResponse.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridDhtAtomicDeferredUpdateResponse.java
index 1163761..db14b3d 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridDhtAtomicDeferredUpdateResponse.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridDhtAtomicDeferredUpdateResponse.java
@@ -119,7 +119,7 @@ public class GridDhtAtomicDeferredUpdateResponse extends GridCacheMessage implem
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridDhtAtomicDeferredUpdateResponse.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridDhtAtomicUpdateRequest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridDhtAtomicUpdateRequest.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridDhtAtomicUpdateRequest.java
index f83b8fa..514ab5b 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridDhtAtomicUpdateRequest.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridDhtAtomicUpdateRequest.java
@@ -884,7 +884,7 @@ public class GridDhtAtomicUpdateRequest extends GridCacheMessage implements Grid
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridDhtAtomicUpdateRequest.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridDhtAtomicUpdateResponse.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridDhtAtomicUpdateResponse.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridDhtAtomicUpdateResponse.java
index c5b5a37..8a2befb 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridDhtAtomicUpdateResponse.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridDhtAtomicUpdateResponse.java
@@ -262,7 +262,7 @@ public class GridDhtAtomicUpdateResponse extends GridCacheMessage implements Gri
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridDhtAtomicUpdateResponse.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridNearAtomicUpdateRequest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridNearAtomicUpdateRequest.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridNearAtomicUpdateRequest.java
index 86c5ab8..670995b 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridNearAtomicUpdateRequest.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridNearAtomicUpdateRequest.java
@@ -921,7 +921,7 @@ public class GridNearAtomicUpdateRequest extends GridCacheMessage implements Gri
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridNearAtomicUpdateRequest.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridNearAtomicUpdateResponse.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridNearAtomicUpdateResponse.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridNearAtomicUpdateResponse.java
index 330e43c..3bf99c0 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridNearAtomicUpdateResponse.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridNearAtomicUpdateResponse.java
@@ -602,7 +602,7 @@ public class GridNearAtomicUpdateResponse extends GridCacheMessage implements Gr
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridNearAtomicUpdateResponse.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtForceKeysRequest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtForceKeysRequest.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtForceKeysRequest.java
index 29823f9..83d139c 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtForceKeysRequest.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtForceKeysRequest.java
@@ -26,7 +26,6 @@ import org.apache.ignite.internal.util.typedef.*;
 import org.apache.ignite.internal.util.typedef.internal.*;
 import org.apache.ignite.lang.*;
 import org.apache.ignite.plugin.extensions.communication.*;
-import org.jetbrains.annotations.*;
 
 import java.io.*;
 import java.nio.*;
@@ -243,7 +242,7 @@ public class GridDhtForceKeysRequest extends GridCacheMessage implements GridCac
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridDhtForceKeysRequest.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtForceKeysResponse.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtForceKeysResponse.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtForceKeysResponse.java
index 41ce0be..8bb6b3a 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtForceKeysResponse.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtForceKeysResponse.java
@@ -82,7 +82,7 @@ public class GridDhtForceKeysResponse extends GridCacheMessage implements GridCa
 
     /**
      * Sets error.
-     * @param err
+     * @param err Error.
      */
     public void error(IgniteCheckedException err){
         this.err = err;
@@ -288,7 +288,7 @@ public class GridDhtForceKeysResponse extends GridCacheMessage implements GridCa
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridDhtForceKeysResponse.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtPartitionDemandMessage.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtPartitionDemandMessage.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtPartitionDemandMessage.java
index a849b54..4beee06 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtPartitionDemandMessage.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtPartitionDemandMessage.java
@@ -308,7 +308,7 @@ public class GridDhtPartitionDemandMessage extends GridCacheMessage {
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridDhtPartitionDemandMessage.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtPartitionExchangeId.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtPartitionExchangeId.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtPartitionExchangeId.java
index 8a3287c..3320d62 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtPartitionExchangeId.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtPartitionExchangeId.java
@@ -217,7 +217,7 @@ public class GridDhtPartitionExchangeId implements Message, Comparable<GridDhtPa
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridDhtPartitionExchangeId.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtPartitionSupplyMessage.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtPartitionSupplyMessage.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtPartitionSupplyMessage.java
index 75846a1..bda526b 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtPartitionSupplyMessage.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtPartitionSupplyMessage.java
@@ -374,7 +374,7 @@ public class GridDhtPartitionSupplyMessage extends GridCacheMessage implements G
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridDhtPartitionSupplyMessage.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtPartitionsAbstractMessage.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtPartitionsAbstractMessage.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtPartitionsAbstractMessage.java
index 5a8616d..ff40daa 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtPartitionsAbstractMessage.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtPartitionsAbstractMessage.java
@@ -140,7 +140,7 @@ abstract class GridDhtPartitionsAbstractMessage extends GridCacheMessage {
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridDhtPartitionsAbstractMessage.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtPartitionsFullMessage.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtPartitionsFullMessage.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtPartitionsFullMessage.java
index 73794ae..c285215 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtPartitionsFullMessage.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtPartitionsFullMessage.java
@@ -180,7 +180,7 @@ public class GridDhtPartitionsFullMessage extends GridDhtPartitionsAbstractMessa
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridDhtPartitionsFullMessage.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtPartitionsSingleMessage.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtPartitionsSingleMessage.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtPartitionsSingleMessage.java
index 713a80b..d9633d2 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtPartitionsSingleMessage.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtPartitionsSingleMessage.java
@@ -170,7 +170,7 @@ public class GridDhtPartitionsSingleMessage extends GridDhtPartitionsAbstractMes
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridDhtPartitionsSingleMessage.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtPartitionsSingleRequest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtPartitionsSingleRequest.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtPartitionsSingleRequest.java
index 7578e97..0b443f8 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtPartitionsSingleRequest.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtPartitionsSingleRequest.java
@@ -71,7 +71,7 @@ public class GridDhtPartitionsSingleRequest extends GridDhtPartitionsAbstractMes
         if (!super.readFrom(buf, reader))
             return false;
 
-        return true;
+        return reader.afterMessageRead(GridDhtPartitionsSingleRequest.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/CacheVersionedValue.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/CacheVersionedValue.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/CacheVersionedValue.java
index 97b96c8..745ca17 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/CacheVersionedValue.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/CacheVersionedValue.java
@@ -149,7 +149,7 @@ public class CacheVersionedValue implements Message {
 
         }
 
-        return true;
+        return reader.afterMessageRead(CacheVersionedValue.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearGetRequest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearGetRequest.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearGetRequest.java
index 93c869d..4b52e69 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearGetRequest.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearGetRequest.java
@@ -461,7 +461,7 @@ public class GridNearGetRequest extends GridCacheMessage implements GridCacheDep
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridNearGetRequest.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearGetResponse.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearGetResponse.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearGetResponse.java
index 73d877a..25a6969 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearGetResponse.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearGetResponse.java
@@ -331,7 +331,7 @@ public class GridNearGetResponse extends GridCacheMessage implements GridCacheDe
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridNearGetResponse.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearLockRequest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearLockRequest.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearLockRequest.java
index 4776963..4440e89 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearLockRequest.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearLockRequest.java
@@ -577,7 +577,7 @@ public class GridNearLockRequest extends GridDistributedLockRequest {
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridNearLockRequest.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearLockResponse.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearLockResponse.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearLockResponse.java
index 62002dc..110501b 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearLockResponse.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearLockResponse.java
@@ -307,7 +307,7 @@ public class GridNearLockResponse extends GridDistributedLockResponse {
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridNearLockResponse.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearTxFinishRequest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearTxFinishRequest.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearTxFinishRequest.java
index 26e4bdc..5730357 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearTxFinishRequest.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearTxFinishRequest.java
@@ -271,7 +271,7 @@ public class GridNearTxFinishRequest extends GridDistributedTxFinishRequest {
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridNearTxFinishRequest.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearTxFinishResponse.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearTxFinishResponse.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearTxFinishResponse.java
index 68e23ce..84f4f46 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearTxFinishResponse.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearTxFinishResponse.java
@@ -188,7 +188,7 @@ public class GridNearTxFinishResponse extends GridDistributedTxFinishResponse {
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridNearTxFinishResponse.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearTxPrepareRequest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearTxPrepareRequest.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearTxPrepareRequest.java
index 4cc8f91..f018d18 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearTxPrepareRequest.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearTxPrepareRequest.java
@@ -470,7 +470,7 @@ public class GridNearTxPrepareRequest extends GridDistributedTxPrepareRequest {
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridNearTxPrepareRequest.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearTxPrepareResponse.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearTxPrepareResponse.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearTxPrepareResponse.java
index b24c62d..6f8e334 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearTxPrepareResponse.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearTxPrepareResponse.java
@@ -514,7 +514,7 @@ public class GridNearTxPrepareResponse extends GridDistributedTxPrepareResponse
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridNearTxPrepareResponse.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearUnlockRequest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearUnlockRequest.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearUnlockRequest.java
index 292e04d..14f468f 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearUnlockRequest.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearUnlockRequest.java
@@ -73,7 +73,7 @@ public class GridNearUnlockRequest extends GridDistributedUnlockRequest {
         if (!super.readFrom(buf, reader))
             return false;
 
-        return true;
+        return reader.afterMessageRead(GridNearUnlockRequest.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/GridCacheQueryRequest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/GridCacheQueryRequest.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/GridCacheQueryRequest.java
index 2113e7a..76ddebd 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/GridCacheQueryRequest.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/GridCacheQueryRequest.java
@@ -732,7 +732,7 @@ public class GridCacheQueryRequest extends GridCacheMessage implements GridCache
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridCacheQueryRequest.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/GridCacheQueryResponse.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/GridCacheQueryResponse.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/GridCacheQueryResponse.java
index 1988cff..95f7dfa 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/GridCacheQueryResponse.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/GridCacheQueryResponse.java
@@ -318,7 +318,7 @@ public class GridCacheQueryResponse extends GridCacheMessage implements GridCach
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridCacheQueryResponse.class);
     }
 
     /** {@inheritDoc} */


[16/59] [abbrv] ignite git commit: IGNITE-1288: Implemented basic platform processor infrastructure.

Posted by vk...@apache.org.
IGNITE-1288: Implemented basic platform processor infrastructure.


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

Branch: refs/heads/ignite-884
Commit: 3fbb99c1212a7835c256b9ead8e25279d517c905
Parents: a03584a
Author: vozerov-gridgain <vo...@gridgain.com>
Authored: Tue Aug 25 11:25:01 2015 +0300
Committer: vozerov-gridgain <vo...@gridgain.com>
Committed: Tue Aug 25 11:25:01 2015 +0300

----------------------------------------------------------------------
 .../ignite/internal/GridKernalContext.java      |  6 +++
 .../ignite/internal/GridKernalContextImpl.java  | 12 ++++++
 .../org/apache/ignite/internal/IgniteEx.java    |  1 +
 .../apache/ignite/internal/IgniteKernal.java    |  5 +++
 .../platform/PlatformNoopProcessor.java         | 41 ++++++++++++++++++++
 .../processors/platform/PlatformProcessor.java  | 40 +++++++++++++++++++
 .../ignite/internal/platform/Platform.java      | 39 -------------------
 .../internal/platform/PlatformBootstrap.java    |  5 ++-
 .../internal/platform/PlatformIgnition.java     | 19 ++++-----
 9 files changed, 118 insertions(+), 50 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/3fbb99c1/modules/core/src/main/java/org/apache/ignite/internal/GridKernalContext.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/GridKernalContext.java b/modules/core/src/main/java/org/apache/ignite/internal/GridKernalContext.java
index f4da333..4e15a7a 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/GridKernalContext.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/GridKernalContext.java
@@ -43,6 +43,7 @@ import org.apache.ignite.internal.processors.igfs.*;
 import org.apache.ignite.internal.processors.job.*;
 import org.apache.ignite.internal.processors.jobmetrics.*;
 import org.apache.ignite.internal.processors.offheap.*;
+import org.apache.ignite.internal.processors.platform.*;
 import org.apache.ignite.internal.processors.plugin.*;
 import org.apache.ignite.internal.processors.port.*;
 import org.apache.ignite.internal.processors.query.*;
@@ -562,4 +563,9 @@ public interface GridKernalContext extends Iterable<GridComponent> {
      * @return {@code True} if local node in disconnected state.
      */
     public boolean clientDisconnected();
+
+    /**
+     * @return Platform processor.
+     */
+    public PlatformProcessor platform();
 }

http://git-wip-us.apache.org/repos/asf/ignite/blob/3fbb99c1/modules/core/src/main/java/org/apache/ignite/internal/GridKernalContextImpl.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/GridKernalContextImpl.java b/modules/core/src/main/java/org/apache/ignite/internal/GridKernalContextImpl.java
index 01dadfd..d0a0fe7 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/GridKernalContextImpl.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/GridKernalContextImpl.java
@@ -45,6 +45,7 @@ import org.apache.ignite.internal.processors.igfs.*;
 import org.apache.ignite.internal.processors.job.*;
 import org.apache.ignite.internal.processors.jobmetrics.*;
 import org.apache.ignite.internal.processors.offheap.*;
+import org.apache.ignite.internal.processors.platform.*;
 import org.apache.ignite.internal.processors.plugin.*;
 import org.apache.ignite.internal.processors.port.*;
 import org.apache.ignite.internal.processors.query.*;
@@ -236,6 +237,10 @@ public class GridKernalContextImpl implements GridKernalContext, Externalizable
 
     /** */
     @GridToStringExclude
+    private PlatformProcessor platformProc;
+
+    /** */
+    @GridToStringExclude
     private IgniteSpringHelper spring;
 
     /** */
@@ -486,6 +491,8 @@ public class GridKernalContextImpl implements GridKernalContext, Externalizable
             dataStructuresProc = (DataStructuresProcessor)comp;
         else if (comp instanceof ClusterProcessor)
             cluster = (ClusterProcessor)comp;
+        else if (comp instanceof PlatformProcessor)
+            platformProc = (PlatformProcessor)comp;
         else if (!(comp instanceof DiscoveryNodeValidationProcessor))
             assert (comp instanceof GridPluginComponent) : "Unknown manager class: " + comp.getClass();
 
@@ -925,6 +932,11 @@ public class GridKernalContextImpl implements GridKernalContext, Externalizable
         return locNode != null ? (locNode.isClient() && disconnected) : false;
     }
 
+    /** {@inheritDoc} */
+    @Override public PlatformProcessor platform() {
+        return platformProc;
+    }
+
     /**
      * @param disconnected Disconnected flag.
      */

http://git-wip-us.apache.org/repos/asf/ignite/blob/3fbb99c1/modules/core/src/main/java/org/apache/ignite/internal/IgniteEx.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/IgniteEx.java b/modules/core/src/main/java/org/apache/ignite/internal/IgniteEx.java
index 4845d51..ef733cf 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/IgniteEx.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/IgniteEx.java
@@ -22,6 +22,7 @@ import org.apache.ignite.cluster.*;
 import org.apache.ignite.internal.cluster.*;
 import org.apache.ignite.internal.processors.cache.*;
 import org.apache.ignite.internal.processors.hadoop.*;
+import org.apache.ignite.internal.processors.platform.*;
 import org.apache.ignite.lang.*;
 import org.jetbrains.annotations.*;
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/3fbb99c1/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 391d3dc..1db73bf 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
@@ -49,6 +49,7 @@ import org.apache.ignite.internal.processors.job.*;
 import org.apache.ignite.internal.processors.jobmetrics.*;
 import org.apache.ignite.internal.processors.nodevalidation.*;
 import org.apache.ignite.internal.processors.offheap.*;
+import org.apache.ignite.internal.processors.platform.*;
 import org.apache.ignite.internal.processors.plugin.*;
 import org.apache.ignite.internal.processors.port.*;
 import org.apache.ignite.internal.processors.query.*;
@@ -790,6 +791,7 @@ public class IgniteKernal implements IgniteEx, IgniteMXBean, Externalizable {
                 IgniteComponentType.HADOOP.createIfInClassPath(ctx, cfg.getHadoopConfiguration() != null)));
             startProcessor(new GridServiceProcessor(ctx));
             startProcessor(new DataStructuresProcessor(ctx));
+            startProcessor(createComponent(PlatformProcessor.class, ctx));
 
             // Start plugins.
             for (PluginProvider provider : ctx.plugins().allProviders()) {
@@ -2971,6 +2973,9 @@ public class IgniteKernal implements IgniteEx, IgniteMXBean, Externalizable {
         if (cls.equals(DiscoveryNodeValidationProcessor.class))
             return (T)new OsDiscoveryNodeValidationProcessor(ctx);
 
+        if (cls.equals(PlatformProcessor.class))
+            return (T)new PlatformNoopProcessor(ctx);
+
         Class<T> implCls = null;
 
         try {

http://git-wip-us.apache.org/repos/asf/ignite/blob/3fbb99c1/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/PlatformNoopProcessor.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/PlatformNoopProcessor.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/PlatformNoopProcessor.java
new file mode 100644
index 0000000..245d4d7
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/PlatformNoopProcessor.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.internal.processors.platform;
+
+import org.apache.ignite.*;
+import org.apache.ignite.internal.*;
+import org.apache.ignite.internal.processors.*;
+
+/**
+ * No-op processor.
+ */
+public class PlatformNoopProcessor extends GridProcessorAdapter implements PlatformProcessor {
+    public PlatformNoopProcessor(GridKernalContext ctx) {
+        super(ctx);
+    }
+
+    /** {@inheritDoc} */
+    @Override public Ignite ignite() {
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public long environmentPointer() {
+        return 0;
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/3fbb99c1/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/PlatformProcessor.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/PlatformProcessor.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/PlatformProcessor.java
new file mode 100644
index 0000000..137c31b
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/PlatformProcessor.java
@@ -0,0 +1,40 @@
+/*
+ * 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.platform;
+
+import org.apache.ignite.*;
+import org.apache.ignite.internal.processors.*;
+
+/**
+ * Platform processor.
+ */
+public interface PlatformProcessor extends GridProcessor {
+    /**
+     * Get owning Ignite instance.
+     *
+     * @return Ignite instance.
+     */
+    public Ignite ignite();
+
+    /**
+     * Get environment pointer associated with this processor.
+     *
+     * @return Environment pointer.
+     */
+    public long environmentPointer();
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/3fbb99c1/modules/platform/src/main/java/org/apache/ignite/internal/platform/Platform.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/platform/Platform.java b/modules/platform/src/main/java/org/apache/ignite/internal/platform/Platform.java
deleted file mode 100644
index 6306723..0000000
--- a/modules/platform/src/main/java/org/apache/ignite/internal/platform/Platform.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * 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.platform;
-
-import org.apache.ignite.*;
-
-/**
- * Platform entry point.
- */
-public interface Platform {
-    /**
-     * Get owning Ignite instance.
-     *
-     * @return Ignite instance.
-     */
-    public Ignite ignite();
-
-    /**
-     * Get environment pointer associated with this processor.
-     *
-     * @return Environment pointer.
-     */
-    public long environmentPointer();
-}

http://git-wip-us.apache.org/repos/asf/ignite/blob/3fbb99c1/modules/platform/src/main/java/org/apache/ignite/internal/platform/PlatformBootstrap.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/platform/PlatformBootstrap.java b/modules/platform/src/main/java/org/apache/ignite/internal/platform/PlatformBootstrap.java
index 1044445..faee665 100644
--- a/modules/platform/src/main/java/org/apache/ignite/internal/platform/PlatformBootstrap.java
+++ b/modules/platform/src/main/java/org/apache/ignite/internal/platform/PlatformBootstrap.java
@@ -18,6 +18,7 @@
 package org.apache.ignite.internal.platform;
 
 import org.apache.ignite.configuration.*;
+import org.apache.ignite.internal.processors.platform.*;
 
 /**
  * Platform bootstrap. Responsible for starting Ignite node with non-Java platform.
@@ -29,7 +30,7 @@ public interface PlatformBootstrap {
      * @param cfg Configuration.
      * @param envPtr Environment pointer.
      * @param dataPtr Optional pointer to additional data required for startup.
-     * @return Ignite node.
+     * @return Platform processor.
      */
-    public Platform start(IgniteConfiguration cfg, long envPtr, long dataPtr);
+    public PlatformProcessor start(IgniteConfiguration cfg, long envPtr, long dataPtr);
 }

http://git-wip-us.apache.org/repos/asf/ignite/blob/3fbb99c1/modules/platform/src/main/java/org/apache/ignite/internal/platform/PlatformIgnition.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/platform/PlatformIgnition.java b/modules/platform/src/main/java/org/apache/ignite/internal/platform/PlatformIgnition.java
index 685cded..2d31307 100644
--- a/modules/platform/src/main/java/org/apache/ignite/internal/platform/PlatformIgnition.java
+++ b/modules/platform/src/main/java/org/apache/ignite/internal/platform/PlatformIgnition.java
@@ -20,6 +20,7 @@ package org.apache.ignite.internal.platform;
 import org.apache.ignite.*;
 import org.apache.ignite.configuration.*;
 import org.apache.ignite.internal.*;
+import org.apache.ignite.internal.processors.platform.*;
 import org.apache.ignite.internal.processors.resource.*;
 import org.apache.ignite.internal.util.typedef.internal.*;
 import org.apache.ignite.lang.*;
@@ -35,7 +36,7 @@ import java.util.*;
 @SuppressWarnings("UnusedDeclaration")
 public class PlatformIgnition {
     /** Map with active instances. */
-    private static final HashMap<String, Platform> instances = new HashMap<>();
+    private static final HashMap<String, PlatformProcessor> instances = new HashMap<>();
 
     /**
      * Start Ignite node in platform mode.
@@ -47,14 +48,14 @@ public class PlatformIgnition {
      * @param dataPtr Optional pointer to additional data required for startup.
      * @return Ignite instance.
      */
-    public static synchronized Platform start(@Nullable String springCfgPath, @Nullable String gridName,
+    public static synchronized PlatformProcessor start(@Nullable String springCfgPath, @Nullable String gridName,
         int factoryId, long envPtr, long dataPtr) {
         if (envPtr <= 0)
             throw new IgniteException("Environment pointer must be positive.");
 
         ClassLoader oldClsLdr = Thread.currentThread().getContextClassLoader();
 
-        Thread.currentThread().setContextClassLoader(Platform.class.getClassLoader());
+        Thread.currentThread().setContextClassLoader(PlatformProcessor.class.getClassLoader());
 
         try {
             IgniteConfiguration cfg = configuration(springCfgPath);
@@ -66,9 +67,9 @@ public class PlatformIgnition {
 
             PlatformBootstrap bootstrap = bootstrap(factoryId);
 
-            Platform proc = bootstrap.start(cfg, envPtr, dataPtr);
+            PlatformProcessor proc = bootstrap.start(cfg, envPtr, dataPtr);
 
-            Platform old = instances.put(gridName, proc);
+            PlatformProcessor old = instances.put(gridName, proc);
 
             assert old == null;
 
@@ -85,7 +86,7 @@ public class PlatformIgnition {
      * @param gridName Grid name.
      * @return Instance or {@code null} if it doesn't exist (never started or stopped).
      */
-    @Nullable public static synchronized Platform instance(@Nullable String gridName) {
+    @Nullable public static synchronized PlatformProcessor instance(@Nullable String gridName) {
         return instances.get(gridName);
     }
 
@@ -96,7 +97,7 @@ public class PlatformIgnition {
      * @return Environment pointer or {@code 0} in case grid with such name doesn't exist.
      */
     public static synchronized long environmentPointer(@Nullable String gridName) {
-        Platform proc = instance(gridName);
+        PlatformProcessor proc = instance(gridName);
 
         return proc != null ? proc.environmentPointer() : 0;
     }
@@ -110,7 +111,7 @@ public class PlatformIgnition {
      */
     public static synchronized boolean stop(@Nullable String gridName, boolean cancel) {
         if (Ignition.stop(gridName, cancel)) {
-            Platform old = instances.remove(gridName);
+            PlatformProcessor old = instances.remove(gridName);
 
             assert old != null;
 
@@ -126,7 +127,7 @@ public class PlatformIgnition {
      * @param cancel Cancel flag.
      */
     public static synchronized void stopAll(boolean cancel) {
-        for (Platform proc : instances.values())
+        for (PlatformProcessor proc : instances.values())
             Ignition.stop(proc.ignite().name(), cancel);
 
         instances.clear();


[59/59] [abbrv] ignite git commit: Merge remote-tracking branch 'apache/master' into ignite-884

Posted by vk...@apache.org.
Merge remote-tracking branch 'apache/master' into ignite-884

# Conflicts:
#	modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheProcessor.java


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

Branch: refs/heads/ignite-884
Commit: 1a83d65adab4f634ccd3a4e00d0d9334259b89f5
Parents: e34872d
Author: Valentin Kulichenko <va...@gmail.com>
Authored: Wed Aug 26 17:10:33 2015 -0700
Committer: Valentin Kulichenko <va...@gmail.com>
Committed: Wed Aug 26 17:10:33 2015 -0700

----------------------------------------------------------------------
 .../internal/processors/cache/GridCacheProcessor.java       | 9 ++++++---
 1 file changed, 6 insertions(+), 3 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/1a83d65a/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 02411b1..270eef4 100644
--- 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
@@ -563,10 +563,13 @@ public class GridCacheProcessor extends GridProcessorAdapter {
 
         CacheConfiguration[] cfgs = ctx.config().getCacheConfiguration();
 
-        Collection<CacheStoreSessionListener> sesLsnrs = CU.create(ctx,
-            ctx.config().getCacheStoreSessionListenerFactories());
+        Collection<CacheStoreSessionListener> sesLsnrs = null;
 
-        CU.startStoreSessionListeners(ctx, sesLsnrs);
+        if (!ctx.config().isDaemon()) {
+            sesLsnrs = CU.create(ctx, ctx.config().getCacheStoreSessionListenerFactories());
+
+            CU.startStoreSessionListeners(ctx, sesLsnrs);
+        }
 
         sharedCtx = createSharedContext(ctx, sesLsnrs);
 


[31/59] [abbrv] ignite git commit: Moving platform classes to "...internal.processors..." package to follow Ignite common approach.

Posted by vk...@apache.org.
http://git-wip-us.apache.org/repos/asf/ignite/blob/2225f8d2/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformMemoryManagerImpl.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformMemoryManagerImpl.java b/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformMemoryManagerImpl.java
deleted file mode 100644
index 53a3e19..0000000
--- a/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformMemoryManagerImpl.java
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * 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.platform.memory;
-
-import org.apache.ignite.internal.platform.callback.*;
-import org.jetbrains.annotations.*;
-
-import static org.apache.ignite.internal.platform.memory.PlatformMemoryUtils.*;
-
-/**
- * Interop memory manager implementation.
- */
-public class PlatformMemoryManagerImpl implements PlatformMemoryManager {
-    /** Native gateway. */
-    private final PlatformCallbackGateway gate;
-
-    /** Default allocation capacity. */
-    private final int dfltCap;
-
-    /** Thread-local pool. */
-    private final ThreadLocal<PlatformMemoryPool> threadLocPool = new ThreadLocal<>();
-
-    /**
-     * Constructor.
-     *
-     * @param gate Native gateway.
-     * @param dfltCap Default memory chunk capacity.
-     */
-    public PlatformMemoryManagerImpl(@Nullable PlatformCallbackGateway gate, int dfltCap) {
-        this.gate = gate;
-        this.dfltCap = dfltCap;
-    }
-
-    /** {@inheritDoc} */
-    @Override public PlatformMemory allocate() {
-        return allocate(dfltCap);
-    }
-
-    /** {@inheritDoc} */
-    @Override public PlatformMemory allocate(int cap) {
-        return pool().allocate(cap);
-    }
-
-    /** {@inheritDoc} */
-    @Override public PlatformMemory get(long memPtr) {
-        int flags = flags(memPtr);
-
-        return isExternal(flags) ? new PlatformExternalMemory(gate, memPtr) :
-            isPooled(flags) ? pool().get(memPtr) : new PlatformUnpooledMemory(memPtr);
-    }
-
-    /**
-     * Gets or creates thread-local memory pool.
-     *
-     * @return Memory pool.
-     */
-    private PlatformMemoryPool pool() {
-        PlatformMemoryPool pool = threadLocPool.get();
-
-        if (pool == null) {
-            pool = new PlatformMemoryPool();
-
-            threadLocPool.set(pool);
-        }
-
-        return pool;
-    }
-}

http://git-wip-us.apache.org/repos/asf/ignite/blob/2225f8d2/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformMemoryPool.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformMemoryPool.java b/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformMemoryPool.java
deleted file mode 100644
index a012b5c..0000000
--- a/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformMemoryPool.java
+++ /dev/null
@@ -1,133 +0,0 @@
-/*
- * 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.platform.memory;
-
-import static org.apache.ignite.internal.platform.memory.PlatformMemoryUtils.*;
-
-/**
- * Memory pool associated with a thread.
- */
-public class PlatformMemoryPool {
-    /** base pointer. */
-    private final long poolPtr;
-
-    /** First pooled memory chunk. */
-    private PlatformPooledMemory mem1;
-
-    /** Second pooled memory chunk. */
-    private PlatformPooledMemory mem2;
-
-    /** Third pooled memory chunk. */
-    private PlatformPooledMemory mem3;
-
-    /**
-     * Constructor.
-     */
-    public PlatformMemoryPool() {
-        poolPtr = allocatePool();
-
-        sun.misc.Cleaner.create(this, new CleanerRunnable(poolPtr));
-    }
-
-    /**
-     * Allocate memory chunk, optionally pooling it.
-     *
-     * @param cap Minimum capacity.
-     * @return Memory chunk.
-     */
-    public PlatformMemory allocate(int cap) {
-        long memPtr = allocatePooled(poolPtr, cap);
-
-        // memPtr == 0 means that we failed to acquire thread-local memory chunk, so fallback to unpooled memory.
-        return memPtr != 0 ? get(memPtr) : new PlatformUnpooledMemory(allocateUnpooled(cap));
-    }
-
-    /**
-     * Re-allocate existing pool memory chunk.
-     *
-     * @param memPtr Memory pointer.
-     * @param cap Minimum capacity.
-     */
-    void reallocate(long memPtr, int cap) {
-        reallocatePooled(memPtr, cap);
-    }
-
-    /**
-     * Release pooled memory chunk.
-     *
-     * @param memPtr Memory pointer.
-     */
-    void release(long memPtr) {
-        releasePooled(memPtr);
-    }
-
-    /**
-     * Get pooled memory chunk.
-     *
-     * @param memPtr Memory pointer.
-     * @return Memory chunk.
-     */
-    public PlatformMemory get(long memPtr) {
-        long delta = memPtr - poolPtr;
-
-        if (delta == POOL_HDR_OFF_MEM_1) {
-            if (mem1 == null)
-                mem1 = new PlatformPooledMemory(this, memPtr);
-
-            return mem1;
-        }
-        else if (delta == POOL_HDR_OFF_MEM_2) {
-            if (mem2 == null)
-                mem2 = new PlatformPooledMemory(this, memPtr);
-
-            return mem2;
-        }
-        else {
-            assert delta == POOL_HDR_OFF_MEM_3;
-
-            if (mem3 == null)
-                mem3 = new PlatformPooledMemory(this, memPtr);
-
-            return mem3;
-        }
-    }
-
-    /**
-     * Cleaner runnable.
-     */
-    private static class CleanerRunnable implements Runnable {
-        /** Pointer. */
-        private final long poolPtr;
-
-        /**
-         * Constructor.
-         *
-         * @param poolPtr Pointer.
-         */
-        private CleanerRunnable(long poolPtr) {
-            assert poolPtr != 0;
-
-            this.poolPtr = poolPtr;
-        }
-
-        /** {@inheritDoc} */
-        @Override public void run() {
-            PlatformMemoryUtils.releasePool(poolPtr);
-        }
-    }
-}

http://git-wip-us.apache.org/repos/asf/ignite/blob/2225f8d2/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformMemoryUtils.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformMemoryUtils.java b/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformMemoryUtils.java
deleted file mode 100644
index d820ca6..0000000
--- a/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformMemoryUtils.java
+++ /dev/null
@@ -1,468 +0,0 @@
-/*
- * 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.platform.memory;
-
-import org.apache.ignite.internal.util.*;
-import sun.misc.*;
-
-import java.nio.*;
-
-/**
- * Utility classes for memory management.
- */
-public class PlatformMemoryUtils {
-    /** Unsafe instance. */
-    public static final Unsafe UNSAFE = GridUnsafe.unsafe();
-
-    /** Array offset: boolean. */
-    public static final long BOOLEAN_ARR_OFF = UNSAFE.arrayBaseOffset(boolean[].class);
-
-    /** Array offset: byte. */
-    public static final long BYTE_ARR_OFF = UNSAFE.arrayBaseOffset(byte[].class);
-
-    /** Array offset: short. */
-    public static final long SHORT_ARR_OFF = UNSAFE.arrayBaseOffset(short[].class);
-
-    /** Array offset: char. */
-    public static final long CHAR_ARR_OFF = UNSAFE.arrayBaseOffset(char[].class);
-
-    /** Array offset: int. */
-    public static final long INT_ARR_OFF = UNSAFE.arrayBaseOffset(int[].class);
-
-    /** Array offset: float. */
-    public static final long FLOAT_ARR_OFF = UNSAFE.arrayBaseOffset(float[].class);
-
-    /** Array offset: long. */
-    public static final long LONG_ARR_OFF = UNSAFE.arrayBaseOffset(long[].class);
-
-    /** Array offset: double. */
-    public static final long DOUBLE_ARR_OFF = UNSAFE.arrayBaseOffset(double[].class);
-
-    /** Whether little endian is used on the platform. */
-    public static final boolean LITTLE_ENDIAN = ByteOrder.nativeOrder() == ByteOrder.LITTLE_ENDIAN;
-
-    /** Header length. */
-    public static final int POOL_HDR_LEN = 64;
-
-    /** Pool header offset: first memory chunk. */
-    public static final int POOL_HDR_OFF_MEM_1 = 0;
-
-    /** Pool header offset: second memory chunk. */
-    public static final int POOL_HDR_OFF_MEM_2 = 20;
-
-    /** Pool header offset: third memory chunk. */
-    public static final int POOL_HDR_OFF_MEM_3 = 40;
-
-    /** Memory chunk header length. */
-    public static final int MEM_HDR_LEN = 20;
-
-    /** Offset: capacity. */
-    public static final int MEM_HDR_OFF_CAP = 8;
-
-    /** Offset: length. */
-    public static final int MEM_HDR_OFF_LEN = 12;
-
-    /** Offset: flags. */
-    public static final int MEM_HDR_OFF_FLAGS = 16;
-
-    /** Flag: external. */
-    public static final int FLAG_EXT = 0x1;
-
-    /** Flag: pooled. */
-    public static final int FLAG_POOLED = 0x2;
-
-    /** Flag: whether this pooled memory chunk is acquired. */
-    public static final int FLAG_ACQUIRED = 0x4;
-
-    /** --- COMMON METHODS. --- */
-
-    /**
-     * Gets data pointer for the given memory chunk.
-     *
-     * @param memPtr Memory pointer.
-     * @return Data pointer.
-     */
-    public static long data(long memPtr) {
-        return UNSAFE.getLong(memPtr);
-    }
-
-    /**
-     * Gets capacity for the given memory chunk.
-     *
-     * @param memPtr Memory pointer.
-     * @return Capacity.
-     */
-    public static int capacity(long memPtr) {
-        return UNSAFE.getInt(memPtr + MEM_HDR_OFF_CAP);
-    }
-
-    /**
-     * Sets capacity for the given memory chunk.
-     *
-     * @param memPtr Memory pointer.
-     * @param cap Capacity.
-     */
-    public static void capacity(long memPtr, int cap) {
-        assert !isExternal(memPtr) : "Attempt to update external memory chunk capacity: " + memPtr;
-
-        UNSAFE.putInt(memPtr + MEM_HDR_OFF_CAP, cap);
-    }
-
-    /**
-     * Gets length for the given memory chunk.
-     *
-     * @param memPtr Memory pointer.
-     * @return Length.
-     */
-    public static int length(long memPtr) {
-        return UNSAFE.getInt(memPtr + MEM_HDR_OFF_LEN);
-    }
-
-    /**
-     * Sets length for the given memory chunk.
-     *
-     * @param memPtr Memory pointer.
-     * @param len Length.
-     */
-    public static void length(long memPtr, int len) {
-        UNSAFE.putInt(memPtr + MEM_HDR_OFF_LEN, len);
-    }
-
-    /**
-     * Gets flags for the given memory chunk.
-     *
-     * @param memPtr Memory pointer.
-     * @return Flags.
-     */
-    public static int flags(long memPtr) {
-        return UNSAFE.getInt(memPtr + MEM_HDR_OFF_FLAGS);
-    }
-
-    /**
-     * Sets flags for the given memory chunk.
-     *
-     * @param memPtr Memory pointer.
-     * @param flags Flags.
-     */
-    public static void flags(long memPtr, int flags) {
-        assert !isExternal(memPtr) : "Attempt to update external memory chunk flags: " + memPtr;
-
-        UNSAFE.putInt(memPtr + MEM_HDR_OFF_FLAGS, flags);
-    }
-
-    /**
-     * Check whether this memory chunk is external.
-     *
-     * @param memPtr Memory pointer.
-     * @return {@code True} if owned by native platform.
-     */
-    public static boolean isExternal(long memPtr) {
-        return isExternal(flags(memPtr));
-    }
-
-    /**
-     * Check whether flags denote that this memory chunk is external.
-     *
-     * @param flags Flags.
-     * @return {@code True} if owned by native platform.
-     */
-    public static boolean isExternal(int flags) {
-        return (flags & FLAG_EXT) == FLAG_EXT;
-    }
-
-    /**
-     * Check whether this memory chunk is pooled.
-     *
-     * @param memPtr Memory pointer.
-     * @return {@code True} if pooled.
-     */
-    public static boolean isPooled(long memPtr) {
-        return isPooled(flags(memPtr));
-    }
-
-    /**
-     * Check whether flags denote pooled memory chunk.
-     *
-     * @param flags Flags.
-     * @return {@code True} if pooled.
-     */
-    public static boolean isPooled(int flags) {
-        return (flags & FLAG_POOLED) != 0;
-    }
-
-    /**
-     * Check whether this memory chunk is pooled and acquired.
-     *
-     * @param memPtr Memory pointer.
-     * @return {@code True} if pooled and acquired.
-     */
-    public static boolean isAcquired(long memPtr) {
-        return isAcquired(flags(memPtr));
-    }
-
-    /**
-     * Check whether flags denote pooled and acquired memory chunk.
-     *
-     * @param flags Flags.
-     * @return {@code True} if acquired.
-     */
-    public static boolean isAcquired(int flags) {
-        assert isPooled(flags);
-
-        return (flags & FLAG_ACQUIRED) != 0;
-    }
-
-    /** --- UNPOOLED MEMORY MANAGEMENT. --- */
-
-    /**
-     * Allocate unpooled memory chunk.
-     *
-     * @param cap Minimum capacity.
-     * @return New memory pointer.
-     */
-    public static long allocateUnpooled(int cap) {
-        assert cap > 0;
-
-        long memPtr = UNSAFE.allocateMemory(MEM_HDR_LEN);
-        long dataPtr = UNSAFE.allocateMemory(cap);
-
-        UNSAFE.putLong(memPtr, dataPtr);              // Write address.
-        UNSAFE.putInt(memPtr + MEM_HDR_OFF_CAP, cap); // Write capacity.
-        UNSAFE.putInt(memPtr + MEM_HDR_OFF_LEN, 0);   // Write length.
-        UNSAFE.putInt(memPtr + MEM_HDR_OFF_FLAGS, 0); // Write flags.
-
-        return memPtr;
-    }
-
-    /**
-     * Reallocate unpooled memory chunk.
-     *
-     * @param memPtr Memory pointer.
-     * @param cap Minimum capacity.
-     */
-    public static void reallocateUnpooled(long memPtr, int cap) {
-        assert cap > 0;
-
-        assert !isExternal(memPtr) : "Attempt to reallocate external memory chunk directly: " + memPtr;
-        assert !isPooled(memPtr) : "Attempt to reallocate pooled memory chunk directly: " + memPtr;
-
-        long dataPtr = data(memPtr);
-
-        long newDataPtr = UNSAFE.reallocateMemory(dataPtr, cap);
-
-        if (dataPtr != newDataPtr)
-            UNSAFE.putLong(memPtr, newDataPtr); // Write new data address if needed.
-
-        UNSAFE.putInt(memPtr + MEM_HDR_OFF_CAP, cap); // Write new capacity.
-    }
-
-    /**
-     * Release unpooled memory chunk.
-     *
-     * @param memPtr Memory pointer.
-     */
-    public static void releaseUnpooled(long memPtr) {
-        assert !isExternal(memPtr) : "Attempt to release external memory chunk directly: " + memPtr;
-        assert !isPooled(memPtr) : "Attempt to release pooled memory chunk directly: " + memPtr;
-
-        UNSAFE.freeMemory(data(memPtr));
-        UNSAFE.freeMemory(memPtr);
-    }
-
-    /** --- POOLED MEMORY MANAGEMENT. --- */
-
-    /**
-     * Allocate pool memory.
-     *
-     * @return Pool pointer.
-     */
-    public static long allocatePool() {
-        long poolPtr = UNSAFE.allocateMemory(POOL_HDR_LEN);
-
-        UNSAFE.setMemory(poolPtr, POOL_HDR_LEN, (byte)0);
-
-        flags(poolPtr + POOL_HDR_OFF_MEM_1, FLAG_POOLED);
-        flags(poolPtr + POOL_HDR_OFF_MEM_2, FLAG_POOLED);
-        flags(poolPtr + POOL_HDR_OFF_MEM_3, FLAG_POOLED);
-
-        return poolPtr;
-    }
-
-    /**
-     * Release pool memory.
-     *
-     * @param poolPtr Pool pointer.
-     */
-    public static void releasePool(long poolPtr) {
-        // Clean predefined memory chunks.
-        long mem = UNSAFE.getLong(poolPtr + POOL_HDR_OFF_MEM_1);
-
-        if (mem != 0)
-            UNSAFE.freeMemory(mem);
-
-        mem = UNSAFE.getLong(poolPtr + POOL_HDR_OFF_MEM_2);
-
-        if (mem != 0)
-            UNSAFE.freeMemory(mem);
-
-        mem = UNSAFE.getLong(poolPtr + POOL_HDR_OFF_MEM_3);
-
-        if (mem != 0)
-            UNSAFE.freeMemory(mem);
-
-        // Clean pool chunk.
-        UNSAFE.freeMemory(poolPtr);
-    }
-
-    /**
-     * Allocate pooled memory chunk.
-     *
-     * @param poolPtr Pool pointer.
-     * @param cap Capacity.
-     * @return Cross-platform memory pointer or {@code 0} in case there are no free memory chunks in the pool.
-     */
-    public static long allocatePooled(long poolPtr, int cap) {
-        long memPtr1 = poolPtr + POOL_HDR_OFF_MEM_1;
-
-        if (isAcquired(memPtr1)) {
-            long memPtr2 = poolPtr + POOL_HDR_OFF_MEM_2;
-
-            if (isAcquired(memPtr2)) {
-                long memPtr3 = poolPtr + POOL_HDR_OFF_MEM_3;
-
-                if (isAcquired(memPtr3))
-                    return 0L;
-                else {
-                    allocatePooled0(memPtr3, cap);
-
-                    return memPtr3;
-                }
-            }
-            else {
-                allocatePooled0(memPtr2, cap);
-
-                return memPtr2;
-            }
-        }
-        else {
-            allocatePooled0(memPtr1, cap);
-
-            return memPtr1;
-        }
-    }
-
-    /**
-     * Internal pooled memory chunk allocation routine.
-     *
-     * @param memPtr Memory pointer.
-     * @param cap Capacity.
-     */
-    private static void allocatePooled0(long memPtr, int cap) {
-        assert !isExternal(memPtr);
-        assert isPooled(memPtr);
-        assert !isAcquired(memPtr);
-
-        long data = UNSAFE.getLong(memPtr);
-
-        if (data == 0) {
-            // First allocation of the chunk.
-            data = UNSAFE.allocateMemory(cap);
-
-            UNSAFE.putLong(memPtr, data);
-            UNSAFE.putInt(memPtr + MEM_HDR_OFF_CAP, cap);
-        }
-        else {
-            // Ensure that we have enough capacity.
-            int curCap = capacity(memPtr);
-
-            if (cap > curCap) {
-                data = UNSAFE.reallocateMemory(data, cap);
-
-                UNSAFE.putLong(memPtr, data);
-                UNSAFE.putInt(memPtr + MEM_HDR_OFF_CAP, cap);
-            }
-        }
-
-        flags(memPtr, FLAG_POOLED | FLAG_ACQUIRED);
-    }
-
-    /**
-     * Reallocate pooled memory chunk.
-     *
-     * @param memPtr Memory pointer.
-     * @param cap Minimum capacity.
-     */
-    public static void reallocatePooled(long memPtr, int cap) {
-        assert !isExternal(memPtr);
-        assert isPooled(memPtr);
-        assert isAcquired(memPtr);
-
-        long data = UNSAFE.getLong(memPtr);
-
-        assert data != 0;
-
-        int curCap = capacity(memPtr);
-
-        if (cap > curCap) {
-            data = UNSAFE.reallocateMemory(data, cap);
-
-            UNSAFE.putLong(memPtr, data);
-            UNSAFE.putInt(memPtr + MEM_HDR_OFF_CAP, cap);
-        }
-    }
-
-    /**
-     * Release pooled memory chunk.
-     *
-     * @param memPtr Memory pointer.
-     */
-    public static void releasePooled(long memPtr) {
-        assert !isExternal(memPtr);
-        assert isPooled(memPtr);
-        assert isAcquired(memPtr);
-
-        flags(memPtr, flags(memPtr) ^ FLAG_ACQUIRED);
-    }
-
-    /** --- UTILITY STUFF. --- */
-
-    /**
-     * Reallocate arbitrary memory chunk.
-     *
-     * @param memPtr Memory pointer.
-     * @param cap Capacity.
-     */
-    public static void reallocate(long memPtr, int cap) {
-        int flags = flags(memPtr);
-
-        if (isPooled(flags))
-            reallocatePooled(memPtr, cap);
-        else {
-            assert !isExternal(flags);
-
-            reallocateUnpooled(memPtr, cap);
-        }
-    }
-
-    /**
-     * Constructor.
-     */
-    private PlatformMemoryUtils() {
-        // No-op.
-    }
-}

http://git-wip-us.apache.org/repos/asf/ignite/blob/2225f8d2/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformOutputStream.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformOutputStream.java b/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformOutputStream.java
deleted file mode 100644
index 89527ce..0000000
--- a/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformOutputStream.java
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * 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.platform.memory;
-
-import org.apache.ignite.internal.portable.streams.*;
-
-/**
- * Interop output stream.
- */
-public interface PlatformOutputStream extends PortableOutputStream {
-    /**
-     * Synchronize output stream with underlying memory
-     */
-    public void synchronize();
-}

http://git-wip-us.apache.org/repos/asf/ignite/blob/2225f8d2/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformOutputStreamImpl.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformOutputStreamImpl.java b/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformOutputStreamImpl.java
deleted file mode 100644
index 13492eb..0000000
--- a/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformOutputStreamImpl.java
+++ /dev/null
@@ -1,259 +0,0 @@
-/*
- * 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.platform.memory;
-
-import static org.apache.ignite.internal.platform.memory.PlatformMemoryUtils.*;
-
-/**
- * Interop output stream implementation.
- */
-public class PlatformOutputStreamImpl implements PlatformOutputStream {
-    /** Underlying memory chunk. */
-    protected final PlatformMemory mem;
-
-    /** Pointer. */
-    protected long data;
-
-    /** Maximum capacity. */
-    protected int cap;
-
-    /** Current position. */
-    protected int pos;
-
-    /**
-     * Constructor.
-     *
-     * @param mem Underlying memory chunk.
-     */
-    public PlatformOutputStreamImpl(PlatformMemory mem) {
-        this.mem = mem;
-
-        data = mem.data();
-        cap = mem.capacity();
-    }
-
-    /** {@inheritDoc} */
-    @Override public void writeByte(byte val) {
-        ensureCapacity(pos + 1);
-
-        UNSAFE.putByte(data + pos++, val);
-    }
-
-    /** {@inheritDoc} */
-    @Override public void writeByteArray(byte[] val) {
-        copyAndShift(val, BYTE_ARR_OFF, val.length);
-    }
-
-    /** {@inheritDoc} */
-    @Override public void writeBoolean(boolean val) {
-        writeByte(val ? (byte) 1 : (byte) 0);
-    }
-
-    /** {@inheritDoc} */
-    @Override public void writeBooleanArray(boolean[] val) {
-        copyAndShift(val, BOOLEAN_ARR_OFF, val.length);
-    }
-
-    /** {@inheritDoc} */
-    @Override public void writeShort(short val) {
-        ensureCapacity(pos + 2);
-
-        UNSAFE.putShort(data + pos, val);
-
-        shift(2);
-    }
-
-    /** {@inheritDoc} */
-    @Override public void writeShortArray(short[] val) {
-        copyAndShift(val, SHORT_ARR_OFF, val.length << 1);
-    }
-
-    /** {@inheritDoc} */
-    @Override public void writeChar(char val) {
-        ensureCapacity(pos + 2);
-
-        UNSAFE.putChar(data + pos, val);
-
-        shift(2);
-    }
-
-    /** {@inheritDoc} */
-    @Override public void writeCharArray(char[] val) {
-        copyAndShift(val, CHAR_ARR_OFF, val.length << 1);
-    }
-
-    /** {@inheritDoc} */
-    @Override public void writeInt(int val) {
-        ensureCapacity(pos + 4);
-
-        UNSAFE.putInt(data + pos, val);
-
-        shift(4);
-    }
-
-    /** {@inheritDoc} */
-    @Override public void writeIntArray(int[] val) {
-        copyAndShift(val, INT_ARR_OFF, val.length << 2);
-    }
-
-    /** {@inheritDoc} */
-    @Override public void writeInt(int pos, int val) {
-        ensureCapacity(pos + 4);
-
-        UNSAFE.putInt(data + pos, val);
-    }
-
-    /** {@inheritDoc} */
-    @Override public void writeFloat(float val) {
-        writeInt(Float.floatToIntBits(val));
-    }
-
-    /** {@inheritDoc} */
-    @Override public void writeFloatArray(float[] val) {
-        copyAndShift(val, FLOAT_ARR_OFF, val.length << 2);
-    }
-
-    /** {@inheritDoc} */
-    @Override public void writeLong(long val) {
-        ensureCapacity(pos + 8);
-
-        UNSAFE.putLong(data + pos, val);
-
-        shift(8);
-    }
-
-    /** {@inheritDoc} */
-    @Override public void writeLongArray(long[] val) {
-        copyAndShift(val, LONG_ARR_OFF, val.length << 3);
-    }
-
-    /** {@inheritDoc} */
-    @Override public void writeDouble(double val) {
-        writeLong(Double.doubleToLongBits(val));
-    }
-
-    /** {@inheritDoc} */
-    @Override public void writeDoubleArray(double[] val) {
-        copyAndShift(val, DOUBLE_ARR_OFF, val.length << 3);
-    }
-
-    /** {@inheritDoc} */
-    @Override public void write(byte[] arr, int off, int len) {
-        copyAndShift(arr, BYTE_ARR_OFF + off, len);
-    }
-
-    /** {@inheritDoc} */
-    @Override public void write(long addr, int cnt) {
-        copyAndShift(null, addr, cnt);
-    }
-
-    /** {@inheritDoc} */
-    @Override public int position() {
-        return pos;
-    }
-
-    /** {@inheritDoc} */
-    @Override public void position(int pos) {
-        ensureCapacity(pos);
-
-        this.pos = pos;
-    }
-
-    /** {@inheritDoc} */
-    @Override public void close() {
-        // No-op.
-    }
-
-    /** {@inheritDoc} */
-    @Override public byte[] array() {
-        assert false;
-
-        throw new UnsupportedOperationException("Should not be called.");
-    }
-
-    /** {@inheritDoc} */
-    @Override public byte[] arrayCopy() {
-        assert false;
-
-        throw new UnsupportedOperationException("Should not be called.");
-    }
-
-    /** {@inheritDoc} */
-    @Override public long offheapPointer() {
-        assert false;
-
-        throw new UnsupportedOperationException("Should not be called.");
-    }
-
-    /** {@inheritDoc} */
-    @Override public boolean hasArray() {
-        assert false;
-
-        throw new UnsupportedOperationException("Should not be called.");
-    }
-
-    /** {@inheritDoc} */
-    @Override public void synchronize() {
-        PlatformMemoryUtils.length(mem.pointer(), pos);
-    }
-
-    /**
-     * Ensure capacity.
-     *
-     * @param reqCap Required byte count.
-     */
-    protected void ensureCapacity(int reqCap) {
-        if (reqCap > cap) {
-            int newCap = cap << 1;
-
-            if (newCap < reqCap)
-                newCap = reqCap;
-
-            mem.reallocate(newCap);
-
-            assert mem.capacity() >= newCap;
-
-            data = mem.data();
-            cap = newCap;
-        }
-    }
-
-    /**
-     * Shift position.
-     *
-     * @param cnt Byte count.
-     */
-    protected void shift(int cnt) {
-        pos += cnt;
-    }
-
-    /**
-     * Copy source object to the stream shifting position afterwards.
-     *
-     * @param src Source.
-     * @param off Offset.
-     * @param len Length.
-     */
-    private void copyAndShift(Object src, long off, int len) {
-        ensureCapacity(pos + len);
-
-        UNSAFE.copyMemory(src, off, null, data + pos, len);
-
-        shift(len);
-    }
-}

http://git-wip-us.apache.org/repos/asf/ignite/blob/2225f8d2/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformPooledMemory.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformPooledMemory.java b/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformPooledMemory.java
deleted file mode 100644
index 5043fd1..0000000
--- a/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformPooledMemory.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * 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.platform.memory;
-
-import static org.apache.ignite.internal.platform.memory.PlatformMemoryUtils.*;
-
-/**
- * Interop pooled memory chunk.
- */
-public class PlatformPooledMemory extends PlatformAbstractMemory {
-    /** Owning memory pool. */
-    private final PlatformMemoryPool pool;
-
-    /**
-     * Constructor.
-     *
-     * @param pool Owning memory pool.
-     * @param memPtr Cross-platform memory pointer.
-     */
-    public PlatformPooledMemory(PlatformMemoryPool pool, long memPtr) {
-        super(memPtr);
-
-        assert isPooled(memPtr);
-        assert isAcquired(memPtr);
-
-        this.pool = pool;
-    }
-
-    /** {@inheritDoc} */
-    @Override public void reallocate(int cap) {
-        assert isAcquired(memPtr);
-
-        // Try doubling capacity to avoid excessive allocations.
-        int doubledCap = PlatformMemoryUtils.capacity(memPtr) << 1;
-
-        if (doubledCap > cap)
-            cap = doubledCap;
-
-        pool.reallocate(memPtr, cap);
-    }
-
-    /** {@inheritDoc} */
-    @Override public void close() {
-        assert isAcquired(memPtr);
-
-        pool.release(memPtr); // Return to the pool.
-    }
-}

http://git-wip-us.apache.org/repos/asf/ignite/blob/2225f8d2/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformUnpooledMemory.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformUnpooledMemory.java b/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformUnpooledMemory.java
deleted file mode 100644
index f3fe227..0000000
--- a/modules/platform/src/main/java/org/apache/ignite/internal/platform/memory/PlatformUnpooledMemory.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * 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.platform.memory;
-
-import static org.apache.ignite.internal.platform.memory.PlatformMemoryUtils.*;
-
-/**
- * Interop un-pooled memory chunk.
- */
-public class PlatformUnpooledMemory extends PlatformAbstractMemory {
-    /**
-     * Constructor.
-     *
-     * @param memPtr Cross-platform memory pointer.
-     */
-    public PlatformUnpooledMemory(long memPtr) {
-        super(memPtr);
-    }
-
-    /** {@inheritDoc} */
-    @Override public void reallocate(int cap) {
-        // Try doubling capacity to avoid excessive allocations.
-        int doubledCap = PlatformMemoryUtils.capacity(memPtr) << 1;
-
-        if (doubledCap > cap)
-            cap = doubledCap;
-
-        reallocateUnpooled(memPtr, cap);
-    }
-
-    /** {@inheritDoc} */
-    @Override public void close() {
-        releaseUnpooled(memPtr);
-    }
-}
-

http://git-wip-us.apache.org/repos/asf/ignite/blob/2225f8d2/modules/platform/src/main/java/org/apache/ignite/internal/platform/utils/PlatformReaderBiClosure.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/platform/utils/PlatformReaderBiClosure.java b/modules/platform/src/main/java/org/apache/ignite/internal/platform/utils/PlatformReaderBiClosure.java
deleted file mode 100644
index 0280ba8..0000000
--- a/modules/platform/src/main/java/org/apache/ignite/internal/platform/utils/PlatformReaderBiClosure.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * 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.platform.utils;
-
-import org.apache.ignite.internal.portable.*;
-import org.apache.ignite.lang.*;
-
-/**
- * Reader bi-closure.
- */
-public interface PlatformReaderBiClosure<T1, T2> {
-    /**
-     * Read object from reader.
-     *
-     * @param reader Reader.
-     * @return Object.
-     */
-    IgniteBiTuple<T1, T2> read(PortableRawReaderEx reader);
-}

http://git-wip-us.apache.org/repos/asf/ignite/blob/2225f8d2/modules/platform/src/main/java/org/apache/ignite/internal/platform/utils/PlatformReaderClosure.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/platform/utils/PlatformReaderClosure.java b/modules/platform/src/main/java/org/apache/ignite/internal/platform/utils/PlatformReaderClosure.java
deleted file mode 100644
index 73a24d1..0000000
--- a/modules/platform/src/main/java/org/apache/ignite/internal/platform/utils/PlatformReaderClosure.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * 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.platform.utils;
-
-import org.apache.ignite.internal.portable.*;
-
-/**
- * Reader closure.
- */
-public interface PlatformReaderClosure<T> {
-
-    /**
-     * Read object from reader.
-     *
-     * @param reader Reader.
-     * @return Object.
-     */
-    T read(PortableRawReaderEx reader);
-}

http://git-wip-us.apache.org/repos/asf/ignite/blob/2225f8d2/modules/platform/src/main/java/org/apache/ignite/internal/platform/utils/PlatformWriterBiClosure.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/platform/utils/PlatformWriterBiClosure.java b/modules/platform/src/main/java/org/apache/ignite/internal/platform/utils/PlatformWriterBiClosure.java
deleted file mode 100644
index cbd34fa..0000000
--- a/modules/platform/src/main/java/org/apache/ignite/internal/platform/utils/PlatformWriterBiClosure.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * 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.platform.utils;
-
-import org.apache.ignite.internal.portable.*;
-
-/**
- * Interop writer bi-closure.
- */
-public interface PlatformWriterBiClosure<T1, T2> {
-    /**
-     * Write values.
-     *
-     * @param writer Writer.
-     * @param val1 Value 1.
-     * @param val2 Value 2.
-     */
-    public void write(PortableRawWriterEx writer, T1 val1, T2 val2);
-}

http://git-wip-us.apache.org/repos/asf/ignite/blob/2225f8d2/modules/platform/src/main/java/org/apache/ignite/internal/platform/utils/PlatformWriterClosure.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/platform/utils/PlatformWriterClosure.java b/modules/platform/src/main/java/org/apache/ignite/internal/platform/utils/PlatformWriterClosure.java
deleted file mode 100644
index d9953ca..0000000
--- a/modules/platform/src/main/java/org/apache/ignite/internal/platform/utils/PlatformWriterClosure.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * 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.platform.utils;
-
-import org.apache.ignite.internal.portable.*;
-
-/**
- * Interop writer closure.
- */
-public interface PlatformWriterClosure<T> {
-    /**
-     * Write value.
-     *
-     * @param writer Writer.
-     * @param val Value.
-     */
-    public void write(PortableRawWriterEx writer, T val);
-}

http://git-wip-us.apache.org/repos/asf/ignite/blob/2225f8d2/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/PlatformBootstrap.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/PlatformBootstrap.java b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/PlatformBootstrap.java
new file mode 100644
index 0000000..319c670
--- /dev/null
+++ b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/PlatformBootstrap.java
@@ -0,0 +1,36 @@
+/*
+ * 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.platform;
+
+import org.apache.ignite.configuration.*;
+import org.apache.ignite.internal.processors.platform.*;
+
+/**
+ * Platform bootstrap. Responsible for starting Ignite node with non-Java platform.
+ */
+public interface PlatformBootstrap {
+    /**
+     * Start Ignite node.
+     *
+     * @param cfg Configuration.
+     * @param envPtr Environment pointer.
+     * @param dataPtr Optional pointer to additional data required for startup.
+     * @return Platform processor.
+     */
+    public PlatformProcessor start(IgniteConfiguration cfg, long envPtr, long dataPtr);
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/2225f8d2/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/PlatformBootstrapFactory.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/PlatformBootstrapFactory.java b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/PlatformBootstrapFactory.java
new file mode 100644
index 0000000..f5b3adf
--- /dev/null
+++ b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/PlatformBootstrapFactory.java
@@ -0,0 +1,37 @@
+/*
+ * 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.platform;
+
+/**
+ * Platform bootstrap factory.
+ */
+public interface PlatformBootstrapFactory {
+    /**
+     * Get bootstrap factory ID.
+     *
+     * @return ID.
+     */
+    public int id();
+
+    /**
+     * Create bootstrap instance.
+     *
+     * @return Bootstrap instance.
+     */
+    public PlatformBootstrap create();
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/2225f8d2/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/PlatformException.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/PlatformException.java b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/PlatformException.java
new file mode 100644
index 0000000..479d533
--- /dev/null
+++ b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/PlatformException.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.internal.processors.platform;
+
+import org.apache.ignite.*;
+import org.apache.ignite.internal.util.typedef.internal.*;
+import org.jetbrains.annotations.*;
+
+/**
+ * Interop checked exception.
+ */
+public class PlatformException extends IgniteCheckedException {
+    /** */
+    private static final long serialVersionUID = 0L;
+
+    /**
+     * Create empty exception.
+     */
+    public PlatformException() {
+        // No-op.
+    }
+
+    /**
+     * Creates new exception with given error message.
+     *
+     * @param msg Error message.
+     */
+    public PlatformException(String msg) {
+        super(msg);
+    }
+
+    /**
+     * Creates new grid exception with given throwable as a cause and
+     * source of error message.
+     *
+     * @param cause Non-null throwable cause.
+     */
+    public PlatformException(Throwable cause) {
+        this(cause.getMessage(), cause);
+    }
+
+    /**
+     * Creates new exception with given error message and optional nested exception.
+     *
+     * @param msg Error message.
+     * @param cause Optional nested exception (can be {@code null}).
+     */
+    public PlatformException(String msg, @Nullable Throwable cause) {
+        super(msg, cause);
+    }
+
+    /** {@inheritDoc} */
+    @Override public String toString() {
+        return S.toString(PlatformException.class, this);
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/2225f8d2/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/PlatformIgnition.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/PlatformIgnition.java b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/PlatformIgnition.java
new file mode 100644
index 0000000..93cf8b4
--- /dev/null
+++ b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/PlatformIgnition.java
@@ -0,0 +1,186 @@
+/*
+ * 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.platform;
+
+import org.apache.ignite.*;
+import org.apache.ignite.configuration.*;
+import org.apache.ignite.internal.*;
+import org.apache.ignite.internal.processors.resource.*;
+import org.apache.ignite.internal.util.typedef.internal.*;
+import org.apache.ignite.lang.*;
+import org.jetbrains.annotations.*;
+
+import java.net.*;
+import java.security.*;
+import java.util.*;
+
+/**
+ * Entry point for platform nodes.
+ */
+@SuppressWarnings("UnusedDeclaration")
+public class PlatformIgnition {
+    /** Map with active instances. */
+    private static final HashMap<String, PlatformProcessor> instances = new HashMap<>();
+
+    /**
+     * Start Ignite node in platform mode.
+     *
+     * @param springCfgPath Spring configuration path.
+     * @param gridName Grid name.
+     * @param factoryId Factory ID.
+     * @param envPtr Environment pointer.
+     * @param dataPtr Optional pointer to additional data required for startup.
+     * @return Ignite instance.
+     */
+    public static synchronized PlatformProcessor start(@Nullable String springCfgPath, @Nullable String gridName,
+        int factoryId, long envPtr, long dataPtr) {
+        if (envPtr <= 0)
+            throw new IgniteException("Environment pointer must be positive.");
+
+        ClassLoader oldClsLdr = Thread.currentThread().getContextClassLoader();
+
+        Thread.currentThread().setContextClassLoader(PlatformProcessor.class.getClassLoader());
+
+        try {
+            IgniteConfiguration cfg = configuration(springCfgPath);
+
+            if (gridName != null)
+                cfg.setGridName(gridName);
+            else
+                gridName = cfg.getGridName();
+
+            PlatformBootstrap bootstrap = bootstrap(factoryId);
+
+            PlatformProcessor proc = bootstrap.start(cfg, envPtr, dataPtr);
+
+            PlatformProcessor old = instances.put(gridName, proc);
+
+            assert old == null;
+
+            return proc;
+        }
+        finally {
+            Thread.currentThread().setContextClassLoader(oldClsLdr);
+        }
+    }
+
+    /**
+     * Get instance by environment pointer.
+     *
+     * @param gridName Grid name.
+     * @return Instance or {@code null} if it doesn't exist (never started or stopped).
+     */
+    @Nullable public static synchronized PlatformProcessor instance(@Nullable String gridName) {
+        return instances.get(gridName);
+    }
+
+    /**
+     * Get environment pointer of the given instance.
+     *
+     * @param gridName Grid name.
+     * @return Environment pointer or {@code 0} in case grid with such name doesn't exist.
+     */
+    public static synchronized long environmentPointer(@Nullable String gridName) {
+        PlatformProcessor proc = instance(gridName);
+
+        return proc != null ? proc.environmentPointer() : 0;
+    }
+
+    /**
+     * Stop single instance.
+     *
+     * @param gridName Grid name,
+     * @param cancel Cancel flag.
+     * @return {@code True} if instance was found and stopped.
+     */
+    public static synchronized boolean stop(@Nullable String gridName, boolean cancel) {
+        if (Ignition.stop(gridName, cancel)) {
+            PlatformProcessor old = instances.remove(gridName);
+
+            assert old != null;
+
+            return true;
+        }
+        else
+            return false;
+    }
+
+    /**
+     * Stop all instances.
+     *
+     * @param cancel Cancel flag.
+     */
+    public static synchronized void stopAll(boolean cancel) {
+        for (PlatformProcessor proc : instances.values())
+            Ignition.stop(proc.ignite().name(), cancel);
+
+        instances.clear();
+    }
+
+    /**
+     * Create configuration.
+     *
+     * @param springCfgPath Path to Spring XML.
+     * @return Configuration.
+     */
+    private static IgniteConfiguration configuration(@Nullable String springCfgPath) {
+        try {
+            URL url = springCfgPath == null ? U.resolveIgniteUrl(IgnitionEx.DFLT_CFG) :
+                U.resolveSpringUrl(springCfgPath);
+
+            IgniteBiTuple<IgniteConfiguration, GridSpringResourceContext> t = IgnitionEx.loadConfiguration(url);
+
+            return t.get1();
+        }
+        catch (IgniteCheckedException e) {
+            throw new IgniteException("Failed to instantiate configuration from Spring XML: " + springCfgPath, e);
+        }
+    }
+
+    /**
+     * Create bootstrap for the given factory ID.
+     *
+     * @param factoryId Factory ID.
+     * @return Bootstrap.
+     */
+    private static PlatformBootstrap bootstrap(final int factoryId) {
+        PlatformBootstrapFactory factory = AccessController.doPrivileged(
+            new PrivilegedAction<PlatformBootstrapFactory>() {
+                @Override public PlatformBootstrapFactory run() {
+                    for (PlatformBootstrapFactory factory : ServiceLoader.load(PlatformBootstrapFactory.class)) {
+                        if (factory.id() == factoryId)
+                            return factory;
+                    }
+
+                    return null;
+                }
+            });
+
+        if (factory == null)
+            throw new IgniteException("Interop factory is not found (did you put into the classpath?): " + factoryId);
+
+        return factory.create();
+    }
+
+    /**
+     * Private constructor.
+     */
+    private PlatformIgnition() {
+        // No-op.
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/2225f8d2/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/PlatformNoCallbackException.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/PlatformNoCallbackException.java b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/PlatformNoCallbackException.java
new file mode 100644
index 0000000..ad61719
--- /dev/null
+++ b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/PlatformNoCallbackException.java
@@ -0,0 +1,50 @@
+/*
+ * 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.platform;
+
+import org.apache.ignite.internal.util.typedef.internal.*;
+
+/**
+ * Exception raised when interop callback is not set in native platform.
+ */
+@SuppressWarnings("UnusedDeclaration")
+public class PlatformNoCallbackException extends PlatformException {
+    /** */
+    private static final long serialVersionUID = 0L;
+
+    /**
+     * Constructor.
+     */
+    public PlatformNoCallbackException() {
+        // No-op.
+    }
+
+    /**
+     * Constructor.
+     *
+     * @param msg Message.
+     */
+    public PlatformNoCallbackException(String msg) {
+        super(msg);
+    }
+
+    /** {@inheritDoc} */
+    @Override public String toString() {
+        return S.toString(PlatformNoCallbackException.class, this);
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/2225f8d2/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/callback/PlatformCallbackGateway.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/callback/PlatformCallbackGateway.java b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/callback/PlatformCallbackGateway.java
new file mode 100644
index 0000000..a8e7879
--- /dev/null
+++ b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/callback/PlatformCallbackGateway.java
@@ -0,0 +1,869 @@
+/*
+ * 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.platform.callback;
+
+import org.apache.ignite.*;
+import org.apache.ignite.internal.util.*;
+
+/**
+ * Gateway to all platform-dependent callbacks. Implementers might extend this class and provide additional callbacks.
+ */
+@SuppressWarnings({"FieldCanBeLocal", "UnusedDeclaration"})
+public class PlatformCallbackGateway {
+    /** Environment pointer. */
+    protected final long envPtr;
+
+    /** Lock. */
+    private final GridSpinReadWriteLock lock = new GridSpinReadWriteLock();
+
+    /**
+     * Native gateway.
+     *
+     * @param envPtr Environment pointer.
+     */
+    public PlatformCallbackGateway(long envPtr) {
+        this.envPtr = envPtr;
+    }
+
+    /**
+     * Get environment pointer.
+     *
+     * @return Environment pointer.
+     */
+    public long environmentPointer() {
+        return envPtr;
+    }
+
+    /**
+     * Create cache store.
+     *
+     * @param memPtr Memory pointer.
+     * @return Pointer.
+     */
+    public long cacheStoreCreate(long memPtr) {
+        enter();
+
+        try {
+            return PlatformCallbackUtils.cacheStoreCreate(envPtr, memPtr);
+        }
+        finally {
+            leave();
+        }
+    }
+
+    /**
+     * @param objPtr Object pointer.
+     * @param memPtr Memory pointer.
+     * @param cb Callback.
+     * @return Result.
+     */
+    public int cacheStoreInvoke(long objPtr, long memPtr, Object cb) {
+        enter();
+
+        try {
+            return PlatformCallbackUtils.cacheStoreInvoke(envPtr, objPtr, memPtr, cb);
+        }
+        finally {
+            leave();
+        }
+    }
+
+    /**
+     * @param objPtr Object pointer.
+     */
+    public void cacheStoreDestroy(long objPtr) {
+        enter();
+
+        try {
+            PlatformCallbackUtils.cacheStoreDestroy(envPtr, objPtr);
+        }
+        finally {
+            leave();
+        }
+    }
+
+    /**
+     * Creates cache store session.
+     *
+     * @param storePtr Store instance pointer.
+     * @return Session instance pointer.
+     */
+    public long cacheStoreSessionCreate(long storePtr) {
+        enter();
+
+        try {
+            return PlatformCallbackUtils.cacheStoreSessionCreate(envPtr, storePtr);
+        }
+        finally {
+            leave();
+        }
+    }
+
+    /**
+     * Creates cache entry filter and returns a pointer.
+     *
+     * @param memPtr Memory pointer.
+     * @return Pointer.
+     */
+    public long cacheEntryFilterCreate(long memPtr) {
+        enter();
+
+        try {
+            return PlatformCallbackUtils.cacheEntryFilterCreate(envPtr, memPtr);
+        }
+        finally {
+            leave();
+        }
+    }
+
+    /**
+     * @param ptr Pointer.
+     * @param memPtr Memory pointer.
+     * @return Result.
+     */
+    public int cacheEntryFilterApply(long ptr, long memPtr) {
+        enter();
+
+        try {
+            return PlatformCallbackUtils.cacheEntryFilterApply(envPtr, ptr, memPtr);
+        }
+        finally {
+            leave();
+        }
+    }
+
+    /**
+     * @param ptr Pointer.
+     */
+    public void cacheEntryFilterDestroy(long ptr) {
+        enter();
+
+        try {
+            PlatformCallbackUtils.cacheEntryFilterDestroy(envPtr, ptr);
+        }
+        finally {
+            leave();
+        }
+    }
+
+    /**
+     * Invoke cache entry processor.
+     *
+     * @param outMemPtr Output memory pointer.
+     * @param inMemPtr Input memory pointer.
+     */
+    public void cacheInvoke(long outMemPtr, long inMemPtr) {
+        enter();
+
+        try {
+            PlatformCallbackUtils.cacheInvoke(envPtr, outMemPtr, inMemPtr);
+        }
+        finally {
+            leave();
+        }
+    }
+
+    /**
+     * Perform native task map. Do not throw exceptions, serializing them to the output stream instead.
+     *
+     * @param taskPtr Task pointer.
+     * @param outMemPtr Output memory pointer (exists if topology changed, otherwise {@code 0}).
+     * @param inMemPtr Input memory pointer.
+     */
+    public void computeTaskMap(long taskPtr, long outMemPtr, long inMemPtr) {
+        enter();
+
+        try {
+            PlatformCallbackUtils.computeTaskMap(envPtr, taskPtr, outMemPtr, inMemPtr);
+        }
+        finally {
+            leave();
+        }
+    }
+
+    /**
+     * Perform native task job result notification.
+     *
+     * @param taskPtr Task pointer.
+     * @param jobPtr Job pointer.
+     * @param memPtr Memory pointer (always zero for local job execution).
+     * @return Job result enum ordinal.
+     */
+    public int computeTaskJobResult(long taskPtr, long jobPtr, long memPtr) {
+        enter();
+
+        try {
+            return PlatformCallbackUtils.computeTaskJobResult(envPtr, taskPtr, jobPtr, memPtr);
+        }
+        finally {
+            leave();
+        }
+    }
+
+    /**
+     * Perform native task reduce.
+     *
+     * @param taskPtr Task pointer.
+     */
+    public void computeTaskReduce(long taskPtr) {
+        enter();
+
+        try {
+            PlatformCallbackUtils.computeTaskReduce(envPtr, taskPtr);
+        }
+        finally {
+            leave();
+        }
+    }
+
+    /**
+     * Complete task with native error.
+     *
+     * @param taskPtr Task pointer.
+     * @param memPtr Memory pointer with exception data or {@code 0} in case of success.
+     */
+    public void computeTaskComplete(long taskPtr, long memPtr) {
+        enter();
+
+        try {
+            PlatformCallbackUtils.computeTaskComplete(envPtr, taskPtr, memPtr);
+        }
+        finally {
+            leave();
+        }
+    }
+
+    /**
+     * Serialize native job.
+     *
+     * @param jobPtr Job pointer.
+     * @param memPtr Memory pointer.
+     * @return {@code True} if serialization succeeded.
+     */
+    public int computeJobSerialize(long jobPtr, long memPtr) {
+        enter();
+
+        try {
+            return PlatformCallbackUtils.computeJobSerialize(envPtr, jobPtr, memPtr);
+        }
+        finally {
+            leave();
+        }
+    }
+
+    /**
+     * Create job in native platform.
+     *
+     * @param memPtr Memory pointer.
+     * @return Pointer to job.
+     */
+    public long computeJobCreate(long memPtr) {
+        enter();
+
+        try {
+            return PlatformCallbackUtils.computeJobCreate(envPtr, memPtr);
+        }
+        finally {
+            leave();
+        }
+    }
+
+    /**
+     * Execute native job on a node other than where it was created.
+     *
+     * @param jobPtr Job pointer.
+     * @param cancel Cancel flag.
+     * @param memPtr Memory pointer to write result to for remote job execution or {@code 0} for local job execution.
+     */
+    public void computeJobExecute(long jobPtr, int cancel, long memPtr) {
+        enter();
+
+        try {
+            PlatformCallbackUtils.computeJobExecute(envPtr, jobPtr, cancel, memPtr);
+        }
+        finally {
+            leave();
+        }
+    }
+
+    /**
+     * Cancel the job.
+     *
+     * @param jobPtr Job pointer.
+     */
+    public void computeJobCancel(long jobPtr) {
+        enter();
+
+        try {
+            PlatformCallbackUtils.computeJobCancel(envPtr, jobPtr);
+        }
+        finally {
+            leave();
+        }
+    }
+
+    /**
+     * Destroy the job.
+     *
+     * @param ptr Pointer.
+     */
+    public void computeJobDestroy(long ptr) {
+        enter();
+
+        try {
+            PlatformCallbackUtils.computeJobDestroy(envPtr, ptr);
+        }
+        finally {
+            leave();
+        }
+    }
+
+    /**
+     * Invoke local callback.
+     *
+     * @param cbPtr Callback pointer.
+     * @param memPtr Memory pointer.
+     */
+    public void continuousQueryListenerApply(long cbPtr, long memPtr) {
+        enter();
+
+        try {
+            PlatformCallbackUtils.continuousQueryListenerApply(envPtr, cbPtr, memPtr);
+        }
+        finally {
+            leave();
+        }
+    }
+
+    /**
+     * Create filter in native platform.
+     *
+     * @param memPtr Memory pointer.
+     * @return Pointer to created filter.
+     */
+    public long continuousQueryFilterCreate(long memPtr) {
+        enter();
+
+        try {
+            return PlatformCallbackUtils.continuousQueryFilterCreate(envPtr, memPtr);
+        }
+        finally {
+            leave();
+        }
+    }
+
+    /**
+     * Invoke remote filter.
+     *
+     * @param filterPtr Filter pointer.
+     * @param memPtr Memory pointer.
+     * @return Result.
+     */
+    public int continuousQueryFilterApply(long filterPtr, long memPtr) {
+        enter();
+
+        try {
+            return PlatformCallbackUtils.continuousQueryFilterApply(envPtr, filterPtr, memPtr);
+        }
+        finally {
+            leave();
+        }
+    }
+
+    /**
+     * Release remote  filter.
+     *
+     * @param filterPtr Filter pointer.
+     */
+    public void continuousQueryFilterRelease(long filterPtr) {
+        enter();
+
+        try {
+            PlatformCallbackUtils.continuousQueryFilterRelease(envPtr, filterPtr);
+        }
+        finally {
+            leave();
+        }
+    }
+
+    /**
+     * Notify native data streamer about topology update.
+     *
+     * @param ptr Data streamer native pointer.
+     * @param topVer Topology version.
+     * @param topSize Topology size.
+     */
+    public void dataStreamerTopologyUpdate(long ptr, long topVer, int topSize) {
+        enter();
+
+        try {
+            PlatformCallbackUtils.dataStreamerTopologyUpdate(envPtr, ptr, topVer, topSize);
+        }
+        finally {
+            leave();
+        }
+    }
+
+    /**
+     * Invoke stream receiver.
+     *
+     * @param ptr Receiver native pointer.
+     * @param cache Cache object.
+     * @param memPtr Stream pointer.
+     * @param keepPortable Portable flag.
+     */
+    public void dataStreamerStreamReceiverInvoke(long ptr, Object cache, long memPtr, boolean keepPortable) {
+        enter();
+
+        try {
+            PlatformCallbackUtils.dataStreamerStreamReceiverInvoke(envPtr, ptr, cache, memPtr, keepPortable);
+        }
+        finally {
+            leave();
+        }
+    }
+
+    /**
+     * Notify future with byte result.
+     *
+     * @param futPtr Future pointer.
+     * @param res Result.
+     */
+    public void futureByteResult(long futPtr, int res) {
+        enter();
+
+        try {
+            PlatformCallbackUtils.futureByteResult(envPtr, futPtr, res);
+        }
+        finally {
+            leave();
+        }
+    }
+
+    /**
+     * Notify future with boolean result.
+     *
+     * @param futPtr Future pointer.
+     * @param res Result.
+     */
+    public void futureBoolResult(long futPtr, int res) {
+        enter();
+
+        try {
+            PlatformCallbackUtils.futureBoolResult(envPtr, futPtr, res);
+        }
+        finally {
+            leave();
+        }
+    }
+
+    /**
+     * Notify future with short result.
+     *
+     * @param futPtr Future pointer.
+     * @param res Result.
+     */
+    public void futureShortResult(long futPtr, int res) {
+        enter();
+
+        try {
+            PlatformCallbackUtils.futureShortResult(envPtr, futPtr, res);
+        }
+        finally {
+            leave();
+        }
+    }
+
+    /**
+     * Notify future with byte result.
+     *
+     * @param futPtr Future pointer.
+     * @param res Result.
+     */
+    public void futureCharResult(long futPtr, int res) {
+        enter();
+
+        try {
+            PlatformCallbackUtils.futureCharResult(envPtr, futPtr, res);
+        }
+        finally {
+            leave();
+        }
+    }
+
+    /**
+     * Notify future with int result.
+     *
+     * @param futPtr Future pointer.
+     * @param res Result.
+     */
+    public void futureIntResult(long futPtr, int res) {
+        enter();
+
+        try {
+            PlatformCallbackUtils.futureIntResult(envPtr, futPtr, res);
+        }
+        finally {
+            leave();
+        }
+    }
+
+    /**
+     * Notify future with float result.
+     *
+     * @param futPtr Future pointer.
+     * @param res Result.
+     */
+    public void futureFloatResult(long futPtr, float res) {
+        enter();
+
+        try {
+            PlatformCallbackUtils.futureFloatResult(envPtr, futPtr, res);
+        }
+        finally {
+            leave();
+        }
+    }
+
+    /**
+     * Notify future with long result.
+     *
+     * @param futPtr Future pointer.
+     * @param res Result.
+     */
+    public void futureLongResult(long futPtr, long res) {
+        enter();
+
+        try {
+            PlatformCallbackUtils.futureLongResult(envPtr, futPtr, res);
+        }
+        finally {
+            leave();
+        }
+    }
+
+    /**
+     * Notify future with double result.
+     *
+     * @param futPtr Future pointer.
+     * @param res Result.
+     */
+    public void futureDoubleResult(long futPtr, double res) {
+        enter();
+
+        try {
+            PlatformCallbackUtils.futureDoubleResult(envPtr, futPtr, res);
+        }
+        finally {
+            leave();
+        }
+    }
+
+    /**
+     * Notify future with object result.
+     *
+     * @param futPtr Future pointer.
+     * @param memPtr Memory pointer.
+     */
+    public void futureObjectResult(long futPtr, long memPtr) {
+        enter();
+
+        try {
+            PlatformCallbackUtils.futureObjectResult(envPtr, futPtr, memPtr);
+        }
+        finally {
+            leave();
+        }
+    }
+
+    /**
+     * Notify future with null result.
+     *
+     * @param futPtr Future pointer.
+     */
+    public void futureNullResult(long futPtr) {
+        enter();
+
+        try {
+            PlatformCallbackUtils.futureNullResult(envPtr, futPtr);
+        }
+        finally {
+            leave();
+        }
+    }
+
+    /**
+     * Notify future with error.
+     *
+     * @param futPtr Future pointer.
+     * @param memPtr Pointer to memory with error information.
+     */
+    public void futureError(long futPtr, long memPtr) {
+        enter();
+
+        try {
+            PlatformCallbackUtils.futureError(envPtr, futPtr, memPtr);
+        }
+        finally {
+            leave();
+        }
+    }
+
+    /**
+     * Creates message filter and returns a pointer.
+     *
+     * @param memPtr Memory pointer.
+     * @return Pointer.
+     */
+    public long messagingFilterCreate(long memPtr) {
+        enter();
+
+        try {
+            return PlatformCallbackUtils.messagingFilterCreate(envPtr, memPtr);
+        }
+        finally {
+            leave();
+        }
+    }
+
+    /**
+     * @param ptr Pointer.
+     * @param memPtr Memory pointer.
+     * @return Result.
+     */
+    public int messagingFilterApply(long ptr, long memPtr) {
+        enter();
+
+        try {
+            return PlatformCallbackUtils.messagingFilterApply(envPtr, ptr, memPtr);
+        }
+        finally {
+            leave();
+        }}
+
+    /**
+     * @param ptr Pointer.
+     */
+    public void messagingFilterDestroy(long ptr) {
+        enter();
+
+        try {
+            PlatformCallbackUtils.messagingFilterDestroy(envPtr, ptr);
+        }
+        finally {
+            leave();
+        }
+    }
+
+    /**
+     * Creates event filter and returns a pointer.
+     *
+     * @param memPtr Memory pointer.
+     * @return Pointer.
+     */
+    public long eventFilterCreate(long memPtr) {
+        enter();
+
+        try {
+            return PlatformCallbackUtils.eventFilterCreate(envPtr, memPtr);
+        }
+        finally {
+            leave();
+        }
+    }
+
+    /**
+     * @param ptr Pointer.
+     * @param memPtr Memory pointer.
+     * @return Result.
+     */
+    public int eventFilterApply(long ptr, long memPtr) {
+        enter();
+
+        try {
+            return PlatformCallbackUtils.eventFilterApply(envPtr, ptr, memPtr);
+        }
+        finally {
+            leave();
+        }
+    }
+
+    /**
+     * @param ptr Pointer.
+     */
+    public void eventFilterDestroy(long ptr) {
+        enter();
+
+        try {
+            PlatformCallbackUtils.eventFilterDestroy(envPtr, ptr);
+        }
+        finally {
+            leave();
+        }
+    }
+
+    /**
+     * Sends node info to native target.
+     *
+     * @param memPtr Ptr to a stream with serialized node.
+     */
+    public void nodeInfo(long memPtr) {
+        enter();
+
+        try {
+            PlatformCallbackUtils.nodeInfo(envPtr, memPtr);
+        }
+        finally {
+            leave();
+        }
+    }
+
+    /**
+     * Kernal start callback.
+     *
+     * @param memPtr Memory pointer.
+     */
+    public void onStart(long memPtr) {
+        enter();
+
+        try {
+            PlatformCallbackUtils.onStart(envPtr, memPtr);
+        }
+        finally {
+            leave();
+        }
+    }
+
+    /**
+     * Lifecycle event callback.
+     *
+     * @param ptr Holder pointer.
+     * @param evt Event.
+     */
+    public void lifecycleEvent(long ptr, int evt) {
+        enter();
+
+        try {
+            PlatformCallbackUtils.lifecycleEvent(envPtr, ptr, evt);
+        }
+        finally {
+            leave();
+        }
+    }
+
+    /**
+     * Re-allocate external memory chunk.
+     *
+     * @param memPtr Cross-platform pointer.
+     * @param cap Capacity.
+     */
+    public void memoryReallocate(long memPtr, int cap) {
+        enter();
+
+        try {
+            PlatformCallbackUtils.memoryReallocate(envPtr, memPtr, cap);
+        }
+        finally {
+            leave();
+        }
+    }
+
+    /**
+     * Initializes native service.
+     *
+     * @param memPtr Pointer.
+     * @throws org.apache.ignite.IgniteCheckedException In case of error.
+     */
+    public long serviceInit(long memPtr) throws IgniteCheckedException {
+        return PlatformCallbackUtils.serviceInit(envPtr, memPtr);
+    }
+
+    /**
+     * Executes native service.
+     *
+     * @param svcPtr Pointer to the service in the native platform.
+     * @param memPtr Stream pointer.
+     * @throws org.apache.ignite.IgniteCheckedException In case of error.
+     */
+    public void serviceExecute(long svcPtr, long memPtr) throws IgniteCheckedException {
+        PlatformCallbackUtils.serviceExecute(envPtr, svcPtr, memPtr);
+    }
+
+    /**
+     * Cancels native service.
+     *
+     * @param svcPtr Pointer to the service in the native platform.
+     * @param memPtr Stream pointer.
+     * @throws org.apache.ignite.IgniteCheckedException In case of error.
+     */
+    public void serviceCancel(long svcPtr, long memPtr) throws IgniteCheckedException {
+        PlatformCallbackUtils.serviceCancel(envPtr, svcPtr, memPtr);
+    }
+
+    /**
+     * Invokes service method.
+     *
+     * @param svcPtr Pointer to the service in the native platform.
+     * @param outMemPtr Output memory pointer.
+     * @param inMemPtr Input memory pointer.
+     * @throws org.apache.ignite.IgniteCheckedException In case of error.
+     */
+    public void serviceInvokeMethod(long svcPtr, long outMemPtr, long inMemPtr) throws IgniteCheckedException {
+        PlatformCallbackUtils.serviceInvokeMethod(envPtr, svcPtr, outMemPtr, inMemPtr);
+    }
+
+    /**
+     * Invokes cluster node filter.
+     *
+     * @param memPtr Stream pointer.
+     */
+    public int clusterNodeFilterApply(long memPtr) {
+        return PlatformCallbackUtils.clusterNodeFilterApply(envPtr, memPtr);
+    }
+
+    /**
+     * Kernal stop callback.
+     */
+    public void onStop() {
+        block();
+
+        PlatformCallbackUtils.onStop(envPtr);
+    }
+
+    /**
+     * Enter gateway.
+     */
+    protected void enter() {
+        if (!lock.tryReadLock())
+            throw new IgniteException("Failed to execute native callback because grid is stopping.");
+    }
+
+    /**
+     * Leave gateway.
+     */
+    protected void leave() {
+        lock.readUnlock();
+    }
+
+    /**
+     * Block gateway.
+     */
+    protected void block() {
+        lock.writeLock();
+    }
+}


[40/59] [abbrv] ignite git commit: IGNITE-1292: Moved handle registry to Ignite. Contributed by Pavel Tupitsyn.

Posted by vk...@apache.org.
IGNITE-1292: Moved handle registry to Ignite.
Contributed by Pavel Tupitsyn.


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

Branch: refs/heads/ignite-884
Commit: 7c351bf3e0ef5fd28b88d9a279a32f4796a60c91
Parents: 08be80f
Author: vozerov-gridgain <vo...@gridgain.com>
Authored: Wed Aug 26 12:10:32 2015 +0300
Committer: vozerov-gridgain <vo...@gridgain.com>
Committed: Wed Aug 26 12:10:32 2015 +0300

----------------------------------------------------------------------
 .../Apache.Ignite.Core.csproj                   |   3 +
 .../Apache.Ignite.Core/Impl/Handle/Handle.cs    |  69 ++++
 .../Impl/Handle/HandleRegistry.cs               | 340 +++++++++++++++++++
 .../Apache.Ignite.Core/Impl/Handle/IHandle.cs   |  35 ++
 4 files changed, 447 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/7c351bf3/modules/platform/src/main/dotnet/Apache.Ignite.Core/Apache.Ignite.Core.csproj
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Apache.Ignite.Core.csproj b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Apache.Ignite.Core.csproj
index c6c8324..658e5fb 100644
--- a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Apache.Ignite.Core.csproj
+++ b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Apache.Ignite.Core.csproj
@@ -48,6 +48,9 @@
   </ItemGroup>
   <ItemGroup>
     <Compile Include="Ignition.cs" />
+    <Compile Include="Impl\Handle\Handle.cs" />
+    <Compile Include="Impl\Handle\HandleRegistry.cs" />
+    <Compile Include="Impl\Handle\IHandle.cs" />
     <Compile Include="Impl\Memory\IPlatformMemory.cs" />
     <Compile Include="Impl\Memory\PlatformBigEndianMemoryStream.cs" />
     <Compile Include="Impl\Memory\PlatformMemory.cs" />

http://git-wip-us.apache.org/repos/asf/ignite/blob/7c351bf3/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Handle/Handle.cs
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Handle/Handle.cs b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Handle/Handle.cs
new file mode 100644
index 0000000..0168963
--- /dev/null
+++ b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Handle/Handle.cs
@@ -0,0 +1,69 @@
+/*
+ * 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.
+ */
+
+namespace Apache.Ignite.Core.Impl.Handle
+{
+    using System;
+    using System.Threading;
+
+    /// <summary>
+    /// Wrapper over some resource ensuring it's release.
+    /// </summary>
+    public class Handle<T> : IHandle
+    {
+        /** Target.*/
+        private readonly T _target;
+
+        /** Release action. */
+        private readonly Action<T> _releaseAction; 
+
+        /** Release flag. */
+        private int _released;
+
+        /// <summary>
+        /// Constructor.
+        /// </summary>
+        /// <param name="target">Target.</param>
+        /// <param name="releaseAction">Release action.</param>
+        public Handle(T target, Action<T> releaseAction)
+        {
+            _target = target;
+            _releaseAction = releaseAction;
+        }
+
+        /// <summary>
+        /// Target.
+        /// </summary>
+        public T Target
+        {
+            get { return _target; }
+        }
+
+        /** <inheritdoc /> */
+        public void Release()
+        {
+            if (Interlocked.CompareExchange(ref _released, 1, 0) == 0)
+                _releaseAction(_target);
+        }
+
+        /** <inheritdoc /> */
+        public bool Released
+        {
+            get { return Thread.VolatileRead(ref _released) == 1; }
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/7c351bf3/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Handle/HandleRegistry.cs
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Handle/HandleRegistry.cs b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Handle/HandleRegistry.cs
new file mode 100644
index 0000000..2a67c41
--- /dev/null
+++ b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Handle/HandleRegistry.cs
@@ -0,0 +1,340 @@
+/*
+ * 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.
+ */
+
+namespace Apache.Ignite.Core.Impl.Handle
+{
+    using System;
+    using System.Collections.Concurrent;
+    using System.Collections.Generic;
+    using System.Linq;
+    using System.Threading;
+
+    /// <summary>
+    /// Resource registry.
+    /// </summary>
+    public class HandleRegistry
+    {
+        /** Default critical resources capacity. */
+        internal const int DfltFastCap = 1024;
+
+        /** Array for fast-path. */
+        private readonly object[] _fast;
+
+        /** Dictionery for slow-path. */
+        private readonly ConcurrentDictionary<long, object> _slow;
+
+        /** Capacity of fast array. */
+        private readonly int _fastCap;
+
+        /** Counter for fast-path. */
+        private int _fastCtr;
+
+        /** Counter for slow-path. */
+        private long _slowCtr;
+
+        /** Close flag. */
+        private int _closed;
+
+        /// <summary>
+        /// Constructor.
+        /// </summary>
+        public HandleRegistry() : this(DfltFastCap)
+        {
+            // No-op.
+        }
+
+        /// <summary>
+        /// Constructor.
+        /// </summary>
+        /// <param name="fastCap">Amount of critical resources this registry can allocate in "fast" mode.</param>
+        public HandleRegistry(int fastCap)
+        {
+            _fastCap = fastCap;
+            _fast = new object[fastCap];
+
+            _slow = new ConcurrentDictionary<long, object>();
+            _slowCtr = fastCap;
+        }
+
+        /// <summary>
+        /// Allocate a handle for resource.
+        /// </summary>
+        /// <param name="target">Target.</param>
+        /// <returns>Pointer.</returns>
+        public long Allocate(object target)
+        {
+            return Allocate0(target, false, false);
+        }
+
+        /// <summary>
+        /// Allocate a handle in safe mode.
+        /// </summary>
+        /// <param name="target">Target.</param>
+        /// <returns>Pointer.</returns>
+        public long AllocateSafe(object target)
+        {
+            return Allocate0(target, false, true);
+        }
+
+        /// <summary>
+        /// Allocate a handle for critical resource.
+        /// </summary>
+        /// <param name="target">Target.</param>
+        /// <returns>Pointer.</returns>
+        public long AllocateCritical(object target)
+        {
+            return Allocate0(target, true, false);
+        }
+
+        /// <summary>
+        /// Allocate a handle for critical resource in safe mode.
+        /// </summary>
+        /// <param name="target">Target.</param>
+        /// <returns>Pointer.</returns>
+        public long AllocateCriticalSafe(object target)
+        {
+            return Allocate0(target, true, true);
+        }
+
+        /// <summary>
+        /// Internal allocation routine.
+        /// </summary>
+        /// <param name="target">Target.</param>
+        /// <param name="critical">Critical flag.</param>
+        /// <param name="safe">Safe flag.</param>
+        /// <returns>Pointer.</returns>
+        private long Allocate0(object target, bool critical, bool safe)
+        {
+            if (Closed)
+                throw ClosedException();
+
+            // Try allocating on critical path.
+            if (critical)
+            {
+                if (_fastCtr < _fastCap) // Non-volatile read could yield in old value, but increment resolves this.
+                {
+                    int fastIdx = Interlocked.Increment(ref _fastCtr);
+
+                    if (fastIdx < _fastCap)
+                    {
+                        Thread.VolatileWrite(ref _fast[fastIdx], target);
+
+                        if (safe && Closed)
+                        {
+                            Thread.VolatileWrite(ref _fast[fastIdx], null);
+
+                            Release0(target, true);
+
+                            throw ClosedException();
+                        }
+
+                        return fastIdx;
+                    }
+                }
+            }
+            
+            // Critical allocation failed, fallback to slow mode.
+            long slowIdx = Interlocked.Increment(ref _slowCtr);
+
+            _slow[slowIdx] = target;
+
+            if (safe && Closed)
+            {
+                _slow[slowIdx] = null;
+
+                Release0(target, true);
+
+                throw ClosedException();
+            }
+
+            return slowIdx;
+        }
+
+
+        /// <summary>
+        /// Release handle.
+        /// </summary>
+        /// <param name="id">Identifier.</param>
+        /// <param name="quiet">Whether release must be quiet or not.</param>
+        public void Release(long id, bool quiet = false)
+        {
+            if (id < _fastCap)
+            {
+                object target = Thread.VolatileRead(ref _fast[id]);
+
+                if (target != null)
+                {
+                    Thread.VolatileWrite(ref _fast[id], null);
+
+                    Release0(target, quiet);
+                }
+            }
+            else
+            {
+                object target;
+
+                if (_slow.TryRemove(id, out target))
+                    Release0(target, quiet);
+            }
+        }
+        
+        /// <summary>
+        /// Internal release routine.
+        /// </summary>
+        /// <param name="target">Target.</param>
+        /// <param name="quiet">Whether release must be quiet or not.</param>
+        private static void Release0(object target, bool quiet)
+        {
+            IHandle target0 = target as IHandle;
+
+            if (target0 != null)
+            {
+                if (quiet)
+                {
+                    try
+                    {
+                        target0.Release();
+                    }
+                    catch (Exception)
+                    {
+                        // No-op.
+                    }
+                }
+                else
+                    target0.Release();
+            }
+        }
+
+        /// <summary>
+        /// Gets handle target.
+        /// </summary>
+        /// <param name="id">Identifier.</param>
+        /// <returns>Target.</returns>
+        public T Get<T>(long id)
+        {
+            return Get<T>(id, false);
+        }
+
+        /// <summary>
+        /// Gets handle target.
+        /// </summary>
+        /// <param name="id">Identifier.</param>
+        /// <param name="throwOnAbsent">Whether to throw an exception if resource is not found.</param>
+        /// <returns>Target.</returns>
+        public T Get<T>(long id, bool throwOnAbsent)
+        {
+            object target;
+
+            if (id < _fastCap)
+            {
+                target = Thread.VolatileRead(ref _fast[id]);
+
+                if (target != null)
+                    return (T)target;
+            }
+            else
+            {
+                if (_slow.TryGetValue(id, out target))
+                    return (T) target;
+            }
+
+            if (throwOnAbsent)
+                throw new InvalidOperationException("Resource handle has been released (is grid stopping?).");
+
+            return default(T);
+        }
+
+        /// <summary>
+        /// Close the registry. All resources allocated at the moment of close are
+        /// guaranteed to be released.
+        /// </summary>
+        public void Close()
+        {
+            if (Interlocked.CompareExchange(ref _closed, 1, 0) == 0)
+            {
+                // Cleanup on fast-path.
+                for (int i = 0; i < _fastCap; i++)
+                {
+                    object target = Thread.VolatileRead(ref _fast[i]);
+
+                    if (target != null)
+                    {
+                        Thread.VolatileWrite(ref _fast[i], null);
+
+                        Release0(target, true);
+                    }
+                }
+
+                // Cleanup on slow-path.
+                foreach (var item in _slow)
+                {
+                    object target = item.Value;
+
+                    if (target != null)
+                        Release0(target, true);
+                }
+
+                _slow.Clear();
+            }
+        }
+
+        /// <summary>
+        /// Closed flag.
+        /// </summary>
+        public bool Closed
+        {
+            get { return Thread.VolatileRead(ref _closed) == 1; }
+        }
+
+        /// <summary>
+        /// Gets the current handle count.
+        /// </summary>
+        public int Count
+        {
+            get
+            {
+                Thread.MemoryBarrier();
+
+                return _fast.Count(x => x != null) + _slow.Count;
+            }
+        }
+
+        /// <summary>
+        /// Gets a snapshot of currently referenced objects list.
+        /// </summary>
+        public List<KeyValuePair<long, object>> GetItems()
+        {
+            Thread.MemoryBarrier();
+
+            return
+                _fast.Select((x, i) => new KeyValuePair<long, object>(i, x))
+                    .Where(x => x.Value != null)
+                    .Concat(_slow)
+                    .ToList();
+        }
+
+        /// <summary>
+        /// Create new exception for closed state.
+        /// </summary>
+        /// <returns>Exception.</returns>
+        private static Exception ClosedException()
+        {
+            return new InvalidOperationException("Cannot allocate a resource handle because grid is stopping.");
+        }
+    }
+}
+ 
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ignite/blob/7c351bf3/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Handle/IHandle.cs
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Handle/IHandle.cs b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Handle/IHandle.cs
new file mode 100644
index 0000000..d147f8b
--- /dev/null
+++ b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Handle/IHandle.cs
@@ -0,0 +1,35 @@
+/*
+ * 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.
+ */
+
+namespace Apache.Ignite.Core.Impl.Handle
+{
+    /// <summary>
+    /// Wrapper over some resource ensuring it's release.
+    /// </summary>
+    public interface IHandle
+    {
+        /// <summary>
+        /// Release the resource.
+        /// </summary>
+        void Release();
+
+        /// <summary>
+        /// Resource released flag.
+        /// </summary>
+        bool Released { get; }
+    }
+}
\ No newline at end of file


[42/59] [abbrv] ignite git commit: Moved platform future utils to Ignite.

Posted by vk...@apache.org.
Moved platform future utils to Ignite.


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

Branch: refs/heads/ignite-884
Commit: cdf82e942d0a2577cd077faf5c60dcc3bec4886a
Parents: bcf3054
Author: vozerov-gridgain <vo...@gridgain.com>
Authored: Wed Aug 26 12:47:55 2015 +0300
Committer: vozerov-gridgain <vo...@gridgain.com>
Committed: Wed Aug 26 12:47:55 2015 +0300

----------------------------------------------------------------------
 .../platform/PlatformExtendedException.java     |  39 +++
 .../platform/utils/PlatformFutureUtils.java     | 326 +++++++++++++++++++
 .../platform/utils/PlatformUtils.java           |  54 +++
 3 files changed, 419 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/cdf82e94/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/PlatformExtendedException.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/PlatformExtendedException.java b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/PlatformExtendedException.java
new file mode 100644
index 0000000..80b1703
--- /dev/null
+++ b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/PlatformExtendedException.java
@@ -0,0 +1,39 @@
+/*
+ * 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.platform;
+
+import org.apache.ignite.internal.portable.*;
+
+/**
+ * Denotes an exception which has some data to be written in a special manner.
+ */
+public interface PlatformExtendedException {
+    /**
+     * Gets platform context.
+     *
+     * @return Platform context.
+     */
+    public PlatformContext context();
+
+    /**
+     * Write data.
+     *
+     * @param writer Writer.
+     */
+    public void writeData(PortableRawWriterEx writer);
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/cdf82e94/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/utils/PlatformFutureUtils.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/utils/PlatformFutureUtils.java b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/utils/PlatformFutureUtils.java
new file mode 100644
index 0000000..fa986fe
--- /dev/null
+++ b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/utils/PlatformFutureUtils.java
@@ -0,0 +1,326 @@
+/*
+ * 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.platform.utils;
+
+import org.apache.ignite.internal.portable.*;
+import org.apache.ignite.internal.processors.platform.*;
+import org.apache.ignite.internal.processors.platform.callback.*;
+import org.apache.ignite.internal.processors.platform.memory.*;
+import org.apache.ignite.lang.*;
+import org.jetbrains.annotations.*;
+
+/**
+ * Interop future utils.
+ */
+public class PlatformFutureUtils {
+    /** Future type: byte. */
+    public static final int TYP_BYTE = 1;
+
+    /** Future type: boolean. */
+    public static final int TYP_BOOL = 2;
+
+    /** Future type: short. */
+    public static final int TYP_SHORT = 3;
+
+    /** Future type: char. */
+    public static final int TYP_CHAR = 4;
+
+    /** Future type: int. */
+    public static final int TYP_INT = 5;
+
+    /** Future type: float. */
+    public static final int TYP_FLOAT = 6;
+
+    /** Future type: long. */
+    public static final int TYP_LONG = 7;
+
+    /** Future type: double. */
+    public static final int TYP_DOUBLE = 8;
+
+    /** Future type: object. */
+    public static final int TYP_OBJ = 9;
+
+    /**
+     * Listen future.
+     *
+     * @param ctx Interop context.
+     * @param fut Java future.
+     * @param futPtr Native future pointer.
+     * @param typ Expected return type.
+     */
+    public static void listen(final PlatformContext ctx, IgniteFuture fut, final long futPtr, final int typ) {
+        listen(ctx, new FutureListenable(fut), futPtr, typ, null);
+    }
+
+    /**
+     * Listen future.
+     *
+     * @param ctx Interop context.
+     * @param fut Java future.
+     * @param futPtr Native future pointer.
+     * @param typ Expected return type.
+     * @param writer Writer.
+     */
+    public static void listen(final PlatformContext ctx, IgniteFuture fut, final long futPtr, final int typ,
+        Writer writer) {
+        listen(ctx, new FutureListenable(fut), futPtr, typ, writer);
+    }
+
+    /**
+     * Listen future.
+     *
+     * @param ctx Interop context.
+     * @param fut Java future.
+     * @param futPtr Native future pointer.
+     * @param writer Writer.
+     */
+    public static void listen(final PlatformContext ctx, IgniteFuture fut, final long futPtr, Writer writer) {
+        listen(ctx, new FutureListenable(fut), futPtr, TYP_OBJ, writer);
+    }
+
+    /**
+     * Listen future.
+     *
+     * @param ctx Interop context.
+     * @param listenable Listenable entry.
+     * @param futPtr Native future pointer.
+     * @param typ Expected return type.
+     * @param writer Optional writer.
+     */
+    @SuppressWarnings("unchecked")
+    private static void listen(final PlatformContext ctx, Listenable listenable, final long futPtr, final int typ,
+        @Nullable final Writer writer) {
+        final PlatformCallbackGateway gate = ctx.gateway();
+
+        listenable.listen(new IgniteBiInClosure<Object, Throwable>() {
+            private static final long serialVersionUID = 0L;
+
+            @Override public void apply(Object res, Throwable err) {
+                if (writer != null && writeToWriter(res, err, ctx, writer, futPtr))
+                    return;
+
+                if (err != null) {
+                    writeFutureError(ctx, futPtr, err);
+
+                    return;
+                }
+
+                try {
+                    if (typ == TYP_OBJ) {
+                        if (res == null)
+                            gate.futureNullResult(futPtr);
+                        else {
+                            try (PlatformMemory mem = ctx.memory().allocate()) {
+                                PlatformOutputStream out = mem.output();
+
+                                PortableRawWriterEx outWriter = ctx.writer(out);
+
+                                outWriter.writeObjectDetached(res);
+
+                                out.synchronize();
+
+                                gate.futureObjectResult(futPtr, mem.pointer());
+                            }
+                        }
+                    }
+                    else if (res == null)
+                        gate.futureNullResult(futPtr);
+                    else {
+                        switch (typ) {
+                            case TYP_BYTE:
+                                gate.futureByteResult(futPtr, (byte) res);
+
+                                break;
+
+                            case TYP_BOOL:
+                                gate.futureBoolResult(futPtr, (boolean) res ? 1 : 0);
+
+                                break;
+
+                            case TYP_SHORT:
+                                gate.futureShortResult(futPtr, (short) res);
+
+                                break;
+
+                            case TYP_CHAR:
+                                gate.futureCharResult(futPtr, (char) res);
+
+                                break;
+
+                            case TYP_INT:
+                                gate.futureIntResult(futPtr, (int) res);
+
+                                break;
+
+                            case TYP_FLOAT:
+                                gate.futureFloatResult(futPtr, (float) res);
+
+                                break;
+
+                            case TYP_LONG:
+                                gate.futureLongResult(futPtr, (long) res);
+
+                                break;
+
+                            case TYP_DOUBLE:
+                                gate.futureDoubleResult(futPtr, (double) res);
+
+                                break;
+
+                            default:
+                                assert false : "Should not reach this: " + typ;
+                        }
+                    }
+                }
+                catch (Throwable t) {
+                    writeFutureError(ctx, futPtr, t);
+
+                    if (t instanceof Error)
+                        throw t;
+                }
+            }
+        });
+    }
+
+    /**
+     * Write future error.
+     *
+     * @param ctx Interop context.
+     * @param futPtr Future pointer.
+     * @param err Error.
+     */
+    private static void writeFutureError(final PlatformContext ctx, long futPtr, Throwable err) {
+        try (PlatformMemory mem = ctx.memory().allocate()) {
+            PlatformOutputStream out = mem.output();
+
+            PortableRawWriterEx outWriter = ctx.writer(out);
+
+            outWriter.writeString(err.getClass().getName());
+            outWriter.writeString(err.getMessage());
+
+            PlatformUtils.writeErrorData(err, outWriter);
+
+            out.synchronize();
+
+            ctx.gateway().futureError(futPtr, mem.pointer());
+        }
+    }
+
+    /**
+     * Write result to a custom writer
+     *
+     * @param obj Object to write.
+     * @param err Error to write.
+     * @param ctx Interop context.
+     * @param writer Writer.
+     * @param futPtr Future pointer.
+     * @return Value indicating whether custom write was performed. When false, default write will be used.
+     */
+    private static boolean writeToWriter(Object obj, Throwable err, PlatformContext ctx, Writer writer, long futPtr) {
+        boolean canWrite = writer.canWrite(obj, err);
+
+        if (!canWrite)
+            return false;
+
+        try (PlatformMemory mem = ctx.memory().allocate()) {
+            PlatformOutputStream out = mem.output();
+
+            PortableRawWriterEx outWriter = ctx.writer(out);
+
+            writer.write(outWriter, obj, err);
+
+            out.synchronize();
+
+            ctx.gateway().futureObjectResult(futPtr, mem.pointer());
+        }
+
+        return true;
+    }
+
+    /**
+     * Writer allowing special future result handling.
+     */
+    public static interface Writer {
+        /**
+         * Write object.
+         *
+         * @param writer Writer.
+         * @param obj Object.
+         * @param err Error.
+         */
+        public void write(PortableRawWriterEx writer, Object obj, Throwable err);
+
+        /**
+         * Determines whether this writer can write given data.
+         *
+         * @param obj Object.
+         * @param err Error.
+         * @return Value indicating whether this writer can write given data.
+         */
+        public boolean canWrite(Object obj, Throwable err);
+    }
+
+    /**
+     * Listenable entry.
+     */
+    private static interface Listenable {
+        /**
+         * Listen.
+         *
+         * @param lsnr Listener.
+         */
+        public void listen(IgniteBiInClosure<Object, Throwable> lsnr);
+    }
+
+    /**
+     * Listenable around Ignite future.
+     */
+    private static class FutureListenable implements Listenable {
+        /** Future. */
+        private final IgniteFuture fut;
+
+        /**
+         * Constructor.
+         *
+         * @param fut Future.
+         */
+        public FutureListenable(IgniteFuture fut) {
+            this.fut = fut;
+        }
+
+        /** {@inheritDoc} */
+        @SuppressWarnings("unchecked")
+        @Override public void listen(final IgniteBiInClosure<Object, Throwable> lsnr) {
+            fut.listen(new IgniteInClosure<IgniteFuture>() {
+                private static final long serialVersionUID = 0L;
+
+                @Override public void apply(IgniteFuture fut0) {
+                    try {
+                        lsnr.apply(fut0.get(), null);
+                    }
+                    catch (Throwable err) {
+                        lsnr.apply(null, err);
+
+                        if (err instanceof Error)
+                            throw err;
+                    }
+                }
+            });
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/cdf82e94/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/utils/PlatformUtils.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/utils/PlatformUtils.java b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/utils/PlatformUtils.java
index a620f8e..614346a 100644
--- a/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/utils/PlatformUtils.java
+++ b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/utils/PlatformUtils.java
@@ -523,6 +523,60 @@ public class PlatformUtils {
     }
 
     /**
+     * Writer error data.
+     *
+     * @param err Error.
+     * @param writer Writer.
+     */
+    public static void writeErrorData(Throwable err, PortableRawWriterEx writer) {
+        writeErrorData(err, writer, null);
+    }
+
+    /**
+     * Write error data.
+     * @param err Error.
+     * @param writer Writer.
+     * @param log Optional logger.
+     */
+    public static void writeErrorData(Throwable err, PortableRawWriterEx writer, @Nullable IgniteLogger log) {
+        // Write additional data if needed.
+        if (err instanceof PlatformExtendedException) {
+            PlatformExtendedException err0 = (PlatformExtendedException)err;
+
+            writer.writeBoolean(true); // Data exists.
+
+            int pos = writer.out().position();
+
+            try {
+                writer.writeBoolean(true); // Optimistically assume that we will be able to write it.
+                err0.writeData(writer);
+            }
+            catch (Exception e) {
+                if (log != null)
+                    U.warn(log, "Failed to write interop exception data: " + e.getMessage(), e);
+
+                writer.out().position(pos);
+
+                writer.writeBoolean(false); // Error occurred.
+                writer.writeString(e.getClass().getName());
+
+                String innerMsg;
+
+                try {
+                    innerMsg = e.getMessage();
+                }
+                catch (Exception innerErr) {
+                    innerMsg = "Exception message is not available.";
+                }
+
+                writer.writeString(innerMsg);
+            }
+        }
+        else
+            writer.writeBoolean(false);
+    }
+
+    /**
      * Private constructor.
      */
     private PlatformUtils() {


[57/59] [abbrv] ignite git commit: Restored backward compatibility for cache objects

Posted by vk...@apache.org.
Restored backward compatibility for cache objects


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

Branch: refs/heads/ignite-884
Commit: e428206d3d2281de72e674fe5abf9f887bf221fc
Parents: 38b3ffd
Author: Valentin Kulichenko <va...@gmail.com>
Authored: Wed Aug 26 15:50:34 2015 -0700
Committer: Valentin Kulichenko <va...@gmail.com>
Committed: Wed Aug 26 15:50:34 2015 -0700

----------------------------------------------------------------------
 .../cache/portable/CacheObjectPortableProcessorImpl.java          | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/e428206d/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/portable/CacheObjectPortableProcessorImpl.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/portable/CacheObjectPortableProcessorImpl.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/portable/CacheObjectPortableProcessorImpl.java
index a421129..e70feb9 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/portable/CacheObjectPortableProcessorImpl.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/portable/CacheObjectPortableProcessorImpl.java
@@ -36,6 +36,7 @@ import org.apache.ignite.internal.util.typedef.internal.*;
 import org.apache.ignite.lang.*;
 import org.apache.ignite.marshaller.*;
 import org.apache.ignite.marshaller.portable.*;
+import org.apache.ignite.plugin.*;
 import org.apache.ignite.portable.*;
 
 import org.jetbrains.annotations.*;
@@ -569,7 +570,7 @@ public class CacheObjectPortableProcessorImpl extends IgniteCacheObjectProcessor
     }
 
     /** {@inheritDoc} */
-    @Override public boolean isPortableEnabled() {
+    @Override public boolean isPortableEnabled(CacheConfiguration<?, ?> ccfg) {
         return marsh instanceof PortableMarshaller;
     }
 


[06/59] [abbrv] ignite git commit: ignite-1258: portable objects API support in Ignite

Posted by vk...@apache.org.
http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/portable/PortableSerializer.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/portable/PortableSerializer.java b/modules/core/src/main/java/org/apache/ignite/portable/PortableSerializer.java
new file mode 100644
index 0000000..54b0937
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/portable/PortableSerializer.java
@@ -0,0 +1,49 @@
+/*
+ * 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.portable;
+
+import org.apache.ignite.marshaller.portable.*;
+
+/**
+ * Interface that allows to implement custom serialization logic for portable objects.
+ * Can be used instead of {@link PortableMarshalAware} in case if the class
+ * cannot be changed directly.
+ * <p>
+ * Portable serializer can be configured for all portable objects via
+ * {@link PortableMarshaller#getSerializer()} method, or for a specific
+ * portable type via {@link PortableTypeConfiguration#getSerializer()} method.
+ */
+public interface PortableSerializer {
+    /**
+     * Writes fields to provided writer.
+     *
+     * @param obj Empty object.
+     * @param writer Portable object writer.
+     * @throws PortableException In case of error.
+     */
+    public void writePortable(Object obj, PortableWriter writer) throws PortableException;
+
+    /**
+     * Reads fields from provided reader.
+     *
+     * @param obj Empty object
+     * @param reader Portable object reader.
+     * @throws PortableException In case of error.
+     */
+    public void readPortable(Object obj, PortableReader reader) throws PortableException;
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/portable/PortableTypeConfiguration.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/portable/PortableTypeConfiguration.java b/modules/core/src/main/java/org/apache/ignite/portable/PortableTypeConfiguration.java
new file mode 100644
index 0000000..b221298
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/portable/PortableTypeConfiguration.java
@@ -0,0 +1,197 @@
+/*
+ * 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.portable;
+
+import org.apache.ignite.internal.util.typedef.internal.*;
+import org.apache.ignite.marshaller.portable.*;
+
+import java.sql.*;
+import java.util.*;
+
+/**
+ * Defines configuration properties for a specific portable type. Providing per-type
+ * configuration is optional, as it is generally enough, and also optional, to provide global portable
+ * configuration using {@link PortableMarshaller#setClassNames(Collection)}.
+ * However, this class allows you to change configuration properties for a specific
+ * portable type without affecting configuration for other portable types.
+ * <p>
+ * Per-type portable configuration can be specified in {@link PortableMarshaller#getTypeConfigurations()} method.
+ */
+public class PortableTypeConfiguration {
+    /** Class name. */
+    private String clsName;
+
+    /** ID mapper. */
+    private PortableIdMapper idMapper;
+
+    /** Serializer. */
+    private PortableSerializer serializer;
+
+    /** Use timestamp flag. */
+    private Boolean useTs;
+
+    /** Meta data enabled flag. */
+    private Boolean metaDataEnabled;
+
+    /** Keep deserialized flag. */
+    private Boolean keepDeserialized;
+
+    /** Affinity key field name. */
+    private String affKeyFieldName;
+
+    /**
+     */
+    public PortableTypeConfiguration() {
+        // No-op.
+    }
+
+    /**
+     * @param clsName Class name.
+     */
+    public PortableTypeConfiguration(String clsName) {
+        this.clsName = clsName;
+    }
+
+    /**
+     * Gets type name.
+     *
+     * @return Type name.
+     */
+    public String getClassName() {
+        return clsName;
+    }
+
+    /**
+     * Sets type name.
+     *
+     * @param clsName Type name.
+     */
+    public void setClassName(String clsName) {
+        this.clsName = clsName;
+    }
+
+    /**
+     * Gets ID mapper.
+     *
+     * @return ID mapper.
+     */
+    public PortableIdMapper getIdMapper() {
+        return idMapper;
+    }
+
+    /**
+     * Sets ID mapper.
+     *
+     * @param idMapper ID mapper.
+     */
+    public void setIdMapper(PortableIdMapper idMapper) {
+        this.idMapper = idMapper;
+    }
+
+    /**
+     * Gets serializer.
+     *
+     * @return Serializer.
+     */
+    public PortableSerializer getSerializer() {
+        return serializer;
+    }
+
+    /**
+     * Sets serializer.
+     *
+     * @param serializer Serializer.
+     */
+    public void setSerializer(PortableSerializer serializer) {
+        this.serializer = serializer;
+    }
+
+    /**
+     * If {@code true} then date values converted to {@link Timestamp} during unmarshalling.
+     *
+     * @return Flag indicating whether date values converted to {@link Timestamp} during unmarshalling.
+     */
+    public Boolean isUseTimestamp() {
+        return useTs;
+    }
+
+    /**
+     * @param useTs Flag indicating whether date values converted to {@link Timestamp} during unmarshalling.
+     */
+    public void setUseTimestamp(Boolean useTs) {
+        this.useTs = useTs;
+    }
+
+    /**
+     * Defines whether meta data is collected for this type. If provided, this value will override
+     * {@link PortableMarshaller#isMetaDataEnabled()} property.
+     *
+     * @return Whether meta data is collected.
+     */
+    public Boolean isMetaDataEnabled() {
+        return metaDataEnabled;
+    }
+
+    /**
+     * @param metaDataEnabled Whether meta data is collected.
+     */
+    public void setMetaDataEnabled(Boolean metaDataEnabled) {
+        this.metaDataEnabled = metaDataEnabled;
+    }
+
+    /**
+     * Defines whether {@link PortableObject} should cache deserialized instance. If provided,
+     * this value will override {@link PortableMarshaller#isKeepDeserialized()}
+     * property.
+     *
+     * @return Whether deserialized value is kept.
+     */
+    public Boolean isKeepDeserialized() {
+        return keepDeserialized;
+    }
+
+    /**
+     * @param keepDeserialized Whether deserialized value is kept.
+     */
+    public void setKeepDeserialized(Boolean keepDeserialized) {
+        this.keepDeserialized = keepDeserialized;
+    }
+
+    /**
+     * Gets affinity key field name.
+     *
+     * @return Affinity key field name.
+     */
+    public String getAffinityKeyFieldName() {
+        return affKeyFieldName;
+    }
+
+    /**
+     * Sets affinity key field name.
+     *
+     * @param affKeyFieldName Affinity key field name.
+     */
+    public void setAffinityKeyFieldName(String affKeyFieldName) {
+        this.affKeyFieldName = affKeyFieldName;
+    }
+
+    /** {@inheritDoc} */
+    @Override public String toString() {
+        return S.toString(PortableTypeConfiguration.class, this, super.toString());
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/portable/PortableWriter.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/portable/PortableWriter.java b/modules/core/src/main/java/org/apache/ignite/portable/PortableWriter.java
new file mode 100644
index 0000000..36fa608
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/portable/PortableWriter.java
@@ -0,0 +1,265 @@
+/*
+ * 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.portable;
+
+import org.jetbrains.annotations.*;
+
+import java.math.*;
+import java.sql.*;
+import java.util.*;
+import java.util.Date;
+
+/**
+ * Writer for portable object used in {@link PortableMarshalAware} implementations.
+ * Useful for the cases when user wants a fine-grained control over serialization.
+ * <p>
+ * Note that Ignite never writes full strings for field or type names. Instead,
+ * for performance reasons, Ignite writes integer hash codes for type and field names.
+ * It has been tested that hash code conflicts for the type names or the field names
+ * within the same type are virtually non-existent and, to gain performance, it is safe
+ * to work with hash codes. For the cases when hash codes for different types or fields
+ * actually do collide, Ignite provides {@link PortableIdMapper} which
+ * allows to override the automatically generated hash code IDs for the type and field names.
+ */
+public interface PortableWriter {
+    /**
+     * @param fieldName Field name.
+     * @param val Value to write.
+     * @throws PortableException In case of error.
+     */
+    public void writeByte(String fieldName, byte val) throws PortableException;
+
+    /**
+     * @param fieldName Field name.
+     * @param val Value to write.
+     * @throws PortableException In case of error.
+     */
+    public void writeShort(String fieldName, short val) throws PortableException;
+
+    /**
+     * @param fieldName Field name.
+     * @param val Value to write.
+     * @throws PortableException In case of error.
+     */
+    public void writeInt(String fieldName, int val) throws PortableException;
+
+    /**
+     * @param fieldName Field name.
+     * @param val Value to write.
+     * @throws PortableException In case of error.
+     */
+    public void writeLong(String fieldName, long val) throws PortableException;
+
+    /**
+     * @param fieldName Field name.
+     * @param val Value to write.
+     * @throws PortableException In case of error.
+     */
+    public void writeFloat(String fieldName, float val) throws PortableException;
+
+    /**
+     * @param fieldName Field name.
+     * @param val Value to write.
+     * @throws PortableException In case of error.
+     */
+    public void writeDouble(String fieldName, double val) throws PortableException;
+
+    /**
+     * @param fieldName Field name.
+     * @param val Value to write.
+     * @throws PortableException In case of error.
+     */
+    public void writeChar(String fieldName, char val) throws PortableException;
+
+    /**
+     * @param fieldName Field name.
+     * @param val Value to write.
+     * @throws PortableException In case of error.
+     */
+    public void writeBoolean(String fieldName, boolean val) throws PortableException;
+
+    /**
+     * @param fieldName Field name.
+     * @param val Value to write.
+     * @throws PortableException In case of error.
+     */
+    public void writeDecimal(String fieldName, @Nullable BigDecimal val) throws PortableException;
+
+    /**
+     * @param fieldName Field name.
+     * @param val Value to write.
+     * @throws PortableException In case of error.
+     */
+    public void writeString(String fieldName, @Nullable String val) throws PortableException;
+
+    /**
+     * @param fieldName Field name.
+     * @param val UUID to write.
+     * @throws PortableException In case of error.
+     */
+    public void writeUuid(String fieldName, @Nullable UUID val) throws PortableException;
+
+    /**
+     * @param fieldName Field name.
+     * @param val Date to write.
+     * @throws PortableException In case of error.
+     */
+    public void writeDate(String fieldName, @Nullable Date val) throws PortableException;
+
+    /**
+     * @param fieldName Field name.
+     * @param val Timestamp to write.
+     * @throws PortableException In case of error.
+     */
+    public void writeTimestamp(String fieldName, @Nullable Timestamp val) throws PortableException;
+
+    /**
+     * @param fieldName Field name.
+     * @param obj Value to write.
+     * @throws PortableException In case of error.
+     */
+    public void writeObject(String fieldName, @Nullable Object obj) throws PortableException;
+
+    /**
+     * @param fieldName Field name.
+     * @param val Value to write.
+     * @throws PortableException In case of error.
+     */
+    public void writeByteArray(String fieldName, @Nullable byte[] val) throws PortableException;
+
+    /**
+     * @param fieldName Field name.
+     * @param val Value to write.
+     * @throws PortableException In case of error.
+     */
+    public void writeShortArray(String fieldName, @Nullable short[] val) throws PortableException;
+
+    /**
+     * @param fieldName Field name.
+     * @param val Value to write.
+     * @throws PortableException In case of error.
+     */
+    public void writeIntArray(String fieldName, @Nullable int[] val) throws PortableException;
+
+    /**
+     * @param fieldName Field name.
+     * @param val Value to write.
+     * @throws PortableException In case of error.
+     */
+    public void writeLongArray(String fieldName, @Nullable long[] val) throws PortableException;
+
+    /**
+     * @param fieldName Field name.
+     * @param val Value to write.
+     * @throws PortableException In case of error.
+     */
+    public void writeFloatArray(String fieldName, @Nullable float[] val) throws PortableException;
+
+    /**
+     * @param fieldName Field name.
+     * @param val Value to write.
+     * @throws PortableException In case of error.
+     */
+    public void writeDoubleArray(String fieldName, @Nullable double[] val) throws PortableException;
+
+    /**
+     * @param fieldName Field name.
+     * @param val Value to write.
+     * @throws PortableException In case of error.
+     */
+    public void writeCharArray(String fieldName, @Nullable char[] val) throws PortableException;
+
+    /**
+     * @param fieldName Field name.
+     * @param val Value to write.
+     * @throws PortableException In case of error.
+     */
+    public void writeBooleanArray(String fieldName, @Nullable boolean[] val) throws PortableException;
+
+    /**
+     * @param fieldName Field name.
+     * @param val Value to write.
+     * @throws PortableException In case of error.
+     */
+    public void writeDecimalArray(String fieldName, @Nullable BigDecimal[] val) throws PortableException;
+
+    /**
+     * @param fieldName Field name.
+     * @param val Value to write.
+     * @throws PortableException In case of error.
+     */
+    public void writeStringArray(String fieldName, @Nullable String[] val) throws PortableException;
+
+    /**
+     * @param fieldName Field name.
+     * @param val Value to write.
+     * @throws PortableException In case of error.
+     */
+    public void writeUuidArray(String fieldName, @Nullable UUID[] val) throws PortableException;
+
+    /**
+     * @param fieldName Field name.
+     * @param val Value to write.
+     * @throws PortableException In case of error.
+     */
+    public void writeDateArray(String fieldName, @Nullable Date[] val) throws PortableException;
+
+    /**
+     * @param fieldName Field name.
+     * @param val Value to write.
+     * @throws PortableException In case of error.
+     */
+    public void writeObjectArray(String fieldName, @Nullable Object[] val) throws PortableException;
+
+    /**
+     * @param fieldName Field name.
+     * @param col Collection to write.
+     * @throws PortableException In case of error.
+     */
+    public <T> void writeCollection(String fieldName, @Nullable Collection<T> col) throws PortableException;
+
+    /**
+     * @param fieldName Field name.
+     * @param map Map to write.
+     * @throws PortableException In case of error.
+     */
+    public <K, V> void writeMap(String fieldName, @Nullable Map<K, V> map) throws PortableException;
+
+    /**
+     * @param fieldName Field name.
+     * @param val Value to write.
+     * @throws PortableException In case of error.
+     */
+    public <T extends Enum<?>> void writeEnum(String fieldName, T val) throws PortableException;
+
+    /**
+     * @param fieldName Field name.
+     * @param val Value to write.
+     * @throws PortableException In case of error.
+     */
+    public <T extends Enum<?>> void writeEnumArray(String fieldName, T[] val) throws PortableException;
+
+    /**
+     * Gets raw writer. Raw writer does not write field name hash codes, therefore,
+     * making the format even more compact. However, if the raw writer is used,
+     * dynamic structure changes to the portable objects are not supported.
+     *
+     * @return Raw writer.
+     */
+    public PortableRawWriter rawWriter();
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/java/org/apache/ignite/portable/package-info.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/portable/package-info.java b/modules/core/src/main/java/org/apache/ignite/portable/package-info.java
new file mode 100644
index 0000000..0105b15
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/portable/package-info.java
@@ -0,0 +1,22 @@
+/*
+ * 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 description. -->
+ * Contains portable objects API classes.
+ */
+package org.apache.ignite.portable;
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/main/resources/META-INF/classnames.properties
----------------------------------------------------------------------
diff --git a/modules/core/src/main/resources/META-INF/classnames.properties b/modules/core/src/main/resources/META-INF/classnames.properties
index 1fb9a37..c5f060b 100644
--- a/modules/core/src/main/resources/META-INF/classnames.properties
+++ b/modules/core/src/main/resources/META-INF/classnames.properties
@@ -17,6 +17,7 @@
 
 org.apache.ignite.IgniteAuthenticationException
 org.apache.ignite.IgniteCheckedException
+org.apache.ignite.IgniteClientDisconnectedException
 org.apache.ignite.IgniteDeploymentException
 org.apache.ignite.IgniteException
 org.apache.ignite.IgniteIllegalStateException
@@ -35,7 +36,6 @@ org.apache.ignite.cache.CacheMode
 org.apache.ignite.cache.CachePartialUpdateException
 org.apache.ignite.cache.CachePeekMode
 org.apache.ignite.cache.CacheRebalanceMode
-org.apache.ignite.cache.CacheEntry
 org.apache.ignite.cache.CacheServerNotFoundException
 org.apache.ignite.cache.CacheTypeFieldMetadata
 org.apache.ignite.cache.CacheTypeMetadata
@@ -70,6 +70,8 @@ org.apache.ignite.cache.query.SqlQuery
 org.apache.ignite.cache.query.TextQuery
 org.apache.ignite.cache.store.jdbc.CacheAbstractJdbcStore$EntryMapping$1
 org.apache.ignite.cache.store.jdbc.CacheAbstractJdbcStore$EntryMapping$2
+org.apache.ignite.cache.store.jdbc.CacheJdbcBlobStoreFactory
+org.apache.ignite.cache.store.jdbc.CacheJdbcPojoStoreFactory
 org.apache.ignite.cache.store.jdbc.dialect.BasicJdbcDialect$1
 org.apache.ignite.cache.store.jdbc.dialect.BasicJdbcDialect$2
 org.apache.ignite.cache.store.jdbc.dialect.BasicJdbcDialect$3
@@ -111,7 +113,6 @@ org.apache.ignite.compute.gridify.aop.GridifyDefaultRangeTask
 org.apache.ignite.compute.gridify.aop.GridifyDefaultTask
 org.apache.ignite.configuration.CacheConfiguration
 org.apache.ignite.configuration.CacheConfiguration$IgniteAllNodesPredicate
-org.apache.ignite.configuration.CacheConfiguration$IgniteServerNodePredicate
 org.apache.ignite.configuration.CollectionConfiguration
 org.apache.ignite.configuration.DeploymentMode
 org.apache.ignite.configuration.IgniteReflectionFactory
@@ -186,6 +187,7 @@ org.apache.ignite.internal.GridTopic$T5
 org.apache.ignite.internal.GridTopic$T6
 org.apache.ignite.internal.GridTopic$T7
 org.apache.ignite.internal.GridTopic$T8
+org.apache.ignite.internal.IgniteClientDisconnectedCheckedException
 org.apache.ignite.internal.IgniteComponentType
 org.apache.ignite.internal.IgniteComputeImpl
 org.apache.ignite.internal.IgniteDeploymentCheckedException
@@ -196,6 +198,7 @@ org.apache.ignite.internal.IgniteFutureTimeoutCheckedException
 org.apache.ignite.internal.IgniteInterruptedCheckedException
 org.apache.ignite.internal.IgniteKernal
 org.apache.ignite.internal.IgniteKernal$1
+org.apache.ignite.internal.IgniteKernal$5
 org.apache.ignite.internal.IgniteMessagingImpl
 org.apache.ignite.internal.IgniteSchedulerImpl
 org.apache.ignite.internal.IgniteServicesImpl
@@ -226,6 +229,7 @@ org.apache.ignite.internal.cluster.ClusterGroupAdapter$AttributeFilter
 org.apache.ignite.internal.cluster.ClusterGroupAdapter$CachesFilter
 org.apache.ignite.internal.cluster.ClusterGroupAdapter$DaemonFilter
 org.apache.ignite.internal.cluster.ClusterGroupAdapter$GroupPredicate
+org.apache.ignite.internal.cluster.ClusterGroupAdapter$HostsFilter
 org.apache.ignite.internal.cluster.ClusterGroupAdapter$OthersFilter
 org.apache.ignite.internal.cluster.ClusterGroupEmptyCheckedException
 org.apache.ignite.internal.cluster.ClusterNodeLocalMapImpl
@@ -243,33 +247,48 @@ org.apache.ignite.internal.executor.GridExecutorService
 org.apache.ignite.internal.executor.GridExecutorService$1
 org.apache.ignite.internal.executor.GridExecutorService$TaskTerminateListener
 org.apache.ignite.internal.igfs.common.IgfsIpcCommand
+org.apache.ignite.internal.interop.InteropAwareEventFilter
+org.apache.ignite.internal.interop.InteropBootstrapFactory
+org.apache.ignite.internal.interop.InteropException
+org.apache.ignite.internal.interop.InteropNoCallbackException
 org.apache.ignite.internal.managers.GridManagerAdapter$1$1
 org.apache.ignite.internal.managers.checkpoint.GridCheckpointManager$CheckpointSet
 org.apache.ignite.internal.managers.checkpoint.GridCheckpointRequest
 org.apache.ignite.internal.managers.communication.GridIoManager$ConcurrentHashMap0
 org.apache.ignite.internal.managers.communication.GridIoMessage
-org.apache.ignite.internal.managers.communication.GridIoPolicy
 org.apache.ignite.internal.managers.communication.GridIoUserMessage
 org.apache.ignite.internal.managers.communication.GridLifecycleAwareMessageFilter
 org.apache.ignite.internal.managers.deployment.GridDeploymentInfoBean
 org.apache.ignite.internal.managers.deployment.GridDeploymentPerVersionStore$2
 org.apache.ignite.internal.managers.deployment.GridDeploymentRequest
 org.apache.ignite.internal.managers.deployment.GridDeploymentResponse
+org.apache.ignite.internal.managers.discovery.CustomMessageWrapper
+org.apache.ignite.internal.managers.discovery.DiscoveryCustomMessage
 org.apache.ignite.internal.managers.discovery.GridDiscoveryManager$1
-org.apache.ignite.internal.managers.discovery.GridDiscoveryManager$4$1
-org.apache.ignite.internal.managers.discovery.GridDiscoveryManager$6
+org.apache.ignite.internal.managers.discovery.GridDiscoveryManager$2
+org.apache.ignite.internal.managers.discovery.GridDiscoveryManager$5$1
+org.apache.ignite.internal.managers.discovery.GridDiscoveryManager$5$2
+org.apache.ignite.internal.managers.discovery.GridDiscoveryManager$7
 org.apache.ignite.internal.managers.discovery.GridDiscoveryManager$DiscoCache$1
 org.apache.ignite.internal.managers.discovery.GridLocalMetrics
 org.apache.ignite.internal.managers.eventstorage.GridEventStorageMessage
 org.apache.ignite.internal.managers.indexing.GridIndexingManager$1
 org.apache.ignite.internal.managers.loadbalancer.GridLoadBalancerAdapter
 org.apache.ignite.internal.managers.loadbalancer.GridLoadBalancerManager$1
+org.apache.ignite.internal.portable.PortableClassDescriptor$Mode
+org.apache.ignite.internal.portable.PortableContext
+org.apache.ignite.internal.portable.PortableLazyMap$1$1$1
+org.apache.ignite.internal.portable.PortableMetaDataImpl
+org.apache.ignite.internal.portable.PortableObjectEx
+org.apache.ignite.internal.portable.PortableObjectImpl
+org.apache.ignite.internal.portable.PortableObjectOffheapImpl
 org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion
 org.apache.ignite.internal.processors.affinity.GridAffinityAssignment
 org.apache.ignite.internal.processors.affinity.GridAffinityMessage
 org.apache.ignite.internal.processors.affinity.GridAffinityUtils$AffinityJob
 org.apache.ignite.internal.processors.cache.CacheAtomicUpdateTimeoutCheckedException
 org.apache.ignite.internal.processors.cache.CacheEntryImpl
+org.apache.ignite.internal.processors.cache.CacheEntryImplEx
 org.apache.ignite.internal.processors.cache.CacheEntryInfoCollection
 org.apache.ignite.internal.processors.cache.CacheEntryPredicate
 org.apache.ignite.internal.processors.cache.CacheEntryPredicateAdapter
@@ -290,47 +309,48 @@ org.apache.ignite.internal.processors.cache.CacheOperationContext
 org.apache.ignite.internal.processors.cache.CachePartialUpdateCheckedException
 org.apache.ignite.internal.processors.cache.CacheStorePartialUpdateException
 org.apache.ignite.internal.processors.cache.CacheType
-org.apache.ignite.internal.processors.cache.CacheEntryImplEx
 org.apache.ignite.internal.processors.cache.CacheWeakQueryIteratorsHolder$WeakQueryFutureIterator
 org.apache.ignite.internal.processors.cache.DynamicCacheChangeBatch
 org.apache.ignite.internal.processors.cache.DynamicCacheChangeRequest
 org.apache.ignite.internal.processors.cache.GridCacheAdapter
-org.apache.ignite.internal.processors.cache.GridCacheAdapter$10
+org.apache.ignite.internal.processors.cache.GridCacheAdapter$11
 org.apache.ignite.internal.processors.cache.GridCacheAdapter$12
 org.apache.ignite.internal.processors.cache.GridCacheAdapter$13
 org.apache.ignite.internal.processors.cache.GridCacheAdapter$14
-org.apache.ignite.internal.processors.cache.GridCacheAdapter$15
-org.apache.ignite.internal.processors.cache.GridCacheAdapter$16$1
+org.apache.ignite.internal.processors.cache.GridCacheAdapter$15$1
+org.apache.ignite.internal.processors.cache.GridCacheAdapter$16
 org.apache.ignite.internal.processors.cache.GridCacheAdapter$17
-org.apache.ignite.internal.processors.cache.GridCacheAdapter$18
 org.apache.ignite.internal.processors.cache.GridCacheAdapter$2
-org.apache.ignite.internal.processors.cache.GridCacheAdapter$26$1
-org.apache.ignite.internal.processors.cache.GridCacheAdapter$28
-org.apache.ignite.internal.processors.cache.GridCacheAdapter$29$1
+org.apache.ignite.internal.processors.cache.GridCacheAdapter$25$1
+org.apache.ignite.internal.processors.cache.GridCacheAdapter$27
+org.apache.ignite.internal.processors.cache.GridCacheAdapter$28$1
+org.apache.ignite.internal.processors.cache.GridCacheAdapter$29
 org.apache.ignite.internal.processors.cache.GridCacheAdapter$3
-org.apache.ignite.internal.processors.cache.GridCacheAdapter$30
-org.apache.ignite.internal.processors.cache.GridCacheAdapter$32
+org.apache.ignite.internal.processors.cache.GridCacheAdapter$31
 org.apache.ignite.internal.processors.cache.GridCacheAdapter$4
 org.apache.ignite.internal.processors.cache.GridCacheAdapter$6
+org.apache.ignite.internal.processors.cache.GridCacheAdapter$64
 org.apache.ignite.internal.processors.cache.GridCacheAdapter$65
 org.apache.ignite.internal.processors.cache.GridCacheAdapter$66
-org.apache.ignite.internal.processors.cache.GridCacheAdapter$67
 org.apache.ignite.internal.processors.cache.GridCacheAdapter$68
+org.apache.ignite.internal.processors.cache.GridCacheAdapter$69
+org.apache.ignite.internal.processors.cache.GridCacheAdapter$69$1
 org.apache.ignite.internal.processors.cache.GridCacheAdapter$7
 org.apache.ignite.internal.processors.cache.GridCacheAdapter$70
 org.apache.ignite.internal.processors.cache.GridCacheAdapter$71
-org.apache.ignite.internal.processors.cache.GridCacheAdapter$71$1
 org.apache.ignite.internal.processors.cache.GridCacheAdapter$72
-org.apache.ignite.internal.processors.cache.GridCacheAdapter$73
-org.apache.ignite.internal.processors.cache.GridCacheAdapter$74
 org.apache.ignite.internal.processors.cache.GridCacheAdapter$9
+org.apache.ignite.internal.processors.cache.GridCacheAdapter$AsyncOpRetryFuture$1
+org.apache.ignite.internal.processors.cache.GridCacheAdapter$AsyncOpRetryFuture$1$1
+org.apache.ignite.internal.processors.cache.GridCacheAdapter$ClearTask
 org.apache.ignite.internal.processors.cache.GridCacheAdapter$GlobalClearAllJob
-org.apache.ignite.internal.processors.cache.GridCacheAdapter$GlobalClearCallable
 org.apache.ignite.internal.processors.cache.GridCacheAdapter$GlobalClearKeySetJob
-org.apache.ignite.internal.processors.cache.GridCacheAdapter$GlobalSizeCallable
 org.apache.ignite.internal.processors.cache.GridCacheAdapter$LoadCacheClosure
 org.apache.ignite.internal.processors.cache.GridCacheAdapter$LoadKeysCallable
 org.apache.ignite.internal.processors.cache.GridCacheAdapter$SizeJob
+org.apache.ignite.internal.processors.cache.GridCacheAdapter$SizeTask
+org.apache.ignite.internal.processors.cache.GridCacheAdapter$TopologyVersionAwareJob
+org.apache.ignite.internal.processors.cache.GridCacheAdapter$TopologyVersionAwareJob$1
 org.apache.ignite.internal.processors.cache.GridCacheAdapter$UpdateGetTimeStatClosure
 org.apache.ignite.internal.processors.cache.GridCacheAdapter$UpdatePutAndGetTimeStatClosure
 org.apache.ignite.internal.processors.cache.GridCacheAdapter$UpdatePutTimeStatClosure
@@ -370,6 +390,7 @@ org.apache.ignite.internal.processors.cache.GridCacheEvictionResponse
 org.apache.ignite.internal.processors.cache.GridCacheExplicitLockSpan
 org.apache.ignite.internal.processors.cache.GridCacheExplicitLockSpan$1
 org.apache.ignite.internal.processors.cache.GridCacheFilterFailedException
+org.apache.ignite.internal.processors.cache.GridCacheGateway$State
 org.apache.ignite.internal.processors.cache.GridCacheIndexUpdateException
 org.apache.ignite.internal.processors.cache.GridCacheIoManager$1$1
 org.apache.ignite.internal.processors.cache.GridCacheIoManager$2
@@ -384,6 +405,7 @@ org.apache.ignite.internal.processors.cache.GridCacheMessage
 org.apache.ignite.internal.processors.cache.GridCacheMultiTxFuture$1
 org.apache.ignite.internal.processors.cache.GridCacheMvccCandidate
 org.apache.ignite.internal.processors.cache.GridCacheMvccCandidate$Mask
+org.apache.ignite.internal.processors.cache.GridCacheMvccManager$4
 org.apache.ignite.internal.processors.cache.GridCacheMvccManager$5
 org.apache.ignite.internal.processors.cache.GridCacheMvccManager$6
 org.apache.ignite.internal.processors.cache.GridCacheMvccManager$7
@@ -394,27 +416,37 @@ org.apache.ignite.internal.processors.cache.GridCachePartitionExchangeManager$1$
 org.apache.ignite.internal.processors.cache.GridCachePartitionExchangeManager$2
 org.apache.ignite.internal.processors.cache.GridCachePartitionExchangeManager$3
 org.apache.ignite.internal.processors.cache.GridCachePartitionExchangeManager$4
+org.apache.ignite.internal.processors.cache.GridCachePartitionExchangeManager$5
+org.apache.ignite.internal.processors.cache.GridCachePartitionExchangeManager$6
 org.apache.ignite.internal.processors.cache.GridCachePartitionExchangeManager$ExchangeFutureSet
 org.apache.ignite.internal.processors.cache.GridCachePartitionExchangeManager$MessageHandler
 org.apache.ignite.internal.processors.cache.GridCacheProcessor$2
 org.apache.ignite.internal.processors.cache.GridCacheProcessor$3
-org.apache.ignite.internal.processors.cache.GridCacheProcessor$5
+org.apache.ignite.internal.processors.cache.GridCacheProcessor$4
+org.apache.ignite.internal.processors.cache.GridCacheProcessor$6
 org.apache.ignite.internal.processors.cache.GridCacheProcessor$LocalAffinityFunction
 org.apache.ignite.internal.processors.cache.GridCacheProxyImpl
 org.apache.ignite.internal.processors.cache.GridCacheReturn
 org.apache.ignite.internal.processors.cache.GridCacheSwapManager$10
 org.apache.ignite.internal.processors.cache.GridCacheSwapManager$12
 org.apache.ignite.internal.processors.cache.GridCacheSwapManager$14
+org.apache.ignite.internal.processors.cache.GridCacheSwapManager$15
+org.apache.ignite.internal.processors.cache.GridCacheSwapManager$16
 org.apache.ignite.internal.processors.cache.GridCacheSwapManager$17
+org.apache.ignite.internal.processors.cache.GridCacheSwapManager$18
 org.apache.ignite.internal.processors.cache.GridCacheSwapManager$2
+org.apache.ignite.internal.processors.cache.GridCacheSwapManager$21
 org.apache.ignite.internal.processors.cache.GridCacheSwapManager$3
 org.apache.ignite.internal.processors.cache.GridCacheSwapManager$4
 org.apache.ignite.internal.processors.cache.GridCacheSwapManager$5
 org.apache.ignite.internal.processors.cache.GridCacheSwapManager$6
 org.apache.ignite.internal.processors.cache.GridCacheSwapManager$7
+org.apache.ignite.internal.processors.cache.GridCacheSwapManager$CloseablePartitionsIterator
 org.apache.ignite.internal.processors.cache.GridCacheSwapManager$IteratorWrapper
 org.apache.ignite.internal.processors.cache.GridCacheTryPutFailedException
+org.apache.ignite.internal.processors.cache.GridCacheTtlManager$GridConcurrentSkipListSetEx
 org.apache.ignite.internal.processors.cache.GridCacheUtilityKey
+org.apache.ignite.internal.processors.cache.GridCacheUtils$1
 org.apache.ignite.internal.processors.cache.GridCacheUtils$10
 org.apache.ignite.internal.processors.cache.GridCacheUtils$11
 org.apache.ignite.internal.processors.cache.GridCacheUtils$12
@@ -428,10 +460,8 @@ org.apache.ignite.internal.processors.cache.GridCacheUtils$19
 org.apache.ignite.internal.processors.cache.GridCacheUtils$2
 org.apache.ignite.internal.processors.cache.GridCacheUtils$20
 org.apache.ignite.internal.processors.cache.GridCacheUtils$21
-org.apache.ignite.internal.processors.cache.GridCacheUtils$22
 org.apache.ignite.internal.processors.cache.GridCacheUtils$23
-org.apache.ignite.internal.processors.cache.GridCacheUtils$25
-org.apache.ignite.internal.processors.cache.GridCacheUtils$26
+org.apache.ignite.internal.processors.cache.GridCacheUtils$24
 org.apache.ignite.internal.processors.cache.GridCacheUtils$3
 org.apache.ignite.internal.processors.cache.GridCacheUtils$4
 org.apache.ignite.internal.processors.cache.GridCacheUtils$5
@@ -445,7 +475,6 @@ org.apache.ignite.internal.processors.cache.GridLoadCacheCloseablePredicate
 org.apache.ignite.internal.processors.cache.IgniteCacheProxy
 org.apache.ignite.internal.processors.cache.IgniteCacheProxy$1
 org.apache.ignite.internal.processors.cache.IgniteCacheProxy$2
-org.apache.ignite.internal.processors.cache.IgniteCacheProxy$4
 org.apache.ignite.internal.processors.cache.IgniteCacheProxy$5
 org.apache.ignite.internal.processors.cache.IgniteCacheProxy$6
 org.apache.ignite.internal.processors.cache.IgniteCacheProxy$7
@@ -456,14 +485,16 @@ org.apache.ignite.internal.processors.cache.datastructures.CacheDataStructuresMa
 org.apache.ignite.internal.processors.cache.datastructures.CacheDataStructuresManager$QueueHeaderPredicate
 org.apache.ignite.internal.processors.cache.datastructures.CacheDataStructuresManager$RemoveSetDataCallable
 org.apache.ignite.internal.processors.cache.distributed.GridCacheCommittedTxInfo
+org.apache.ignite.internal.processors.cache.distributed.GridCacheTtlUpdateRequest
 org.apache.ignite.internal.processors.cache.distributed.GridCacheTxRecoveryFuture$1
+org.apache.ignite.internal.processors.cache.distributed.GridCacheTxRecoveryFuture$2
 org.apache.ignite.internal.processors.cache.distributed.GridCacheTxRecoveryRequest
 org.apache.ignite.internal.processors.cache.distributed.GridCacheTxRecoveryResponse
-org.apache.ignite.internal.processors.cache.distributed.GridCacheTtlUpdateRequest
 org.apache.ignite.internal.processors.cache.distributed.GridDistributedBaseMessage
 org.apache.ignite.internal.processors.cache.distributed.GridDistributedCacheAdapter
 org.apache.ignite.internal.processors.cache.distributed.GridDistributedCacheAdapter$1
-org.apache.ignite.internal.processors.cache.distributed.GridDistributedCacheAdapter$GlobalRemoveAllCallable
+org.apache.ignite.internal.processors.cache.distributed.GridDistributedCacheAdapter$GlobalRemoveAllJob
+org.apache.ignite.internal.processors.cache.distributed.GridDistributedCacheAdapter$RemoveAllTask
 org.apache.ignite.internal.processors.cache.distributed.GridDistributedLockCancelledException
 org.apache.ignite.internal.processors.cache.distributed.GridDistributedLockRequest
 org.apache.ignite.internal.processors.cache.distributed.GridDistributedLockResponse
@@ -496,6 +527,7 @@ org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtLockFuture$3
 org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtLockRequest
 org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtLockResponse
 org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtPartitionState
+org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtPartitionsReservation$1
 org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtTransactionalCacheAdapter
 org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtTransactionalCacheAdapter$1
 org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtTransactionalCacheAdapter$2
@@ -510,6 +542,7 @@ org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtTransactional
 org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtTransactionalCacheAdapter$9$1$1
 org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtTransactionalCacheAdapter$9$2
 org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtTxFinishFuture$1
+org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtTxFinishFuture$2
 org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtTxFinishRequest
 org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtTxFinishResponse
 org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtTxLocal
@@ -517,6 +550,7 @@ org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtTxLocal$1
 org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtTxLocal$2
 org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtTxLocalAdapter
 org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtTxLocalAdapter$1
+org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtTxLocalAdapter$2
 org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtTxPrepareFuture$1
 org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtTxPrepareFuture$2
 org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtTxPrepareFuture$3
@@ -524,6 +558,7 @@ org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtTxPrepareRequ
 org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtTxPrepareResponse
 org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtTxRemote
 org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtUnlockRequest
+org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtUnreservedPartitionException
 org.apache.ignite.internal.processors.cache.distributed.dht.GridPartitionedGetFuture$1
 org.apache.ignite.internal.processors.cache.distributed.dht.GridPartitionedGetFuture$2
 org.apache.ignite.internal.processors.cache.distributed.dht.GridPartitionedGetFuture$MiniFuture$1
@@ -556,6 +591,7 @@ org.apache.ignite.internal.processors.cache.distributed.dht.atomic.GridDhtAtomic
 org.apache.ignite.internal.processors.cache.distributed.dht.atomic.GridNearAtomicUpdateFuture$1
 org.apache.ignite.internal.processors.cache.distributed.dht.atomic.GridNearAtomicUpdateFuture$2
 org.apache.ignite.internal.processors.cache.distributed.dht.atomic.GridNearAtomicUpdateFuture$3
+org.apache.ignite.internal.processors.cache.distributed.dht.atomic.GridNearAtomicUpdateFuture$4
 org.apache.ignite.internal.processors.cache.distributed.dht.atomic.GridNearAtomicUpdateRequest
 org.apache.ignite.internal.processors.cache.distributed.dht.atomic.GridNearAtomicUpdateResponse
 org.apache.ignite.internal.processors.cache.distributed.dht.colocated.GridDhtColocatedCache
@@ -568,6 +604,7 @@ org.apache.ignite.internal.processors.cache.distributed.dht.colocated.GridDhtCol
 org.apache.ignite.internal.processors.cache.distributed.dht.colocated.GridDhtColocatedLockFuture$2
 org.apache.ignite.internal.processors.cache.distributed.dht.colocated.GridDhtColocatedLockFuture$3
 org.apache.ignite.internal.processors.cache.distributed.dht.colocated.GridDhtColocatedLockFuture$4
+org.apache.ignite.internal.processors.cache.distributed.dht.colocated.GridDhtColocatedLockFuture$MiniFuture$1
 org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtForceKeysRequest
 org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtForceKeysResponse
 org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtPartitionDemandMessage
@@ -584,8 +621,8 @@ org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtPar
 org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtPartitionsAbstractMessage
 org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtPartitionsExchangeFuture$1
 org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtPartitionsExchangeFuture$2
-org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtPartitionsExchangeFuture$3
 org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtPartitionsExchangeFuture$4
+org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtPartitionsExchangeFuture$5
 org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtPartitionsFullMessage
 org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtPartitionsSingleMessage
 org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtPartitionsSingleRequest
@@ -622,12 +659,22 @@ org.apache.ignite.internal.processors.cache.distributed.near.GridNearLockFuture$
 org.apache.ignite.internal.processors.cache.distributed.near.GridNearLockFuture$2
 org.apache.ignite.internal.processors.cache.distributed.near.GridNearLockFuture$3
 org.apache.ignite.internal.processors.cache.distributed.near.GridNearLockFuture$4
+org.apache.ignite.internal.processors.cache.distributed.near.GridNearLockFuture$MiniFuture$1
 org.apache.ignite.internal.processors.cache.distributed.near.GridNearLockRequest
 org.apache.ignite.internal.processors.cache.distributed.near.GridNearLockResponse
+org.apache.ignite.internal.processors.cache.distributed.near.GridNearOptimisticTxPrepareFuture$1
+org.apache.ignite.internal.processors.cache.distributed.near.GridNearOptimisticTxPrepareFuture$2
+org.apache.ignite.internal.processors.cache.distributed.near.GridNearOptimisticTxPrepareFuture$3
+org.apache.ignite.internal.processors.cache.distributed.near.GridNearOptimisticTxPrepareFuture$4
+org.apache.ignite.internal.processors.cache.distributed.near.GridNearOptimisticTxPrepareFuture$MiniFuture$1
+org.apache.ignite.internal.processors.cache.distributed.near.GridNearPessimisticTxPrepareFuture$1
+org.apache.ignite.internal.processors.cache.distributed.near.GridNearPessimisticTxPrepareFuture$2
+org.apache.ignite.internal.processors.cache.distributed.near.GridNearPessimisticTxPrepareFuture$3
 org.apache.ignite.internal.processors.cache.distributed.near.GridNearTransactionalCache
 org.apache.ignite.internal.processors.cache.distributed.near.GridNearTransactionalCache$1
 org.apache.ignite.internal.processors.cache.distributed.near.GridNearTransactionalCache$2
 org.apache.ignite.internal.processors.cache.distributed.near.GridNearTxFinishFuture$1
+org.apache.ignite.internal.processors.cache.distributed.near.GridNearTxFinishFuture$2
 org.apache.ignite.internal.processors.cache.distributed.near.GridNearTxFinishRequest
 org.apache.ignite.internal.processors.cache.distributed.near.GridNearTxFinishResponse
 org.apache.ignite.internal.processors.cache.distributed.near.GridNearTxLocal
@@ -638,11 +685,7 @@ org.apache.ignite.internal.processors.cache.distributed.near.GridNearTxLocal$4
 org.apache.ignite.internal.processors.cache.distributed.near.GridNearTxLocal$5
 org.apache.ignite.internal.processors.cache.distributed.near.GridNearTxLocal$6
 org.apache.ignite.internal.processors.cache.distributed.near.GridNearTxLocal$7
-org.apache.ignite.internal.processors.cache.distributed.near.GridNearTxPrepareFuture$1
-org.apache.ignite.internal.processors.cache.distributed.near.GridNearTxPrepareFuture$2
-org.apache.ignite.internal.processors.cache.distributed.near.GridNearTxPrepareFuture$3
-org.apache.ignite.internal.processors.cache.distributed.near.GridNearTxPrepareFuture$4
-org.apache.ignite.internal.processors.cache.distributed.near.GridNearTxPrepareFuture$5
+org.apache.ignite.internal.processors.cache.distributed.near.GridNearTxPrepareFutureAdapter$1
 org.apache.ignite.internal.processors.cache.distributed.near.GridNearTxPrepareRequest
 org.apache.ignite.internal.processors.cache.distributed.near.GridNearTxPrepareResponse
 org.apache.ignite.internal.processors.cache.distributed.near.GridNearTxRemote
@@ -656,6 +699,13 @@ org.apache.ignite.internal.processors.cache.local.atomic.GridLocalAtomicCache$4
 org.apache.ignite.internal.processors.cache.local.atomic.GridLocalAtomicCache$5
 org.apache.ignite.internal.processors.cache.local.atomic.GridLocalAtomicCache$6
 org.apache.ignite.internal.processors.cache.local.atomic.GridLocalAtomicCache$9
+org.apache.ignite.internal.processors.cache.portable.CacheDefaultPortableAffinityKeyMapper
+org.apache.ignite.internal.processors.cache.portable.CacheObjectPortableProcessorImpl$1
+org.apache.ignite.internal.processors.cache.portable.CacheObjectPortableProcessorImpl$4
+org.apache.ignite.internal.processors.cache.portable.CacheObjectPortableProcessorImpl$MetaDataEntryFilter
+org.apache.ignite.internal.processors.cache.portable.CacheObjectPortableProcessorImpl$MetaDataPredicate
+org.apache.ignite.internal.processors.cache.portable.CacheObjectPortableProcessorImpl$MetaDataProcessor
+org.apache.ignite.internal.processors.cache.portable.PortableMetaDataKey
 org.apache.ignite.internal.processors.cache.query.CacheQueryCloseableScanBiPredicate
 org.apache.ignite.internal.processors.cache.query.CacheQueryType
 org.apache.ignite.internal.processors.cache.query.GridCacheDistributedQueryFuture$1
@@ -666,13 +716,15 @@ org.apache.ignite.internal.processors.cache.query.GridCacheDistributedQueryManag
 org.apache.ignite.internal.processors.cache.query.GridCacheDistributedQueryManager$5
 org.apache.ignite.internal.processors.cache.query.GridCacheDistributedQueryManager$6
 org.apache.ignite.internal.processors.cache.query.GridCacheQueryAdapter$1
+org.apache.ignite.internal.processors.cache.query.GridCacheQueryAdapter$2
+org.apache.ignite.internal.processors.cache.query.GridCacheQueryAdapter$CacheQueryFallbackFuture$1
+org.apache.ignite.internal.processors.cache.query.GridCacheQueryAdapter$CacheQueryFallbackFuture$1$1
 org.apache.ignite.internal.processors.cache.query.GridCacheQueryFutureAdapter$1
 org.apache.ignite.internal.processors.cache.query.GridCacheQueryFutureAdapter$2
 org.apache.ignite.internal.processors.cache.query.GridCacheQueryManager$1$1
 org.apache.ignite.internal.processors.cache.query.GridCacheQueryManager$1$2
 org.apache.ignite.internal.processors.cache.query.GridCacheQueryManager$10
 org.apache.ignite.internal.processors.cache.query.GridCacheQueryManager$11$1
-org.apache.ignite.internal.processors.cache.query.GridCacheQueryManager$12$1
 org.apache.ignite.internal.processors.cache.query.GridCacheQueryManager$2
 org.apache.ignite.internal.processors.cache.query.GridCacheQueryManager$3
 org.apache.ignite.internal.processors.cache.query.GridCacheQueryManager$4
@@ -699,7 +751,6 @@ org.apache.ignite.internal.processors.cache.query.GridCacheQueryType
 org.apache.ignite.internal.processors.cache.query.GridCacheSqlIndexMetadata
 org.apache.ignite.internal.processors.cache.query.GridCacheSqlMetadata
 org.apache.ignite.internal.processors.cache.query.GridCacheSqlQuery
-org.apache.ignite.internal.processors.cache.query.GridCacheTwoStepQuery
 org.apache.ignite.internal.processors.cache.query.continuous.CacheContinuousQueryEntry
 org.apache.ignite.internal.processors.cache.query.continuous.CacheContinuousQueryEvent
 org.apache.ignite.internal.processors.cache.query.continuous.CacheContinuousQueryFilterEx
@@ -769,6 +820,7 @@ org.apache.ignite.internal.processors.cache.transactions.IgniteTxLocalAdapter$Po
 org.apache.ignite.internal.processors.cache.transactions.IgniteTxLocalAdapter$PostMissClosure
 org.apache.ignite.internal.processors.cache.transactions.IgniteTxManager$2
 org.apache.ignite.internal.processors.cache.transactions.IgniteTxManager$3
+org.apache.ignite.internal.processors.cache.transactions.IgniteTxManager$4
 org.apache.ignite.internal.processors.cache.transactions.IgniteTxManager$AtomicInt
 org.apache.ignite.internal.processors.cache.transactions.IgniteTxManager$CommitListener
 org.apache.ignite.internal.processors.cache.transactions.IgniteTxManager$CommittedVersion
@@ -809,13 +861,19 @@ org.apache.ignite.internal.processors.closure.GridClosureProcessor$T8
 org.apache.ignite.internal.processors.closure.GridClosureProcessor$T9
 org.apache.ignite.internal.processors.closure.GridClosureProcessor$TaskNoReduceAdapter
 org.apache.ignite.internal.processors.closure.GridPeerDeployAwareTaskAdapter
+org.apache.ignite.internal.processors.continuous.AbstractContinuousMessage
 org.apache.ignite.internal.processors.continuous.GridContinuousHandler
 org.apache.ignite.internal.processors.continuous.GridContinuousHandler$RegisterStatus
 org.apache.ignite.internal.processors.continuous.GridContinuousMessage
 org.apache.ignite.internal.processors.continuous.GridContinuousMessageType
 org.apache.ignite.internal.processors.continuous.GridContinuousProcessor$DiscoveryData
 org.apache.ignite.internal.processors.continuous.GridContinuousProcessor$DiscoveryDataItem
-org.apache.ignite.internal.processors.continuous.GridContinuousProcessor$StartRequestData
+org.apache.ignite.internal.processors.continuous.GridContinuousProcessor$LocalRoutineInfo
+org.apache.ignite.internal.processors.continuous.StartRequestData
+org.apache.ignite.internal.processors.continuous.StartRoutineAckDiscoveryMessage
+org.apache.ignite.internal.processors.continuous.StartRoutineDiscoveryMessage
+org.apache.ignite.internal.processors.continuous.StopRoutineAckDiscoveryMessage
+org.apache.ignite.internal.processors.continuous.StopRoutineDiscoveryMessage
 org.apache.ignite.internal.processors.datastreamer.DataStreamProcessor$3
 org.apache.ignite.internal.processors.datastreamer.DataStreamProcessor$4
 org.apache.ignite.internal.processors.datastreamer.DataStreamerCacheUpdaters$Batched
@@ -825,6 +883,7 @@ org.apache.ignite.internal.processors.datastreamer.DataStreamerEntry
 org.apache.ignite.internal.processors.datastreamer.DataStreamerImpl$1
 org.apache.ignite.internal.processors.datastreamer.DataStreamerImpl$4
 org.apache.ignite.internal.processors.datastreamer.DataStreamerImpl$5
+org.apache.ignite.internal.processors.datastreamer.DataStreamerImpl$6
 org.apache.ignite.internal.processors.datastreamer.DataStreamerImpl$Buffer$1
 org.apache.ignite.internal.processors.datastreamer.DataStreamerImpl$Buffer$2
 org.apache.ignite.internal.processors.datastreamer.DataStreamerImpl$DataStreamerPda
@@ -838,13 +897,13 @@ org.apache.ignite.internal.processors.datastructures.DataStructuresProcessor$1
 org.apache.ignite.internal.processors.datastructures.DataStructuresProcessor$10
 org.apache.ignite.internal.processors.datastructures.DataStructuresProcessor$11
 org.apache.ignite.internal.processors.datastructures.DataStructuresProcessor$12
-org.apache.ignite.internal.processors.datastructures.DataStructuresProcessor$14
+org.apache.ignite.internal.processors.datastructures.DataStructuresProcessor$13
 org.apache.ignite.internal.processors.datastructures.DataStructuresProcessor$15
+org.apache.ignite.internal.processors.datastructures.DataStructuresProcessor$16
 org.apache.ignite.internal.processors.datastructures.DataStructuresProcessor$17
-org.apache.ignite.internal.processors.datastructures.DataStructuresProcessor$18
-org.apache.ignite.internal.processors.datastructures.DataStructuresProcessor$19
 org.apache.ignite.internal.processors.datastructures.DataStructuresProcessor$2
 org.apache.ignite.internal.processors.datastructures.DataStructuresProcessor$3
+org.apache.ignite.internal.processors.datastructures.DataStructuresProcessor$4
 org.apache.ignite.internal.processors.datastructures.DataStructuresProcessor$5
 org.apache.ignite.internal.processors.datastructures.DataStructuresProcessor$6
 org.apache.ignite.internal.processors.datastructures.DataStructuresProcessor$7
@@ -857,6 +916,8 @@ org.apache.ignite.internal.processors.datastructures.DataStructuresProcessor$Cac
 org.apache.ignite.internal.processors.datastructures.DataStructuresProcessor$CollectionInfo
 org.apache.ignite.internal.processors.datastructures.DataStructuresProcessor$DataStructureInfo
 org.apache.ignite.internal.processors.datastructures.DataStructuresProcessor$DataStructureType
+org.apache.ignite.internal.processors.datastructures.DataStructuresProcessor$DataStructuresEntryFilter
+org.apache.ignite.internal.processors.datastructures.DataStructuresProcessor$DataStructuresEntryListener$2
 org.apache.ignite.internal.processors.datastructures.DataStructuresProcessor$QueueInfo
 org.apache.ignite.internal.processors.datastructures.DataStructuresProcessor$RemoveDataStructureProcessor
 org.apache.ignite.internal.processors.datastructures.GridCacheAtomicLongImpl
@@ -930,6 +991,7 @@ org.apache.ignite.internal.processors.igfs.IgfsImpl$IgfsGlobalSpaceTask$1
 org.apache.ignite.internal.processors.igfs.IgfsInputStreamDescriptor
 org.apache.ignite.internal.processors.igfs.IgfsInputStreamImpl$1
 org.apache.ignite.internal.processors.igfs.IgfsInvalidRangeException
+org.apache.ignite.internal.processors.igfs.IgfsIpcHandler$2
 org.apache.ignite.internal.processors.igfs.IgfsJobImpl
 org.apache.ignite.internal.processors.igfs.IgfsListingEntry
 org.apache.ignite.internal.processors.igfs.IgfsMetaManager$1
@@ -956,6 +1018,14 @@ org.apache.ignite.internal.processors.job.GridJobWorker$3
 org.apache.ignite.internal.processors.jobmetrics.GridJobMetricsProcessor$SnapshotReducer
 org.apache.ignite.internal.processors.query.GridQueryFieldMetadata
 org.apache.ignite.internal.processors.query.GridQueryIndexType
+org.apache.ignite.internal.processors.query.GridQueryProcessor$2
+org.apache.ignite.internal.processors.query.GridQueryProcessor$3
+org.apache.ignite.internal.processors.query.GridQueryProcessor$4
+org.apache.ignite.internal.processors.query.GridQueryProcessor$5
+org.apache.ignite.internal.processors.query.GridQueryProcessor$6
+org.apache.ignite.internal.processors.query.GridQueryProcessor$7
+org.apache.ignite.internal.processors.query.GridQueryProcessor$8
+org.apache.ignite.internal.processors.query.GridQueryProcessor$9
 org.apache.ignite.internal.processors.query.h2.twostep.messages.GridQueryCancelRequest
 org.apache.ignite.internal.processors.query.h2.twostep.messages.GridQueryFailResponse
 org.apache.ignite.internal.processors.query.h2.twostep.messages.GridQueryNextPageRequest
@@ -981,26 +1051,40 @@ org.apache.ignite.internal.processors.rest.client.message.GridClientTaskResultBe
 org.apache.ignite.internal.processors.rest.client.message.GridClientTopologyRequest
 org.apache.ignite.internal.processors.rest.client.message.GridRouterRequest
 org.apache.ignite.internal.processors.rest.client.message.GridRouterResponse
+org.apache.ignite.internal.processors.rest.handlers.cache.GridCacheCommandHandler$1
 org.apache.ignite.internal.processors.rest.handlers.cache.GridCacheCommandHandler$2
+org.apache.ignite.internal.processors.rest.handlers.cache.GridCacheCommandHandler$4
 org.apache.ignite.internal.processors.rest.handlers.cache.GridCacheCommandHandler$AddCommand
 org.apache.ignite.internal.processors.rest.handlers.cache.GridCacheCommandHandler$AppendCommand
 org.apache.ignite.internal.processors.rest.handlers.cache.GridCacheCommandHandler$CacheCommand
 org.apache.ignite.internal.processors.rest.handlers.cache.GridCacheCommandHandler$CacheOperationCallable
 org.apache.ignite.internal.processors.rest.handlers.cache.GridCacheCommandHandler$CacheProjectionCommand
 org.apache.ignite.internal.processors.rest.handlers.cache.GridCacheCommandHandler$CasCommand
+org.apache.ignite.internal.processors.rest.handlers.cache.GridCacheCommandHandler$ContainsKeyCommand
+org.apache.ignite.internal.processors.rest.handlers.cache.GridCacheCommandHandler$ContainsKeysCommand
 org.apache.ignite.internal.processors.rest.handlers.cache.GridCacheCommandHandler$FixedResult
 org.apache.ignite.internal.processors.rest.handlers.cache.GridCacheCommandHandler$FlaggedCacheOperationCallable
 org.apache.ignite.internal.processors.rest.handlers.cache.GridCacheCommandHandler$GetAllCommand
+org.apache.ignite.internal.processors.rest.handlers.cache.GridCacheCommandHandler$GetAndPutCommand
+org.apache.ignite.internal.processors.rest.handlers.cache.GridCacheCommandHandler$GetAndPutIfAbsentCommand
+org.apache.ignite.internal.processors.rest.handlers.cache.GridCacheCommandHandler$GetAndRemoveCommand
+org.apache.ignite.internal.processors.rest.handlers.cache.GridCacheCommandHandler$GetAndReplaceCommand
 org.apache.ignite.internal.processors.rest.handlers.cache.GridCacheCommandHandler$GetCommand
 org.apache.ignite.internal.processors.rest.handlers.cache.GridCacheCommandHandler$MetricsCommand
 org.apache.ignite.internal.processors.rest.handlers.cache.GridCacheCommandHandler$PrependCommand
 org.apache.ignite.internal.processors.rest.handlers.cache.GridCacheCommandHandler$PutAllCommand
 org.apache.ignite.internal.processors.rest.handlers.cache.GridCacheCommandHandler$PutCommand
+org.apache.ignite.internal.processors.rest.handlers.cache.GridCacheCommandHandler$PutIfAbsentCommand
 org.apache.ignite.internal.processors.rest.handlers.cache.GridCacheCommandHandler$RemoveAllCommand
 org.apache.ignite.internal.processors.rest.handlers.cache.GridCacheCommandHandler$RemoveCommand
+org.apache.ignite.internal.processors.rest.handlers.cache.GridCacheCommandHandler$RemoveValueCommand
 org.apache.ignite.internal.processors.rest.handlers.cache.GridCacheCommandHandler$ReplaceCommand
+org.apache.ignite.internal.processors.rest.handlers.cache.GridCacheCommandHandler$ReplaceValueCommand
+org.apache.ignite.internal.processors.rest.handlers.cache.GridCacheCommandHandler$SizeCommand
 org.apache.ignite.internal.processors.rest.handlers.cache.GridCacheRestResponse
 org.apache.ignite.internal.processors.rest.handlers.datastructures.DataStructuresCommandHandler$1
+org.apache.ignite.internal.processors.rest.handlers.query.CacheQueryFieldsMetaResult
+org.apache.ignite.internal.processors.rest.handlers.query.CacheQueryResult
 org.apache.ignite.internal.processors.rest.handlers.task.GridTaskCommandHandler$2
 org.apache.ignite.internal.processors.rest.handlers.task.GridTaskCommandHandler$ExeCallable
 org.apache.ignite.internal.processors.rest.handlers.task.GridTaskResultRequest
@@ -1017,6 +1101,8 @@ org.apache.ignite.internal.processors.service.GridServiceDeployment
 org.apache.ignite.internal.processors.service.GridServiceDeploymentKey
 org.apache.ignite.internal.processors.service.GridServiceMethodNotFoundException
 org.apache.ignite.internal.processors.service.GridServiceNotFoundException
+org.apache.ignite.internal.processors.service.GridServiceProcessor$ServiceAssignmentsPredicate
+org.apache.ignite.internal.processors.service.GridServiceProcessor$ServiceDeploymentPredicate
 org.apache.ignite.internal.processors.service.GridServiceProxy
 org.apache.ignite.internal.processors.service.GridServiceProxy$ServiceProxyCallable
 org.apache.ignite.internal.processors.service.ServiceContextImpl
@@ -1097,13 +1183,14 @@ org.apache.ignite.internal.util.IgniteUtils$11
 org.apache.ignite.internal.util.IgniteUtils$12
 org.apache.ignite.internal.util.IgniteUtils$13
 org.apache.ignite.internal.util.IgniteUtils$14
+org.apache.ignite.internal.util.IgniteUtils$16
 org.apache.ignite.internal.util.IgniteUtils$2
-org.apache.ignite.internal.util.IgniteUtils$20
-org.apache.ignite.internal.util.IgniteUtils$21
 org.apache.ignite.internal.util.IgniteUtils$22
 org.apache.ignite.internal.util.IgniteUtils$23
 org.apache.ignite.internal.util.IgniteUtils$24
 org.apache.ignite.internal.util.IgniteUtils$25
+org.apache.ignite.internal.util.IgniteUtils$26
+org.apache.ignite.internal.util.IgniteUtils$27
 org.apache.ignite.internal.util.IgniteUtils$3
 org.apache.ignite.internal.util.IgniteUtils$4
 org.apache.ignite.internal.util.IgniteUtils$5
@@ -1143,48 +1230,10 @@ org.apache.ignite.internal.util.lang.GridCloseableIterator
 org.apache.ignite.internal.util.lang.GridClosureException
 org.apache.ignite.internal.util.lang.GridFunc$1
 org.apache.ignite.internal.util.lang.GridFunc$10
-org.apache.ignite.internal.util.lang.GridFunc$100
-org.apache.ignite.internal.util.lang.GridFunc$101
-org.apache.ignite.internal.util.lang.GridFunc$102
-org.apache.ignite.internal.util.lang.GridFunc$103
-org.apache.ignite.internal.util.lang.GridFunc$104
-org.apache.ignite.internal.util.lang.GridFunc$105
-org.apache.ignite.internal.util.lang.GridFunc$106
-org.apache.ignite.internal.util.lang.GridFunc$107
-org.apache.ignite.internal.util.lang.GridFunc$108
-org.apache.ignite.internal.util.lang.GridFunc$109
 org.apache.ignite.internal.util.lang.GridFunc$11
-org.apache.ignite.internal.util.lang.GridFunc$110
-org.apache.ignite.internal.util.lang.GridFunc$111
-org.apache.ignite.internal.util.lang.GridFunc$112
-org.apache.ignite.internal.util.lang.GridFunc$113
-org.apache.ignite.internal.util.lang.GridFunc$114
-org.apache.ignite.internal.util.lang.GridFunc$115
-org.apache.ignite.internal.util.lang.GridFunc$117
-org.apache.ignite.internal.util.lang.GridFunc$118
 org.apache.ignite.internal.util.lang.GridFunc$12
-org.apache.ignite.internal.util.lang.GridFunc$120
-org.apache.ignite.internal.util.lang.GridFunc$121
-org.apache.ignite.internal.util.lang.GridFunc$123
-org.apache.ignite.internal.util.lang.GridFunc$124
-org.apache.ignite.internal.util.lang.GridFunc$125
-org.apache.ignite.internal.util.lang.GridFunc$127
-org.apache.ignite.internal.util.lang.GridFunc$128
-org.apache.ignite.internal.util.lang.GridFunc$129
 org.apache.ignite.internal.util.lang.GridFunc$13
-org.apache.ignite.internal.util.lang.GridFunc$130
-org.apache.ignite.internal.util.lang.GridFunc$131
-org.apache.ignite.internal.util.lang.GridFunc$132
-org.apache.ignite.internal.util.lang.GridFunc$134
-org.apache.ignite.internal.util.lang.GridFunc$135
-org.apache.ignite.internal.util.lang.GridFunc$136
-org.apache.ignite.internal.util.lang.GridFunc$137
-org.apache.ignite.internal.util.lang.GridFunc$138
-org.apache.ignite.internal.util.lang.GridFunc$139
 org.apache.ignite.internal.util.lang.GridFunc$14
-org.apache.ignite.internal.util.lang.GridFunc$140
-org.apache.ignite.internal.util.lang.GridFunc$141
-org.apache.ignite.internal.util.lang.GridFunc$142
 org.apache.ignite.internal.util.lang.GridFunc$15
 org.apache.ignite.internal.util.lang.GridFunc$16
 org.apache.ignite.internal.util.lang.GridFunc$17
@@ -1205,8 +1254,9 @@ org.apache.ignite.internal.util.lang.GridFunc$3
 org.apache.ignite.internal.util.lang.GridFunc$30
 org.apache.ignite.internal.util.lang.GridFunc$31
 org.apache.ignite.internal.util.lang.GridFunc$32
+org.apache.ignite.internal.util.lang.GridFunc$32$1
 org.apache.ignite.internal.util.lang.GridFunc$33
-org.apache.ignite.internal.util.lang.GridFunc$34
+org.apache.ignite.internal.util.lang.GridFunc$33$1
 org.apache.ignite.internal.util.lang.GridFunc$35
 org.apache.ignite.internal.util.lang.GridFunc$36
 org.apache.ignite.internal.util.lang.GridFunc$37
@@ -1223,10 +1273,18 @@ org.apache.ignite.internal.util.lang.GridFunc$46
 org.apache.ignite.internal.util.lang.GridFunc$47
 org.apache.ignite.internal.util.lang.GridFunc$48
 org.apache.ignite.internal.util.lang.GridFunc$49
+org.apache.ignite.internal.util.lang.GridFunc$49$1
+org.apache.ignite.internal.util.lang.GridFunc$49$2
 org.apache.ignite.internal.util.lang.GridFunc$5
 org.apache.ignite.internal.util.lang.GridFunc$50
+org.apache.ignite.internal.util.lang.GridFunc$50$1
+org.apache.ignite.internal.util.lang.GridFunc$50$2
 org.apache.ignite.internal.util.lang.GridFunc$51
+org.apache.ignite.internal.util.lang.GridFunc$51$1
+org.apache.ignite.internal.util.lang.GridFunc$51$2
 org.apache.ignite.internal.util.lang.GridFunc$52
+org.apache.ignite.internal.util.lang.GridFunc$52$1
+org.apache.ignite.internal.util.lang.GridFunc$52$2
 org.apache.ignite.internal.util.lang.GridFunc$53
 org.apache.ignite.internal.util.lang.GridFunc$54
 org.apache.ignite.internal.util.lang.GridFunc$55
@@ -1239,57 +1297,16 @@ org.apache.ignite.internal.util.lang.GridFunc$60
 org.apache.ignite.internal.util.lang.GridFunc$61
 org.apache.ignite.internal.util.lang.GridFunc$62
 org.apache.ignite.internal.util.lang.GridFunc$63
-org.apache.ignite.internal.util.lang.GridFunc$64
-org.apache.ignite.internal.util.lang.GridFunc$65
-org.apache.ignite.internal.util.lang.GridFunc$66
-org.apache.ignite.internal.util.lang.GridFunc$66$1
-org.apache.ignite.internal.util.lang.GridFunc$67
-org.apache.ignite.internal.util.lang.GridFunc$67$1
-org.apache.ignite.internal.util.lang.GridFunc$69
 org.apache.ignite.internal.util.lang.GridFunc$7
-org.apache.ignite.internal.util.lang.GridFunc$70
-org.apache.ignite.internal.util.lang.GridFunc$71
-org.apache.ignite.internal.util.lang.GridFunc$72
-org.apache.ignite.internal.util.lang.GridFunc$73
-org.apache.ignite.internal.util.lang.GridFunc$74
-org.apache.ignite.internal.util.lang.GridFunc$75
-org.apache.ignite.internal.util.lang.GridFunc$76
-org.apache.ignite.internal.util.lang.GridFunc$77
-org.apache.ignite.internal.util.lang.GridFunc$78
-org.apache.ignite.internal.util.lang.GridFunc$79
 org.apache.ignite.internal.util.lang.GridFunc$8
-org.apache.ignite.internal.util.lang.GridFunc$80
-org.apache.ignite.internal.util.lang.GridFunc$82
-org.apache.ignite.internal.util.lang.GridFunc$83
-org.apache.ignite.internal.util.lang.GridFunc$84
-org.apache.ignite.internal.util.lang.GridFunc$85
-org.apache.ignite.internal.util.lang.GridFunc$86
-org.apache.ignite.internal.util.lang.GridFunc$87
 org.apache.ignite.internal.util.lang.GridFunc$9
-org.apache.ignite.internal.util.lang.GridFunc$90
-org.apache.ignite.internal.util.lang.GridFunc$91
-org.apache.ignite.internal.util.lang.GridFunc$92
-org.apache.ignite.internal.util.lang.GridFunc$93
-org.apache.ignite.internal.util.lang.GridFunc$94
-org.apache.ignite.internal.util.lang.GridFunc$95
-org.apache.ignite.internal.util.lang.GridFunc$96
-org.apache.ignite.internal.util.lang.GridFunc$96$1
-org.apache.ignite.internal.util.lang.GridFunc$96$2
-org.apache.ignite.internal.util.lang.GridFunc$97
-org.apache.ignite.internal.util.lang.GridFunc$97$1
-org.apache.ignite.internal.util.lang.GridFunc$97$2
-org.apache.ignite.internal.util.lang.GridFunc$98
-org.apache.ignite.internal.util.lang.GridFunc$98$1
-org.apache.ignite.internal.util.lang.GridFunc$98$2
-org.apache.ignite.internal.util.lang.GridFunc$99
-org.apache.ignite.internal.util.lang.GridFunc$99$1
-org.apache.ignite.internal.util.lang.GridFunc$99$2
 org.apache.ignite.internal.util.lang.GridIterable
 org.apache.ignite.internal.util.lang.GridIterableAdapter
 org.apache.ignite.internal.util.lang.GridIterableAdapter$IteratorWrapper
 org.apache.ignite.internal.util.lang.GridIterator
 org.apache.ignite.internal.util.lang.GridIteratorAdapter
 org.apache.ignite.internal.util.lang.GridMapEntry
+org.apache.ignite.internal.util.lang.GridMetadataAwareAdapter$EntryKey
 org.apache.ignite.internal.util.lang.GridNodePredicate
 org.apache.ignite.internal.util.lang.GridPeerDeployAware
 org.apache.ignite.internal.util.lang.GridPeerDeployAwareAdapter
@@ -1327,6 +1344,7 @@ org.apache.ignite.internal.util.offheap.unsafe.GridUnsafeMap$Segment$1
 org.apache.ignite.internal.util.offheap.unsafe.GridUnsafeMap$Segment$2
 org.apache.ignite.internal.util.offheap.unsafe.GridUnsafePartitionedMap$2
 org.apache.ignite.internal.util.offheap.unsafe.GridUnsafePartitionedMap$3
+org.apache.ignite.internal.util.offheap.unsafe.GridUnsafePartitionedMap$PartitionedMapCloseableIterator
 org.apache.ignite.internal.util.snaptree.CopyOnWriteManager$COWEpoch
 org.apache.ignite.internal.util.snaptree.Epoch$Root
 org.apache.ignite.internal.util.snaptree.EpochNode
@@ -1504,7 +1522,9 @@ org.apache.ignite.internal.visor.query.VisorQueryNextPageTask$VisorQueryNextPage
 org.apache.ignite.internal.visor.query.VisorQueryResult
 org.apache.ignite.internal.visor.query.VisorQueryResultEx
 org.apache.ignite.internal.visor.query.VisorQueryTask
+org.apache.ignite.internal.visor.util.VisorClusterGroupEmptyException
 org.apache.ignite.internal.visor.util.VisorEventMapper
+org.apache.ignite.internal.visor.util.VisorExceptionWrapper
 org.apache.ignite.internal.visor.util.VisorTaskUtils$4
 org.apache.ignite.lang.IgniteBiClosure
 org.apache.ignite.lang.IgniteBiInClosure
@@ -1538,6 +1558,10 @@ org.apache.ignite.plugin.security.SecuritySubject
 org.apache.ignite.plugin.security.SecuritySubjectType
 org.apache.ignite.plugin.segmentation.SegmentationPolicy
 org.apache.ignite.plugin.segmentation.SegmentationResolver
+org.apache.ignite.portable.PortableException
+org.apache.ignite.portable.PortableInvalidClassException
+org.apache.ignite.portable.PortableObject
+org.apache.ignite.portable.PortableProtocolVersion
 org.apache.ignite.services.Service
 org.apache.ignite.services.ServiceConfiguration
 org.apache.ignite.services.ServiceContext
@@ -1546,6 +1570,7 @@ org.apache.ignite.spi.IgnitePortProtocol
 org.apache.ignite.spi.IgniteSpiCloseableIterator
 org.apache.ignite.spi.IgniteSpiException
 org.apache.ignite.spi.IgniteSpiMultiException
+org.apache.ignite.spi.IgniteSpiOperationTimeoutException
 org.apache.ignite.spi.IgniteSpiVersionCheckException
 org.apache.ignite.spi.checkpoint.sharedfs.SharedFsCheckpointData
 org.apache.ignite.spi.collision.jobstealing.JobStealingRequest
@@ -1554,14 +1579,16 @@ org.apache.ignite.spi.communication.tcp.TcpCommunicationSpi$1
 org.apache.ignite.spi.communication.tcp.TcpCommunicationSpi$2$ConnectClosure
 org.apache.ignite.spi.communication.tcp.TcpCommunicationSpi$2$ConnectClosure$1
 org.apache.ignite.spi.communication.tcp.TcpCommunicationSpi$7
+org.apache.ignite.spi.communication.tcp.TcpCommunicationSpi$8
 org.apache.ignite.spi.communication.tcp.TcpCommunicationSpi$HandshakeClosure
 org.apache.ignite.spi.communication.tcp.TcpCommunicationSpi$HandshakeMessage
 org.apache.ignite.spi.communication.tcp.TcpCommunicationSpi$HandshakeTimeoutException
 org.apache.ignite.spi.communication.tcp.TcpCommunicationSpi$NodeIdMessage
 org.apache.ignite.spi.communication.tcp.TcpCommunicationSpi$RecoveryLastReceivedMessage
-org.apache.ignite.spi.discovery.tcp.TcpClientDiscoverySpi$1
-org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi$IpFinderCleaner$1
-org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi$IpFinderCleaner$2
+org.apache.ignite.spi.discovery.DiscoverySpiCustomMessage
+org.apache.ignite.spi.discovery.tcp.ClientImpl$State
+org.apache.ignite.spi.discovery.tcp.ServerImpl$IpFinderCleaner$1
+org.apache.ignite.spi.discovery.tcp.ServerImpl$IpFinderCleaner$2
 org.apache.ignite.spi.discovery.tcp.internal.TcpDiscoveryNode
 org.apache.ignite.spi.discovery.tcp.internal.TcpDiscoveryNode$1
 org.apache.ignite.spi.discovery.tcp.internal.TcpDiscoveryNodesRing$1
@@ -1571,7 +1598,12 @@ org.apache.ignite.spi.discovery.tcp.internal.TcpDiscoverySpiState
 org.apache.ignite.spi.discovery.tcp.messages.TcpDiscoveryAbstractMessage
 org.apache.ignite.spi.discovery.tcp.messages.TcpDiscoveryAuthFailedMessage
 org.apache.ignite.spi.discovery.tcp.messages.TcpDiscoveryCheckFailedMessage
+org.apache.ignite.spi.discovery.tcp.messages.TcpDiscoveryClientAckResponse
+org.apache.ignite.spi.discovery.tcp.messages.TcpDiscoveryClientHeartbeatMessage
+org.apache.ignite.spi.discovery.tcp.messages.TcpDiscoveryClientPingRequest
+org.apache.ignite.spi.discovery.tcp.messages.TcpDiscoveryClientPingResponse
 org.apache.ignite.spi.discovery.tcp.messages.TcpDiscoveryClientReconnectMessage
+org.apache.ignite.spi.discovery.tcp.messages.TcpDiscoveryConnectionCheckMessage
 org.apache.ignite.spi.discovery.tcp.messages.TcpDiscoveryCustomEventMessage
 org.apache.ignite.spi.discovery.tcp.messages.TcpDiscoveryDiscardMessage
 org.apache.ignite.spi.discovery.tcp.messages.TcpDiscoveryDuplicateIdMessage
@@ -1591,6 +1623,7 @@ org.apache.ignite.spi.discovery.tcp.messages.TcpDiscoveryPingResponse
 org.apache.ignite.spi.discovery.tcp.messages.TcpDiscoveryStatusCheckMessage
 org.apache.ignite.spi.swapspace.file.FileSwapSpaceSpi$1
 org.apache.ignite.spi.swapspace.file.FileSwapSpaceSpi$2
+org.apache.ignite.ssl.SslContextFactory
 org.apache.ignite.startup.BasicWarmupClosure
 org.apache.ignite.startup.cmdline.AboutDialog
 org.apache.ignite.startup.cmdline.AboutDialog$1

http://git-wip-us.apache.org/repos/asf/ignite/blob/878dcd92/modules/core/src/test/java/org/apache/ignite/internal/portable/GridPortableAffinityKeySelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/portable/GridPortableAffinityKeySelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/portable/GridPortableAffinityKeySelfTest.java
new file mode 100644
index 0000000..00705dc
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/portable/GridPortableAffinityKeySelfTest.java
@@ -0,0 +1,215 @@
+/*
+ * 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.portable;
+
+import org.apache.ignite.*;
+import org.apache.ignite.cache.affinity.*;
+import org.apache.ignite.configuration.*;
+import org.apache.ignite.internal.*;
+import org.apache.ignite.internal.processors.affinity.*;
+import org.apache.ignite.internal.processors.cache.*;
+import org.apache.ignite.internal.processors.cacheobject.*;
+import org.apache.ignite.lang.*;
+import org.apache.ignite.marshaller.portable.*;
+import org.apache.ignite.portable.*;
+import org.apache.ignite.resources.*;
+import org.apache.ignite.spi.discovery.tcp.*;
+import org.apache.ignite.spi.discovery.tcp.ipfinder.*;
+import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.*;
+import org.apache.ignite.testframework.junits.common.*;
+
+import java.util.*;
+import java.util.concurrent.atomic.*;
+
+import static org.apache.ignite.cache.CacheMode.*;
+
+/**
+ * Test for portable object affinity key.
+ */
+public class GridPortableAffinityKeySelfTest extends GridCommonAbstractTest {
+    /** */
+    private static final AtomicReference<UUID> nodeId = new AtomicReference<>();
+
+    /** VM ip finder for TCP discovery. */
+    private static TcpDiscoveryIpFinder ipFinder = new TcpDiscoveryVmIpFinder(true);
+
+    /** */
+    private static int GRID_CNT = 5;
+
+    /** {@inheritDoc} */
+    @Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception {
+        IgniteConfiguration cfg = super.getConfiguration(gridName);
+
+        PortableTypeConfiguration typeCfg = new PortableTypeConfiguration();
+
+        typeCfg.setClassName(TestObject.class.getName());
+        typeCfg.setAffinityKeyFieldName("affKey");
+
+        PortableMarshaller marsh = new PortableMarshaller();
+
+        marsh.setTypeConfigurations(Collections.singleton(typeCfg));
+
+        cfg.setMarshaller(marsh);
+
+        if (!gridName.equals(getTestGridName(GRID_CNT))) {
+            CacheConfiguration cacheCfg = new CacheConfiguration();
+
+            cacheCfg.setCacheMode(PARTITIONED);
+
+            cfg.setCacheConfiguration(cacheCfg);
+        }
+
+        ((TcpDiscoverySpi)cfg.getDiscoverySpi()).setIpFinder(ipFinder);
+
+        return cfg;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void beforeTestsStarted() throws Exception {
+        startGridsMultiThreaded(GRID_CNT);
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void afterTestsStopped() throws Exception {
+        stopAllGrids();
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testAffinity() throws Exception {
+        checkAffinity(grid(0));
+
+        try (Ignite igniteNoCache = startGrid(GRID_CNT)) {
+            try {
+                igniteNoCache.cache(null);
+            }
+            catch (IllegalArgumentException ignore) {
+                // Expected error.
+            }
+
+            checkAffinity(igniteNoCache);
+        }
+    }
+
+    /**
+     * @param ignite Ignite.
+     * @throws Exception If failed.
+     */
+    private void checkAffinity(Ignite ignite) throws Exception {
+        Affinity<Object> aff = ignite.affinity(null);
+
+        GridAffinityProcessor affProc = ((IgniteKernal)ignite).context().affinity();
+
+        IgniteCacheObjectProcessor cacheObjProc = ((IgniteKernal)ignite).context().cacheObjects();
+
+        CacheObjectContext cacheObjCtx = cacheObjProc.contextForCache(
+            ignite.cache(null).getConfiguration(CacheConfiguration.class));
+
+        for (int i = 0; i < 1000; i++) {
+            assertEquals(i, aff.affinityKey(i));
+
+            assertEquals(i, aff.affinityKey(new TestObject(i)));
+
+            CacheObject cacheObj = cacheObjProc.toCacheObject(cacheObjCtx, new TestObject(i), true);
+
+            assertEquals(i, aff.affinityKey(cacheObj));
+
+            assertEquals(aff.mapKeyToNode(i), aff.mapKeyToNode(new TestObject(i)));
+
+            assertEquals(aff.mapKeyToNode(i), aff.mapKeyToNode(cacheObj));
+
+            assertEquals(i, affProc.affinityKey(null, i));
+
+            assertEquals(i, affProc.affinityKey(null, new TestObject(i)));
+
+            assertEquals(i, affProc.affinityKey(null, cacheObj));
+
+            assertEquals(affProc.mapKeyToNode(null, i), affProc.mapKeyToNode(null, new TestObject(i)));
+
+            assertEquals(affProc.mapKeyToNode(null, i), affProc.mapKeyToNode(null, cacheObj));
+        }
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testAffinityRun() throws Exception {
+        Affinity<Object> aff = grid(0).affinity(null);
+
+        for (int i = 0; i < 1000; i++) {
+            nodeId.set(null);
+
+            grid(0).compute().affinityRun(null, new TestObject(i), new IgniteRunnable() {
+                @IgniteInstanceResource
+                private Ignite ignite;
+
+                @Override public void run() {
+                    nodeId.set(ignite.configuration().getNodeId());
+                }
+            });
+
+            assertEquals(aff.mapKeyToNode(i).id(), nodeId.get());
+        }
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testAffinityCall() throws Exception {
+        Affinity<Object> aff = grid(0).affinity(null);
+
+        for (int i = 0; i < 1000; i++) {
+            nodeId.set(null);
+
+            grid(0).compute().affinityCall(null, new TestObject(i), new IgniteCallable<Object>() {
+                @IgniteInstanceResource
+                private Ignite ignite;
+
+                @Override public Object call() {
+                    nodeId.set(ignite.configuration().getNodeId());
+
+                    return null;
+                }
+            });
+
+            assertEquals(aff.mapKeyToNode(i).id(), nodeId.get());
+        }
+    }
+
+    /**
+     */
+    private static class TestObject {
+        /** */
+        @SuppressWarnings("UnusedDeclaration")
+        private int affKey;
+
+        /**
+         */
+        private TestObject() {
+            // No-op.
+        }
+
+        /**
+         * @param affKey Affinity key.
+         */
+        private TestObject(int affKey) {
+            this.affKey = affKey;
+        }
+    }
+}


[27/59] [abbrv] ignite git commit: Platforms: minor refactoring.

Posted by vk...@apache.org.
Platforms: minor refactoring.


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

Branch: refs/heads/ignite-884
Commit: 2e6d91571e26a819b0b928095c712bf034fc0e29
Parents: 21cff74
Author: vozerov-gridgain <vo...@gridgain.com>
Authored: Wed Aug 26 09:05:56 2015 +0300
Committer: vozerov-gridgain <vo...@gridgain.com>
Committed: Wed Aug 26 09:05:56 2015 +0300

----------------------------------------------------------------------
 .../internal/GridEventConsumeHandler.java       |  2 +-
 .../eventstorage/GridEventStorageManager.java   |  2 +-
 .../platform/PlatformAwareEventFilter.java      | 37 --------------------
 .../platform/PlatformLocalEventListener.java    | 28 ---------------
 .../platform/PlatformAwareEventFilter.java      | 37 ++++++++++++++++++++
 .../platform/PlatformLocalEventListener.java    | 28 +++++++++++++++
 .../resources/META-INF/classnames.properties    |  2 +-
 7 files changed, 68 insertions(+), 68 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/2e6d9157/modules/core/src/main/java/org/apache/ignite/internal/GridEventConsumeHandler.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/GridEventConsumeHandler.java b/modules/core/src/main/java/org/apache/ignite/internal/GridEventConsumeHandler.java
index 134184a..0ae8050 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/GridEventConsumeHandler.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/GridEventConsumeHandler.java
@@ -23,9 +23,9 @@ import org.apache.ignite.events.*;
 import org.apache.ignite.internal.cluster.*;
 import org.apache.ignite.internal.managers.deployment.*;
 import org.apache.ignite.internal.managers.eventstorage.*;
-import org.apache.ignite.internal.platform.*;
 import org.apache.ignite.internal.processors.cache.*;
 import org.apache.ignite.internal.processors.continuous.*;
+import org.apache.ignite.internal.processors.platform.*;
 import org.apache.ignite.internal.util.typedef.*;
 import org.apache.ignite.internal.util.typedef.internal.*;
 import org.apache.ignite.lang.*;

http://git-wip-us.apache.org/repos/asf/ignite/blob/2e6d9157/modules/core/src/main/java/org/apache/ignite/internal/managers/eventstorage/GridEventStorageManager.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/managers/eventstorage/GridEventStorageManager.java b/modules/core/src/main/java/org/apache/ignite/internal/managers/eventstorage/GridEventStorageManager.java
index d8e6ae1..ae7049c 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/managers/eventstorage/GridEventStorageManager.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/managers/eventstorage/GridEventStorageManager.java
@@ -25,7 +25,7 @@ import org.apache.ignite.internal.events.*;
 import org.apache.ignite.internal.managers.*;
 import org.apache.ignite.internal.managers.communication.*;
 import org.apache.ignite.internal.managers.deployment.*;
-import org.apache.ignite.internal.platform.*;
+import org.apache.ignite.internal.processors.platform.*;
 import org.apache.ignite.internal.util.*;
 import org.apache.ignite.internal.util.future.*;
 import org.apache.ignite.internal.util.typedef.*;

http://git-wip-us.apache.org/repos/asf/ignite/blob/2e6d9157/modules/core/src/main/java/org/apache/ignite/internal/platform/PlatformAwareEventFilter.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/platform/PlatformAwareEventFilter.java b/modules/core/src/main/java/org/apache/ignite/internal/platform/PlatformAwareEventFilter.java
deleted file mode 100644
index 2ae664d..0000000
--- a/modules/core/src/main/java/org/apache/ignite/internal/platform/PlatformAwareEventFilter.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * 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.platform;
-
-import org.apache.ignite.events.*;
-import org.apache.ignite.internal.*;
-import org.apache.ignite.lang.*;
-
-/**
- * Special version of predicate for events with initialize/close callbacks.
- */
-public interface PlatformAwareEventFilter<E extends Event> extends IgnitePredicate<E> {
-    /**
-     * Initializes the filter.
-     */
-    public void initialize(GridKernalContext ctx);
-
-    /**
-     * Closes the filter.
-     */
-    public void close();
-}

http://git-wip-us.apache.org/repos/asf/ignite/blob/2e6d9157/modules/core/src/main/java/org/apache/ignite/internal/platform/PlatformLocalEventListener.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/platform/PlatformLocalEventListener.java b/modules/core/src/main/java/org/apache/ignite/internal/platform/PlatformLocalEventListener.java
deleted file mode 100644
index 31c585c..0000000
--- a/modules/core/src/main/java/org/apache/ignite/internal/platform/PlatformLocalEventListener.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * 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.platform;
-
-/**
- * Special version of listener for events with close callbacks.
- */
-public interface PlatformLocalEventListener {
-    /**
-     * Closes the listener.
-     */
-    public void close();
-}

http://git-wip-us.apache.org/repos/asf/ignite/blob/2e6d9157/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/PlatformAwareEventFilter.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/PlatformAwareEventFilter.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/PlatformAwareEventFilter.java
new file mode 100644
index 0000000..f056bbf
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/PlatformAwareEventFilter.java
@@ -0,0 +1,37 @@
+/*
+ * 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.platform;
+
+import org.apache.ignite.events.*;
+import org.apache.ignite.internal.*;
+import org.apache.ignite.lang.*;
+
+/**
+ * Special version of predicate for events with initialize/close callbacks.
+ */
+public interface PlatformAwareEventFilter<E extends Event> extends IgnitePredicate<E> {
+    /**
+     * Initializes the filter.
+     */
+    public void initialize(GridKernalContext ctx);
+
+    /**
+     * Closes the filter.
+     */
+    public void close();
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/2e6d9157/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/PlatformLocalEventListener.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/PlatformLocalEventListener.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/PlatformLocalEventListener.java
new file mode 100644
index 0000000..41f41eb
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/PlatformLocalEventListener.java
@@ -0,0 +1,28 @@
+/*
+ * 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.platform;
+
+/**
+ * Special version of listener for events with close callbacks.
+ */
+public interface PlatformLocalEventListener {
+    /**
+     * Closes the listener.
+     */
+    public void close();
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/2e6d9157/modules/core/src/main/resources/META-INF/classnames.properties
----------------------------------------------------------------------
diff --git a/modules/core/src/main/resources/META-INF/classnames.properties b/modules/core/src/main/resources/META-INF/classnames.properties
index fb1673a..d80cc49 100644
--- a/modules/core/src/main/resources/META-INF/classnames.properties
+++ b/modules/core/src/main/resources/META-INF/classnames.properties
@@ -278,7 +278,7 @@ org.apache.ignite.internal.managers.eventstorage.GridEventStorageMessage
 org.apache.ignite.internal.managers.indexing.GridIndexingManager$1
 org.apache.ignite.internal.managers.loadbalancer.GridLoadBalancerAdapter
 org.apache.ignite.internal.managers.loadbalancer.GridLoadBalancerManager$1
-org.apache.ignite.internal.platform.PlatformAwareEventFilter
+org.apache.ignite.internal.processors.platform.PlatformAwareEventFilter
 org.apache.ignite.internal.portable.PortableClassDescriptor$Mode
 org.apache.ignite.internal.portable.PortableContext
 org.apache.ignite.internal.portable.PortableLazyMap$1$1$1


[43/59] [abbrv] ignite git commit: Abstracted out metadata processing.

Posted by vk...@apache.org.
Abstracted out metadata processing.


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

Branch: refs/heads/ignite-884
Commit: a43e80a9ad3ceb83775a20a84b972a6b0ee396ae
Parents: cdf82e9
Author: vozerov-gridgain <vo...@gridgain.com>
Authored: Wed Aug 26 12:57:08 2015 +0300
Committer: vozerov-gridgain <vo...@gridgain.com>
Committed: Wed Aug 26 12:57:08 2015 +0300

----------------------------------------------------------------------
 .../ignite/internal/processors/platform/PlatformContext.java  | 7 +++++++
 1 file changed, 7 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/a43e80a9/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/PlatformContext.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/PlatformContext.java b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/PlatformContext.java
index 0385f46..fb1eaa2 100644
--- a/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/PlatformContext.java
+++ b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/PlatformContext.java
@@ -104,4 +104,11 @@ public interface PlatformContext {
      * @param nodes Nodes.
      */
     public void writeNodes(PortableRawWriterEx writer, Collection<ClusterNode> nodes);
+
+    /**
+     * Process metadata from the platform.
+     *
+     * @param reader Reader.
+     */
+    public void processMetadata(PortableRawReaderEx reader);
 }


[19/59] [abbrv] ignite git commit: IGNITE-1287: Moved memory management code to Ignite.

Posted by vk...@apache.org.
IGNITE-1287: Moved memory management code to Ignite.


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

Branch: refs/heads/ignite-884
Commit: 7b61a0973027ac5a7c3d508018503ca2621a1092
Parents: 14718f9
Author: vozerov-gridgain <vo...@gridgain.com>
Authored: Tue Aug 25 13:05:16 2015 +0300
Committer: vozerov-gridgain <vo...@gridgain.com>
Committed: Tue Aug 25 13:05:16 2015 +0300

----------------------------------------------------------------------
 .../Apache.Ignite.Core.csproj                   |  25 +
 .../Impl/Memory/IPlatformMemory.cs              |  62 ++
 .../Memory/PlatformBigEndianMemoryStream.cs     | 483 +++++++++++++
 .../Impl/Memory/PlatformMemory.cs               |  77 +++
 .../Impl/Memory/PlatformMemoryManager.cs        | 106 +++
 .../Impl/Memory/PlatformMemoryPool.cs           | 105 +++
 .../Impl/Memory/PlatformMemoryStream.cs         | 676 +++++++++++++++++++
 .../Impl/Memory/PlatformMemoryUtils.cs          | 462 +++++++++++++
 .../Impl/Memory/PlatformPooledMemory.cs         |  70 ++
 .../Impl/Memory/PlatformRawMemory.cs            |  88 +++
 .../Impl/Memory/PlatformUnpooledMemory.cs       |  52 ++
 .../Impl/Portable/Io/IPortableStream.cs         | 320 +++++++++
 .../Properties/AssemblyInfo.cs                  |   6 +
 .../main/dotnet/Apache.Ignite.sln.DotSettings   |   4 +
 .../Apache.Ignite.Core.Tests.csproj             |   8 +
 .../Memory/InteropMemoryTest.cs                 | 213 ++++++
 .../Apache.Ignite.Core.Tests/TestRunner.cs      |   4 +-
 17 files changed, 2759 insertions(+), 2 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/7b61a097/modules/platform/src/main/dotnet/Apache.Ignite.Core/Apache.Ignite.Core.csproj
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Apache.Ignite.Core.csproj b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Apache.Ignite.Core.csproj
index 0980c8f..c6c8324 100644
--- a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Apache.Ignite.Core.csproj
+++ b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Apache.Ignite.Core.csproj
@@ -15,18 +15,32 @@
   <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x64'">
     <PlatformTarget>x64</PlatformTarget>
     <OutputPath>bin\x64\Debug\</OutputPath>
+    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
   </PropertyGroup>
   <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x64'">
     <PlatformTarget>x64</PlatformTarget>
     <OutputPath>bin\x64\Release\</OutputPath>
+    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
   </PropertyGroup>
   <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x86'">
     <PlatformTarget>x86</PlatformTarget>
     <OutputPath>bin\x86\Debug\</OutputPath>
+    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
   </PropertyGroup>
   <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x86'">
     <PlatformTarget>x86</PlatformTarget>
     <OutputPath>bin\x86\Release\</OutputPath>
+    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
+  </PropertyGroup>
+  <PropertyGroup>
+    <SignAssembly>false</SignAssembly>
+  </PropertyGroup>
+  <PropertyGroup>
+    <AssemblyOriginatorKeyFile>
+    </AssemblyOriginatorKeyFile>
+  </PropertyGroup>
+  <PropertyGroup>
+    <DelaySign>false</DelaySign>
   </PropertyGroup>
   <ItemGroup>
     <Reference Include="System" />
@@ -34,6 +48,17 @@
   </ItemGroup>
   <ItemGroup>
     <Compile Include="Ignition.cs" />
+    <Compile Include="Impl\Memory\IPlatformMemory.cs" />
+    <Compile Include="Impl\Memory\PlatformBigEndianMemoryStream.cs" />
+    <Compile Include="Impl\Memory\PlatformMemory.cs" />
+    <Compile Include="Impl\Memory\PlatformMemoryManager.cs" />
+    <Compile Include="Impl\Memory\PlatformMemoryPool.cs" />
+    <Compile Include="Impl\Memory\PlatformMemoryStream.cs" />
+    <Compile Include="Impl\Memory\PlatformMemoryUtils.cs" />
+    <Compile Include="Impl\Memory\PlatformPooledMemory.cs" />
+    <Compile Include="Impl\Memory\PlatformRawMemory.cs" />
+    <Compile Include="Impl\Memory\PlatformUnpooledMemory.cs" />
+    <Compile Include="Impl\Portable\IO\IPortableStream.cs" />
     <Compile Include="Properties\AssemblyInfo.cs" />
   </ItemGroup>
   <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />

http://git-wip-us.apache.org/repos/asf/ignite/blob/7b61a097/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/IPlatformMemory.cs
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/IPlatformMemory.cs b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/IPlatformMemory.cs
new file mode 100644
index 0000000..ff91f48
--- /dev/null
+++ b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/IPlatformMemory.cs
@@ -0,0 +1,62 @@
+/*
+ * 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.
+ */
+
+namespace Apache.Ignite.Core.Impl.Memory
+{
+    /// <summary>
+    /// Platform memory chunk.
+    /// </summary>
+    public interface IPlatformMemory
+    {
+        /// <summary>
+        /// Gets stream for read/write operations on the given memory chunk.
+        /// </summary>
+        /// <returns></returns>
+        PlatformMemoryStream Stream();
+
+        /// <summary>
+        /// Cross-platform pointer.
+        /// </summary>
+        long Pointer { get; }
+
+        /// <summary>
+        /// Data pointer.
+        /// </summary>
+        long Data { get; }
+
+        /// <summary>
+        /// CalculateCapacity.
+        /// </summary>
+        int Capacity { get; }
+
+        /// <summary>
+        /// Length.
+        /// </summary>
+        int Length { get; set; }
+
+        /// <summary>
+        /// Reallocates memory chunk.
+        /// </summary>
+        /// <param name="cap">Minimum capacity.</param>
+        void Reallocate(int cap);
+
+        /// <summary>
+        /// Release memory.
+        /// </summary>
+        void Release();
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/7b61a097/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/PlatformBigEndianMemoryStream.cs
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/PlatformBigEndianMemoryStream.cs b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/PlatformBigEndianMemoryStream.cs
new file mode 100644
index 0000000..33a0487
--- /dev/null
+++ b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/PlatformBigEndianMemoryStream.cs
@@ -0,0 +1,483 @@
+/*
+ * 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.
+ */
+
+namespace Apache.Ignite.Core.Impl.Memory
+{
+    /// <summary>
+    /// Platform memory stream for big endian platforms.
+    /// </summary>
+    internal class PlatformBigEndianMemoryStream : PlatformMemoryStream
+    {
+        /// <summary>
+        /// Constructor.
+        /// </summary>
+        /// <param name="mem"></param>
+        public PlatformBigEndianMemoryStream(IPlatformMemory mem) : base(mem)
+        {
+            // No-op.
+        }
+
+        #region WRITE
+
+        /** <inheritDoc /> */
+        public override unsafe void WriteShort(short val)
+        {
+            byte* curPos = Data + EnsureWriteCapacityAndShift(Len2);
+
+            byte* valPtr = (byte*)&val;
+
+            curPos[0] = valPtr[1];
+            curPos[1] = valPtr[0];
+        }
+
+        /** <inheritDoc /> */
+        public override unsafe void WriteShortArray(short[] val)
+        {
+            byte* curPos = Data + EnsureWriteCapacityAndShift(val.Length << Shift2);
+
+            for (int i = 0; i < val.Length; i++)
+            {
+                short val0 = val[i];
+
+                byte* valPtr = (byte*)&(val0);
+
+                *curPos++ = valPtr[1];
+                *curPos++ = valPtr[0];
+            }
+        }
+
+        /** <inheritDoc /> */
+        public override unsafe void WriteChar(char val)
+        {
+            WriteShort(*(short*)(&val));
+        }
+
+        /** <inheritDoc /> */
+        public override unsafe void WriteCharArray(char[] val)
+        {
+            byte* curPos = Data + EnsureWriteCapacityAndShift(val.Length << Shift2);
+
+            for (int i = 0; i < val.Length; i++)
+            {
+                char val0 = val[i];
+
+                byte* valPtr = (byte*)&(val0);
+
+                *curPos++ = valPtr[1];
+                *curPos++ = valPtr[0];
+            }
+        }
+
+        /** <inheritDoc /> */
+        public override unsafe void WriteInt(int val)
+        {
+            byte* curPos = Data + EnsureWriteCapacityAndShift(Len4);
+
+            byte* valPtr = (byte*)&val;
+
+            curPos[0] = valPtr[3];
+            curPos[1] = valPtr[2];
+            curPos[2] = valPtr[1];
+            curPos[3] = valPtr[0];
+        }
+
+        /** <inheritDoc /> */
+        public override unsafe void WriteInt(int writePos, int val)
+        {
+            EnsureWriteCapacity(writePos + 4);
+
+            byte* curPos = Data + writePos;
+
+            byte* valPtr = (byte*)&val;
+
+            curPos[0] = valPtr[3];
+            curPos[1] = valPtr[2];
+            curPos[2] = valPtr[1];
+            curPos[3] = valPtr[0];
+        }
+
+        /** <inheritDoc /> */
+        public override unsafe void WriteIntArray(int[] val)
+        {
+            byte* curPos = Data + EnsureWriteCapacityAndShift(val.Length << Shift4);
+
+            for (int i = 0; i < val.Length; i++)
+            {
+                int val0 = val[i];
+
+                byte* valPtr = (byte*)&(val0);
+
+                *curPos++ = valPtr[3];
+                *curPos++ = valPtr[2];
+                *curPos++ = valPtr[1];
+                *curPos++ = valPtr[0];
+            }
+        }
+
+        /** <inheritDoc /> */
+        public override unsafe void WriteLong(long val)
+        {
+            byte* curPos = Data + EnsureWriteCapacityAndShift(Len8);
+
+            byte* valPtr = (byte*)&val;
+
+            curPos[0] = valPtr[7];
+            curPos[1] = valPtr[6];
+            curPos[2] = valPtr[5];
+            curPos[3] = valPtr[4];
+            curPos[4] = valPtr[3];
+            curPos[5] = valPtr[2];
+            curPos[6] = valPtr[1];
+            curPos[7] = valPtr[0];
+        }
+
+        /** <inheritDoc /> */
+        public override unsafe void WriteLongArray(long[] val)
+        {
+            byte* curPos = Data + EnsureWriteCapacityAndShift(val.Length << Shift8);
+
+            for (int i = 0; i < val.Length; i++)
+            {
+                long val0 = val[i];
+
+                byte* valPtr = (byte*)&(val0);
+
+                *curPos++ = valPtr[7];
+                *curPos++ = valPtr[6];
+                *curPos++ = valPtr[5];
+                *curPos++ = valPtr[4];
+                *curPos++ = valPtr[3];
+                *curPos++ = valPtr[2];
+                *curPos++ = valPtr[1];
+                *curPos++ = valPtr[0];
+            }
+        }
+
+        /** <inheritDoc /> */
+        public override unsafe void WriteFloat(float val)
+        {
+            WriteInt(*(int*)(&val));
+        }
+
+        /** <inheritDoc /> */
+        public override unsafe void WriteFloatArray(float[] val)
+        {
+            byte* curPos = Data + EnsureWriteCapacityAndShift(val.Length << Shift4);
+
+            for (int i = 0; i < val.Length; i++)
+            {
+                float val0 = val[i];
+
+                byte* valPtr = (byte*)&(val0);
+
+                *curPos++ = valPtr[3];
+                *curPos++ = valPtr[2];
+                *curPos++ = valPtr[1];
+                *curPos++ = valPtr[0];
+            }
+        }
+
+        /** <inheritDoc /> */
+        public override unsafe void WriteDouble(double val)
+        {
+            WriteLong(*(long*)(&val));
+        }
+
+        /** <inheritDoc /> */
+        public override unsafe void WriteDoubleArray(double[] val)
+        {
+            byte* curPos = Data + EnsureWriteCapacityAndShift(val.Length << Shift8);
+
+            for (int i = 0; i < val.Length; i++)
+            {
+                double val0 = val[i];
+
+                byte* valPtr = (byte*)&(val0);
+
+                *curPos++ = valPtr[7];
+                *curPos++ = valPtr[6];
+                *curPos++ = valPtr[5];
+                *curPos++ = valPtr[4];
+                *curPos++ = valPtr[3];
+                *curPos++ = valPtr[2];
+                *curPos++ = valPtr[1];
+                *curPos++ = valPtr[0];
+            }
+        }
+
+        #endregion
+
+        #region READ
+
+        /** <inheritDoc /> */
+        public override unsafe short ReadShort()
+        {
+            int curPos = EnsureReadCapacityAndShift(Len2);
+
+            short val;
+
+            byte* valPtr = (byte*)&val;
+
+            valPtr[1] = *(Data + curPos++);
+            valPtr[0] = *(Data + curPos);
+
+            return val;
+        }
+
+        /** <inheritDoc /> */
+        public override unsafe short[] ReadShortArray(int len)
+        {
+            int curPos = EnsureReadCapacityAndShift(len << Shift2);
+
+            short[] res = new short[len];
+
+            for (int i = 0; i < len; i++)
+            {
+                short val;
+
+                byte* valPtr = (byte*)&val;
+
+                valPtr[1] = *(Data + curPos++);
+                valPtr[0] = *(Data + curPos++);
+
+                res[i] = val;
+            }
+
+            return res;
+        }
+
+        /** <inheritDoc /> */
+        public override unsafe char ReadChar()
+        {
+            int curPos = EnsureReadCapacityAndShift(Len2);
+
+            char val;
+
+            byte* valPtr = (byte*)&val;
+
+            valPtr[1] = *(Data + curPos++);
+            valPtr[0] = *(Data + curPos);
+
+            return val;
+        }
+
+        /** <inheritDoc /> */
+        public override unsafe char[] ReadCharArray(int len)
+        {
+            int curPos = EnsureReadCapacityAndShift(len << Shift2);
+
+            char[] res = new char[len];
+
+            for (int i = 0; i < len; i++)
+            {
+                char val;
+
+                byte* valPtr = (byte*)&val;
+
+                valPtr[1] = *(Data + curPos++);
+                valPtr[0] = *(Data + curPos++);
+
+                res[i] = val;
+            }
+
+            return res;
+        }
+
+        /** <inheritDoc /> */
+        public override unsafe int ReadInt()
+        {
+            int curPos = EnsureReadCapacityAndShift(Len4);
+
+            int val;
+
+            byte* valPtr = (byte*)&val;
+
+            valPtr[3] = *(Data + curPos++);
+            valPtr[2] = *(Data + curPos++);
+            valPtr[1] = *(Data + curPos++);
+            valPtr[0] = *(Data + curPos);
+
+            return val;
+        }
+
+        /** <inheritDoc /> */
+        public override unsafe int[] ReadIntArray(int len)
+        {
+            int curPos = EnsureReadCapacityAndShift(len << Shift4);
+
+            int[] res = new int[len];
+
+            for (int i = 0; i < len; i++)
+            {
+                int val;
+
+                byte* valPtr = (byte*)&val;
+
+                valPtr[3] = *(Data + curPos++);
+                valPtr[2] = *(Data + curPos++);
+                valPtr[1] = *(Data + curPos++);
+                valPtr[0] = *(Data + curPos++);
+
+                res[i] = val;
+            }
+
+            return res;
+        }
+
+        /** <inheritDoc /> */
+        public override unsafe long ReadLong()
+        {
+            int curPos = EnsureReadCapacityAndShift(Len8);
+
+            long val;
+
+            byte* valPtr = (byte*)&val;
+
+            valPtr[7] = *(Data + curPos++);
+            valPtr[6] = *(Data + curPos++);
+            valPtr[5] = *(Data + curPos++);
+            valPtr[4] = *(Data + curPos++);
+            valPtr[3] = *(Data + curPos++);
+            valPtr[2] = *(Data + curPos++);
+            valPtr[1] = *(Data + curPos++);
+            valPtr[0] = *(Data + curPos);
+
+            return val;
+        }
+
+        /** <inheritDoc /> */
+
+        public override unsafe long[] ReadLongArray(int len)
+        {
+            int curPos = EnsureReadCapacityAndShift(len << Shift8);
+
+            long[] res = new long[len];
+
+            for (int i = 0; i < len; i++)
+            {
+                long val;
+
+                byte* valPtr = (byte*) &val;
+
+                valPtr[7] = *(Data + curPos++);
+                valPtr[6] = *(Data + curPos++);
+                valPtr[5] = *(Data + curPos++);
+                valPtr[4] = *(Data + curPos++);
+                valPtr[3] = *(Data + curPos++);
+                valPtr[2] = *(Data + curPos++);
+                valPtr[1] = *(Data + curPos++);
+                valPtr[0] = *(Data + curPos++);
+
+                res[i] = val;
+            }
+
+            return res;
+        }
+
+        /** <inheritDoc /> */
+        public override unsafe float ReadFloat()
+        {
+            int curPos = EnsureReadCapacityAndShift(Len4);
+
+            float val;
+
+            byte* valPtr = (byte*)&val;
+
+            valPtr[3] = *(Data + curPos++);
+            valPtr[2] = *(Data + curPos++);
+            valPtr[1] = *(Data + curPos++);
+            valPtr[0] = *(Data + curPos);
+
+            return val;
+        }
+
+        /** <inheritDoc /> */
+        public override unsafe float[] ReadFloatArray(int len)
+        {
+            int curPos = EnsureReadCapacityAndShift(len << Shift4);
+
+            float[] res = new float[len];
+
+            for (int i = 0; i < len; i++)
+            {
+                float val;
+
+                byte* valPtr = (byte*)&val;
+
+                valPtr[3] = *(Data + curPos++);
+                valPtr[2] = *(Data + curPos++);
+                valPtr[1] = *(Data + curPos++);
+                valPtr[0] = *(Data + curPos++);
+
+                res[i] = val;
+            }
+
+            return res;
+        }
+
+        /** <inheritDoc /> */
+        public override unsafe double ReadDouble()
+        {
+            int curPos = EnsureReadCapacityAndShift(Len8);
+
+            double val;
+
+            byte* valPtr = (byte*)&val;
+
+            valPtr[7] = *(Data + curPos++);
+            valPtr[6] = *(Data + curPos++);
+            valPtr[5] = *(Data + curPos++);
+            valPtr[4] = *(Data + curPos++);
+            valPtr[3] = *(Data + curPos++);
+            valPtr[2] = *(Data + curPos++);
+            valPtr[1] = *(Data + curPos++);
+            valPtr[0] = *(Data + curPos);
+
+            return val;
+        }
+
+        /** <inheritDoc /> */
+        public override unsafe double[] ReadDoubleArray(int len)
+        {
+            int curPos = EnsureReadCapacityAndShift(len << Shift8);
+
+            double[] res = new double[len];
+
+            for (int i = 0; i < len; i++)
+            {
+                double val;
+
+                byte* valPtr = (byte*)&val;
+
+                valPtr[7] = *(Data + curPos++);
+                valPtr[6] = *(Data + curPos++);
+                valPtr[5] = *(Data + curPos++);
+                valPtr[4] = *(Data + curPos++);
+                valPtr[3] = *(Data + curPos++);
+                valPtr[2] = *(Data + curPos++);
+                valPtr[1] = *(Data + curPos++);
+                valPtr[0] = *(Data + curPos++);
+
+                res[i] = val;
+            }
+
+            return res;
+        }
+
+        #endregion
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/7b61a097/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/PlatformMemory.cs
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/PlatformMemory.cs b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/PlatformMemory.cs
new file mode 100644
index 0000000..e19505c
--- /dev/null
+++ b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/PlatformMemory.cs
@@ -0,0 +1,77 @@
+/*
+ * 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.
+ */
+
+namespace Apache.Ignite.Core.Impl.Memory
+{
+    using System;
+
+    /// <summary>
+    /// Abstract memory chunk.
+    /// </summary>
+    public abstract class PlatformMemory : IPlatformMemory
+    {
+        /** Memory pointer. */
+        protected readonly long MemPtr;
+
+        /// <summary>
+        /// Constructor.
+        /// </summary>
+        /// <param name="memPtr">Memory pointer.</param>
+        protected PlatformMemory(long memPtr)
+        {
+            MemPtr = memPtr;
+        }
+
+        /** <inheritdoc /> */
+        public virtual PlatformMemoryStream Stream()
+        {
+            return BitConverter.IsLittleEndian ? new PlatformMemoryStream(this) : 
+                new PlatformBigEndianMemoryStream(this);
+        }
+
+        /** <inheritdoc /> */
+        public long Pointer
+        {
+            get { return MemPtr; }
+        }
+
+        /** <inheritdoc /> */
+        public long Data
+        {
+            get { return PlatformMemoryUtils.Data(MemPtr); }
+        }
+
+        /** <inheritdoc /> */
+        public int Capacity
+        {
+            get { return PlatformMemoryUtils.Capacity(MemPtr); }
+        }
+
+        /** <inheritdoc /> */
+        public int Length
+        {
+            get { return PlatformMemoryUtils.Length(MemPtr); }
+            set { PlatformMemoryUtils.Length(MemPtr, value); }
+        }
+
+        /** <inheritdoc /> */
+        public abstract void Reallocate(int cap);
+
+        /** <inheritdoc /> */
+        public abstract void Release();
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/7b61a097/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/PlatformMemoryManager.cs
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/PlatformMemoryManager.cs b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/PlatformMemoryManager.cs
new file mode 100644
index 0000000..2d52dd6
--- /dev/null
+++ b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/PlatformMemoryManager.cs
@@ -0,0 +1,106 @@
+/*
+ * 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.
+ */
+
+namespace Apache.Ignite.Core.Impl.Memory
+{
+    using System;
+    using System.Diagnostics.CodeAnalysis;
+    using System.Threading;
+    
+    /// <summary>
+    /// Memory manager implementation.
+    /// </summary>
+    [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable",
+        Justification = "This class instance usually lives as long as the app runs.")]
+    public class PlatformMemoryManager
+    {
+        /** Default capacity. */
+        private readonly int _dfltCap;
+
+        /** Thread-local pool. */
+        private readonly ThreadLocal<PlatformMemoryPool> _threadLocPool = new ThreadLocal<PlatformMemoryPool>();
+
+        /// <summary>
+        /// Constructor.
+        /// </summary>
+        /// <param name="dfltCap">Default capacity.</param>
+        public PlatformMemoryManager(int dfltCap)
+        {
+            _dfltCap = dfltCap;
+        }
+
+        /// <summary>
+        /// Allocate memory.
+        /// </summary>
+        /// <returns>Memory.</returns>
+        public IPlatformMemory Allocate()
+        {
+            return Allocate(_dfltCap);
+        }
+
+        /// <summary>
+        /// Allocate memory having at least the given capacity.
+        /// </summary>
+        /// <param name="cap">Minimum capacity.</param>
+        /// <returns>Memory.</returns>
+        public IPlatformMemory Allocate(int cap)
+        {
+            return Pool().Allocate(cap);
+        }
+
+        /// <summary>
+        /// Gets memory from existing pointer.
+        /// </summary>
+        /// <param name="memPtr">Cross-platform memory pointer.</param>
+        /// <returns>Memory.</returns>
+        public IPlatformMemory Get(long memPtr)
+        {
+            int flags = PlatformMemoryUtils.Flags(memPtr);
+
+            return PlatformMemoryUtils.IsExternal(flags) ? GetExternalMemory(memPtr)
+                : PlatformMemoryUtils.IsPooled(flags) ? Pool().Get(memPtr) : new PlatformUnpooledMemory(memPtr);
+        }
+
+        /// <summary>
+        /// Gets or creates thread-local memory pool.
+        /// </summary>
+        /// <returns>Memory pool.</returns>
+        public PlatformMemoryPool Pool()
+        {
+            PlatformMemoryPool pool = _threadLocPool.Value;
+
+            if (pool == null)
+            {
+                pool = new PlatformMemoryPool();
+
+                _threadLocPool.Value = pool;
+            }
+
+            return pool;
+        }
+
+        /// <summary>
+        /// Gets the external memory.
+        /// </summary>
+        /// <param name="memPtr">Cross-platform memory pointer.</param>
+        /// <returns>Memory.</returns>
+        protected virtual IPlatformMemory GetExternalMemory(long memPtr)
+        {
+            throw new NotSupportedException("Not supported in Ignite yet");
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/7b61a097/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/PlatformMemoryPool.cs
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/PlatformMemoryPool.cs b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/PlatformMemoryPool.cs
new file mode 100644
index 0000000..3cdcd2d
--- /dev/null
+++ b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/PlatformMemoryPool.cs
@@ -0,0 +1,105 @@
+/*
+ * 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.
+ */
+
+namespace Apache.Ignite.Core.Impl.Memory
+{
+    using System;
+    using Microsoft.Win32.SafeHandles;
+
+    /// <summary>
+    /// Platform memory pool.
+    /// </summary>
+    public class PlatformMemoryPool : SafeHandleMinusOneIsInvalid
+    {
+        /** First pooled memory chunk. */
+        private PlatformPooledMemory _mem1;
+
+        /** Second pooled memory chunk. */
+        private PlatformPooledMemory _mem2;
+
+        /** Third pooled memory chunk. */
+        private PlatformPooledMemory _mem3;
+
+        /// <summary>
+        /// Constructor.
+        /// </summary>
+        public PlatformMemoryPool() : base(true)
+        {
+            handle = (IntPtr)PlatformMemoryUtils.AllocatePool();
+        }
+
+        /// <summary>
+        /// Allocate memory chunk, optionally pooling it.
+        /// </summary>
+        /// <param name="cap">Minimum capacity.</param>
+        /// <returns>Memory chunk</returns>
+        public PlatformMemory Allocate(int cap)
+        {
+            var memPtr = PlatformMemoryUtils.AllocatePooled(handle.ToInt64(), cap);
+
+            // memPtr == 0 means that we failed to acquire thread-local memory chunk, so fallback to unpooled memory.
+            return memPtr != 0 ? Get(memPtr) : new PlatformUnpooledMemory(PlatformMemoryUtils.AllocateUnpooled(cap));
+        }
+
+        /// <summary>
+        /// Re-allocate existing pool memory chunk.
+        /// </summary>
+        /// <param name="memPtr">Memory pointer.</param>
+        /// <param name="cap">Minimum capacity.</param>
+        public void Reallocate(long memPtr, int cap)
+        {
+            PlatformMemoryUtils.ReallocatePooled(memPtr, cap);
+        }
+
+        /// <summary>
+        /// Release pooled memory chunk.
+        /// </summary>
+        /// <param name="memPtr">Memory pointer.</param>
+        public void Release(long memPtr)
+        {
+            PlatformMemoryUtils.ReleasePooled(memPtr);
+        }
+
+        /// <summary>
+        /// Get pooled memory chunk.
+        /// </summary>
+        /// <param name="memPtr">Memory pointer.</param>
+        /// <returns>Memory chunk.</returns>
+        public PlatformMemory Get(long memPtr) 
+        {
+            long delta = memPtr - handle.ToInt64();
+
+            if (delta == PlatformMemoryUtils.PoolHdrOffMem1) 
+                return _mem1 ?? (_mem1 = new PlatformPooledMemory(this, memPtr));
+            
+            if (delta == PlatformMemoryUtils.PoolHdrOffMem2) 
+                return _mem2 ?? (_mem2 = new PlatformPooledMemory(this, memPtr));
+
+            return _mem3 ?? (_mem3 = new PlatformPooledMemory(this, memPtr));
+        }
+
+        /** <inheritdoc /> */
+        protected override bool ReleaseHandle()
+        {
+            PlatformMemoryUtils.ReleasePool(handle.ToInt64());
+
+            handle = new IntPtr(-1);
+
+            return true;
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/7b61a097/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/PlatformMemoryStream.cs
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/PlatformMemoryStream.cs b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/PlatformMemoryStream.cs
new file mode 100644
index 0000000..7af8392
--- /dev/null
+++ b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/PlatformMemoryStream.cs
@@ -0,0 +1,676 @@
+/*
+ * 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.
+ */
+
+using Apache.Ignite.Core.Impl.Portable.IO;
+
+namespace Apache.Ignite.Core.Impl.Memory
+{
+    using System;
+    using System.IO;
+    using System.Text;
+
+    /// <summary>
+    /// Platform memory stream.
+    /// </summary>
+    public unsafe class PlatformMemoryStream : IPortableStream
+    {
+        /** Length: 1 byte. */
+        protected const int Len1 = 1;
+
+        /** Length: 2 bytes. */
+        protected const int Len2 = 2;
+
+        /** Length: 4 bytes. */
+        protected const int Len4 = 4;
+
+        /** Length: 8 bytes. */
+        protected const int Len8 = 8;
+
+        /** Shift: 2 bytes. */
+        protected const int Shift2 = 1;
+
+        /** Shift: 4 bytes. */
+        protected const int Shift4 = 2;
+
+        /** Shift: 8 bytes. */
+        protected const int Shift8 = 3;
+        
+        /** Underlying memory. */
+        private readonly IPlatformMemory _mem;
+
+        /** Actual data. */
+        protected byte* Data;
+
+        /** CalculateCapacity. */
+        private int _cap;
+
+        /** Position. */
+        private int _pos;
+
+        /** Length. */
+        private int _len;
+
+        /// <summary>
+        /// Constructor.
+        /// </summary>
+        /// <param name="mem">Memory.</param>
+        public PlatformMemoryStream(IPlatformMemory mem)
+        {
+            _mem = mem;
+
+            Data = (byte*)mem.Data;
+            _cap = mem.Capacity;
+            _len = mem.Length;
+        }
+
+        #region WRITE
+
+        /** <inheritdoc /> */
+        public void WriteByte(byte val)
+        {
+            int curPos = EnsureWriteCapacityAndShift(Len1);
+
+            *(Data + curPos) = val;
+        }
+
+        /** <inheritdoc /> */
+        public void WriteByteArray(byte[] val)
+        {
+            fixed (byte* val0 = val)
+            {
+                CopyFromAndShift(val0, val.Length);
+            }
+        }
+
+        /** <inheritdoc /> */
+        public void WriteBool(bool val)
+        {
+            WriteByte(val ? (byte)1 : (byte)0);
+        }
+        
+        /** <inheritdoc /> */
+        public void WriteBoolArray(bool[] val)
+        {
+            fixed (bool* val0 = val)
+            {
+                CopyFromAndShift((byte*)val0, val.Length);
+            }
+        }
+
+        /** <inheritdoc /> */
+        public virtual void WriteShort(short val)
+        {
+            int curPos = EnsureWriteCapacityAndShift(Len2);
+
+            *((short*)(Data + curPos)) = val;
+        }
+
+        /** <inheritdoc /> */
+        public virtual void WriteShortArray(short[] val)
+        {
+            fixed (short* val0 = val)
+            {
+                CopyFromAndShift((byte*)val0, val.Length << Shift2);
+            }
+        }
+
+        /** <inheritdoc /> */
+        public virtual void WriteChar(char val)
+        {
+            int curPos = EnsureWriteCapacityAndShift(Len2);
+
+            *((char*)(Data + curPos)) = val;
+        }
+
+        /** <inheritdoc /> */
+        public virtual void WriteCharArray(char[] val)
+        {
+            fixed (char* val0 = val)
+            {
+                CopyFromAndShift((byte*)val0, val.Length << Shift2);
+            }
+        }
+
+        /** <inheritdoc /> */
+        public virtual void WriteInt(int val)
+        {
+            int curPos = EnsureWriteCapacityAndShift(Len4);
+
+            *((int*)(Data + curPos)) = val;
+        }
+
+        /** <inheritdoc /> */
+        public virtual void WriteInt(int writePos, int val)
+        {
+            EnsureWriteCapacity(writePos + 4);
+
+            *((int*)(Data + writePos)) = val;
+        }
+
+        /** <inheritdoc /> */
+        public virtual void WriteIntArray(int[] val)
+        {
+            fixed (int* val0 = val)
+            {
+                CopyFromAndShift((byte*)val0, val.Length << Shift4);
+            }
+        }
+
+        /** <inheritdoc /> */
+        public virtual void WriteLong(long val)
+        {
+            int curPos = EnsureWriteCapacityAndShift(Len8);
+
+            *((long*)(Data + curPos)) = val;
+        }
+
+        /** <inheritdoc /> */
+        public virtual void WriteLongArray(long[] val)
+        {
+            fixed (long* val0 = val)
+            {
+                CopyFromAndShift((byte*)val0, val.Length << Shift8);
+            }
+        }
+
+        /** <inheritdoc /> */
+        public virtual void WriteFloat(float val)
+        {
+            int curPos = EnsureWriteCapacityAndShift(Len4);
+
+            *((float*)(Data + curPos)) = val;
+        }
+
+        /** <inheritdoc /> */
+        public virtual void WriteFloatArray(float[] val)
+        {
+            fixed (float* val0 = val)
+            {
+                CopyFromAndShift((byte*)val0, val.Length << Shift4);
+            }
+        }
+
+        /** <inheritdoc /> */
+        public virtual void WriteDouble(double val)
+        {
+            int curPos = EnsureWriteCapacityAndShift(Len8);
+
+            *((double*)(Data + curPos)) = val;
+        }
+
+        /** <inheritdoc /> */
+        public virtual void WriteDoubleArray(double[] val)
+        {
+            fixed (double* val0 = val)
+            {
+                CopyFromAndShift((byte*)val0, val.Length << Shift8);
+            }
+        }
+
+        /** <inheritdoc /> */
+        public int WriteString(char* chars, int charCnt, int byteCnt, Encoding enc)
+        {
+            int curPos = EnsureWriteCapacityAndShift(byteCnt);
+
+            return enc.GetBytes(chars, charCnt, Data + curPos, byteCnt);
+        }
+
+        /** <inheritdoc /> */
+        public void Write(byte[] src, int off, int cnt)
+        {
+            fixed (byte* src0 = src)
+            {
+                CopyFromAndShift(src0 + off, cnt);    
+            }
+        }
+
+        /** <inheritdoc /> */
+        public void Write(byte* src, int cnt)
+        {
+            CopyFromAndShift(src, cnt);
+        }
+        
+        #endregion WRITE
+        
+        #region READ
+
+        /** <inheritdoc /> */
+        public byte ReadByte()
+        {
+            int curPos = EnsureReadCapacityAndShift(Len1);
+
+            return *(Data + curPos);
+        }
+
+        /** <inheritdoc /> */
+
+        public byte[] ReadByteArray(int cnt)
+        {
+            int curPos = EnsureReadCapacityAndShift(cnt);
+
+            byte[] res = new byte[cnt];
+
+            fixed (byte* res0 = res)
+            {
+                PlatformMemoryUtils.CopyMemory(Data + curPos, res0, cnt);
+            }
+
+            return res;
+        }
+        
+        /** <inheritdoc /> */
+        public bool ReadBool()
+        {
+            return ReadByte() == 1;
+        }
+
+        /** <inheritdoc /> */
+        public bool[] ReadBoolArray(int cnt)
+        {
+            bool[] res = new bool[cnt];
+
+            fixed (bool* res0 = res)
+            {
+                CopyToAndShift((byte*)res0, cnt);
+            }
+
+            return res;
+        }
+
+        /** <inheritdoc /> */
+        public virtual short ReadShort()
+        {
+            int curPos = EnsureReadCapacityAndShift(Len2);
+
+            return *((short*)(Data + curPos));
+        }
+
+        /** <inheritdoc /> */
+        public virtual short[] ReadShortArray(int cnt)
+        {
+            short[] res = new short[cnt];
+
+            fixed (short* res0 = res)
+            {
+                CopyToAndShift((byte*)res0, cnt << Shift2);
+            }
+
+            return res;
+        }
+
+        /** <inheritdoc /> */
+        public virtual char ReadChar()
+        {
+            int curPos = EnsureReadCapacityAndShift(Len2);
+
+            return *((char*)(Data + curPos));
+        }
+
+        /** <inheritdoc /> */
+        public virtual char[] ReadCharArray(int cnt)
+        {
+            char[] res = new char[cnt];
+
+            fixed (char* res0 = res)
+            {
+                CopyToAndShift((byte*)res0, cnt << Shift2);
+            }
+
+            return res;
+        }
+
+        /** <inheritdoc /> */
+        public virtual int ReadInt()
+        {
+            int curPos = EnsureReadCapacityAndShift(Len4);
+
+            return *((int*)(Data + curPos));
+        }
+        
+        /** <inheritdoc /> */
+        public virtual int[] ReadIntArray(int cnt)
+        {
+            int[] res = new int[cnt];
+
+            fixed (int* res0 = res)
+            {
+                CopyToAndShift((byte*)res0, cnt << Shift4);
+            }
+
+            return res;
+        }
+
+        /** <inheritdoc /> */
+        public virtual long ReadLong()
+        {
+            int curPos = EnsureReadCapacityAndShift(Len8);
+
+            return *((long*)(Data + curPos));
+        }
+        
+        /** <inheritdoc /> */
+        public virtual long[] ReadLongArray(int cnt)
+        {
+            long[] res = new long[cnt];
+
+            fixed (long* res0 = res)
+            {
+                CopyToAndShift((byte*)res0, cnt << Shift8);
+            }
+
+            return res;
+        }
+
+        /** <inheritdoc /> */
+        public virtual float ReadFloat()
+        {
+            int curPos = EnsureReadCapacityAndShift(Len4);
+
+            return *((float*)(Data + curPos));
+        }
+
+        /** <inheritdoc /> */
+        public virtual float[] ReadFloatArray(int cnt)
+        {
+            float[] res = new float[cnt];
+
+            fixed (float* res0 = res)
+            {
+                CopyToAndShift((byte*)res0, cnt << Shift4);
+            }
+
+            return res;
+        }
+
+        /** <inheritdoc /> */
+        public virtual double ReadDouble()
+        {
+            int curPos = EnsureReadCapacityAndShift(Len8);
+
+            return *((double*)(Data + curPos));
+        }
+
+        /** <inheritdoc /> */
+        public virtual double[] ReadDoubleArray(int cnt)
+        {
+            double[] res = new double[cnt];
+
+            fixed (double* res0 = res)
+            {
+                CopyToAndShift((byte*)res0, cnt << Shift8);
+            }
+
+            return res;
+        }
+
+        /** <inheritdoc /> */
+        public void Read(byte[] dest, int off, int cnt)
+        {
+            fixed (byte* dest0 = dest)
+            {
+                Read(dest0 + off, cnt);
+            }
+        }
+
+        /** <inheritdoc /> */
+        public void Read(byte* dest, int cnt)
+        {
+            CopyToAndShift(dest, cnt);
+        }
+
+        #endregion 
+
+        #region MISC
+
+        /// <summary>
+        /// Get cross-platform memory pointer for the stream.
+        /// </summary>
+        public long MemoryPointer
+        {
+            get { return _mem.Pointer; }
+        }
+
+        /// <summary>
+        /// Synchronize stream write opeartions with underlying memory and return current memory pointer.
+        /// <returns>Memory pointer.</returns>
+        /// </summary>
+        public long SynchronizeOutput()
+        {
+            if (_pos > _len)
+                _len = _pos;
+
+            _mem.Length = _len;
+
+            return MemoryPointer;
+        }
+
+        /// <summary>
+        /// Synchronized stream read operations from underlying memory. This is required when 
+        /// </summary>
+        public void SynchronizeInput()
+        {
+            Data = (byte*)_mem.Data;
+            _cap = _mem.Capacity;
+            _len = _mem.Length;
+        }
+
+        /// <summary>
+        /// Reset stream state. Sets both position and length to 0.
+        /// </summary>
+        public void Reset()
+        {
+            _pos = 0;
+        }
+
+        /// <summary>
+        /// Reset stream state as if it was just created.
+        /// </summary>
+        public void Reuse()
+        {
+            Data = (byte*)_mem.Data;
+            _cap = _mem.Capacity;
+            _len = _mem.Length;
+            _pos = 0;
+        }
+
+        /** <inheritdoc /> */
+        public int Seek(int offset, SeekOrigin origin)
+        {
+            int newPos;
+
+            switch (origin)
+            {
+                case SeekOrigin.Begin:
+                    {
+                        newPos = offset;
+
+                        break;
+                    }
+
+                case SeekOrigin.Current:
+                    {
+                        newPos = _pos + offset;
+
+                        break;
+                    }
+
+                default:
+                    throw new ArgumentException("Unsupported seek origin: " + origin);
+            }
+
+            if (newPos < 0)
+                throw new ArgumentException("Seek before origin: " + newPos);
+
+            EnsureWriteCapacity(newPos);
+
+            _pos = newPos;
+
+            return _pos;
+        }
+
+        /// <summary>
+        /// Ensure capacity for write and shift position.
+        /// </summary>
+        /// <param name="cnt">Bytes count.</param>
+        /// <returns>Position before shift.</returns>
+        protected int EnsureWriteCapacityAndShift(int cnt)
+        {
+            int curPos = _pos;
+
+            int newPos = _pos + cnt;
+
+            EnsureWriteCapacity(newPos);
+
+            _pos = newPos;
+
+            return curPos;
+        }
+
+        /// <summary>
+        /// Ensure write capacity.
+        /// </summary>
+        /// <param name="reqCap">Required capacity.</param>
+        protected void EnsureWriteCapacity(int reqCap)
+        {
+            if (reqCap > _cap)
+            {
+                reqCap = CalculateCapacity(_cap, reqCap);
+
+                _mem.Reallocate(reqCap);
+
+                Data = (byte*)_mem.Data;
+                _cap = _mem.Capacity;
+            }
+        }
+
+        /// <summary>
+        /// Ensure capacity for read and shift position.
+        /// </summary>
+        /// <param name="cnt">Bytes count.</param>
+        /// <returns>Position before shift.</returns>
+        protected int EnsureReadCapacityAndShift(int cnt)
+        {
+            int curPos = _pos;
+
+            if (_len - _pos < cnt)
+                throw new EndOfStreamException("Not enough data in stream [expected=" + cnt +
+                    ", remaining=" + (_len - _pos) + ']');
+
+            _pos += cnt;
+
+            return curPos;
+        }
+
+        /// <summary>
+        /// Copy (read) some data into destination and shift the stream forward.
+        /// </summary>
+        /// <param name="dest">Destination.</param>
+        /// <param name="cnt">Bytes count.</param>
+        private void CopyToAndShift(byte* dest, int cnt)
+        {
+            int curPos = EnsureReadCapacityAndShift(cnt);
+
+            PlatformMemoryUtils.CopyMemory(Data + curPos, dest, cnt);
+        }
+
+        /// <summary>
+        /// Copy (write) some data from source and shift the stream forward.
+        /// </summary>
+        /// <param name="src">Source.</param>
+        /// <param name="cnt">Bytes count.</param>
+        private void CopyFromAndShift(byte* src, int cnt)
+        {
+            int curPos = EnsureWriteCapacityAndShift(cnt);
+
+            PlatformMemoryUtils.CopyMemory(src, Data + curPos, cnt);
+        }
+
+        /// <summary>
+        /// Calculate new capacity.
+        /// </summary>
+        /// <param name="curCap">Current capacity.</param>
+        /// <param name="reqCap">Required capacity.</param>
+        /// <returns>New capacity.</returns>
+        private static int CalculateCapacity(int curCap, int reqCap)
+        {
+            int newCap;
+
+            if (reqCap < 256)
+                newCap = 256;
+            else
+            {
+                newCap = curCap << 1;
+
+                if (newCap < reqCap)
+                    newCap = reqCap;
+            }
+
+            return newCap;
+        }
+
+        /** <inheritdoc /> */
+        public int Position
+        {
+            get { return _pos; }
+        }
+
+        /** <inheritdoc /> */
+        public int Remaining()
+        {
+            return _len - _pos;
+        }
+
+        /** <inheritdoc /> */
+        public void Dispose()
+        {
+            SynchronizeOutput();
+
+            _mem.Release();
+        }
+        
+        #endregion
+
+        #region ARRAYS
+
+        /** <inheritdoc /> */
+        public byte[] Array()
+        {
+            return ArrayCopy();
+        }
+
+        /** <inheritdoc /> */
+        public byte[] ArrayCopy()
+        {
+            byte[] res = new byte[_mem.Length];
+
+            fixed (byte* res0 = res)
+            {
+                PlatformMemoryUtils.CopyMemory(Data, res0, res.Length);
+            }
+
+            return res;
+        }
+
+        /** <inheritdoc /> */
+        public bool IsSameArray(byte[] arr)
+        {
+            return false;
+        }
+
+        #endregion
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/7b61a097/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/PlatformMemoryUtils.cs
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/PlatformMemoryUtils.cs b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/PlatformMemoryUtils.cs
new file mode 100644
index 0000000..fc942a0
--- /dev/null
+++ b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/PlatformMemoryUtils.cs
@@ -0,0 +1,462 @@
+/*
+ * 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.
+ */
+
+namespace Apache.Ignite.Core.Impl.Memory
+{
+    using System;
+    using System.Diagnostics.CodeAnalysis;
+    using System.Reflection;
+    using System.Runtime.InteropServices;
+    
+    /// <summary>
+    /// Utility methods for platform memory management.
+    /// </summary>
+    public static unsafe class PlatformMemoryUtils
+    {
+        #region CONSTANTS
+
+        /** Header length. */
+        private const int PoolHdrLen = 64;
+
+        /** Pool header offset: first memory chunk. */
+        internal const int PoolHdrOffMem1 = 0;
+
+        /** Pool header offset: second memory chunk. */
+        internal const int PoolHdrOffMem2 = 20;
+
+        /** Pool header offset: third memory chunk. */
+        internal const int PoolHdrOffMem3 = 40;
+
+        /** Memory chunk header length. */
+        private const int MemHdrLen = 20;
+
+        /** Offset: capacity. */
+        private const int MemHdrOffCap = 8;
+
+        /** Offset: length. */
+        private const int MemHdrOffLen = 12;
+
+        /** Offset: flags. */
+        private const int MemHdrOffFlags = 16;
+
+        /** Flag: external. */
+        private const int FlagExt = 0x1;
+
+        /** Flag: pooled. */
+        private const int FlagPooled = 0x2;
+
+        /** Flag: whether this pooled memory chunk is acquired. */
+        private const int FlagAcquired = 0x4;
+
+        #endregion
+
+        #region COMMON
+
+        /// <summary>
+        /// Gets data pointer for the given memory chunk.
+        /// </summary>
+        /// <param name="memPtr">Memory pointer.</param>
+        /// <returns>Data pointer.</returns>
+        public static long Data(long memPtr)
+        {
+            return *((long*)memPtr);
+        }
+
+        /// <summary>
+        /// Gets capacity for the given memory chunk.
+        /// </summary>
+        /// <param name="memPtr">Memory pointer.</param>
+        /// <returns>CalculateCapacity.</returns>
+        public static int Capacity(long memPtr) 
+        {
+            return *((int*)(memPtr + MemHdrOffCap));
+        }
+
+        /// <summary>
+        /// Sets capacity for the given memory chunk.
+        /// </summary>
+        /// <param name="memPtr">Memory pointer.</param>
+        /// <param name="cap">CalculateCapacity.</param>
+        public static void Capacity(long memPtr, int cap) 
+        {
+            *((int*)(memPtr + MemHdrOffCap)) = cap;
+        }
+
+        /// <summary>
+        /// Gets length for the given memory chunk.
+        /// </summary>
+        /// <param name="memPtr">Memory pointer.</param>
+        /// <returns>Length.</returns>
+        public static int Length(long memPtr) 
+        {
+            return *((int*)(memPtr + MemHdrOffLen));
+        }
+
+        /// <summary>
+        /// Sets length for the given memory chunk.
+        /// </summary>
+        /// <param name="memPtr">Memory pointer.</param>
+        /// <param name="len">Length.</param>
+        public static void Length(long memPtr, int len) 
+        {
+            *((int*)(memPtr + MemHdrOffLen)) = len;
+        }
+
+        /// <summary>
+        /// Gets flags for the given memory chunk.
+        /// </summary>
+        /// <param name="memPtr">Memory pointer.</param>
+        /// <returns>Flags.</returns>
+        public static int Flags(long memPtr) 
+        {
+            return *((int*)(memPtr + MemHdrOffFlags));
+        }
+
+        /// <summary>
+        /// Sets flags for the given memory chunk.
+        /// </summary>
+        /// <param name="memPtr">Memory pointer.</param>
+        /// <param name="flags">Flags.</param>
+        public static void Flags(long memPtr, int flags) 
+        {
+            *((int*)(memPtr + MemHdrOffFlags)) = flags;
+        }
+
+        /// <summary>
+        /// Check whether this memory chunk is external.
+        /// </summary>
+        /// <param name="memPtr">Memory pointer.</param>
+        /// <returns><c>True</c> if owned by Java.</returns>
+        public static bool IsExternal(long memPtr) 
+        {
+            return IsExternal(Flags(memPtr));
+        }
+
+        /// <summary>
+        /// Check whether flags denote that this memory chunk is external.
+        /// </summary>
+        /// <param name="flags">Flags.</param>
+        /// <returns><c>True</c> if owned by Java.</returns>
+        public static bool IsExternal(int flags) 
+        {
+            return (flags & FlagExt) != FlagExt;
+        }
+
+        /// <summary>
+        /// Check whether this memory chunk is pooled.
+        /// </summary>
+        /// <param name="memPtr">Memory pointer.</param>
+        /// <returns><c>True</c> if pooled.</returns>
+        public static bool IsPooled(long memPtr) 
+        {
+            return IsPooled(Flags(memPtr));
+        }
+
+        /// <summary>
+        /// Check whether flags denote pooled memory chunk.
+        /// </summary>
+        /// <param name="flags">Flags.</param>
+        /// <returns><c>True</c> if pooled.</returns>
+        public static bool IsPooled(int flags) 
+        {
+            return (flags & FlagPooled) != 0;
+        }
+
+        /// <summary>
+        /// Check whether this memory chunk is pooled and acquired.
+        /// </summary>
+        /// <param name="memPtr">Memory pointer.</param>
+        /// <returns><c>True</c> if acquired.</returns>
+        public static bool IsAcquired(long memPtr)
+        {
+            return IsAcquired(Flags(memPtr));
+        }
+
+        /// <summary>
+        /// Check whether flags denote pooled and acquired memory chunk.
+        /// </summary>
+        /// <param name="flags">Flags.</param>
+        /// <returns><c>True</c> if acquired.</returns>
+        public static bool IsAcquired(int flags)
+        {
+            return (flags & FlagAcquired) != 0;
+        }
+
+        #endregion
+
+        #region UNPOOLED MEMORY 
+
+        /// <summary>
+        /// Allocate unpooled memory chunk.
+        /// </summary>
+        /// <param name="cap">Minimum capacity.</param>
+        /// <returns>New memory pointer.</returns>
+        public static long AllocateUnpooled(int cap)
+        {
+            long memPtr = Marshal.AllocHGlobal(MemHdrLen).ToInt64();
+            long dataPtr = Marshal.AllocHGlobal(cap).ToInt64();
+
+            *((long*)memPtr) = dataPtr;
+            *((int*)(memPtr + MemHdrOffCap)) = cap;
+            *((int*)(memPtr + MemHdrOffLen)) = 0;
+            *((int*)(memPtr + MemHdrOffFlags)) = FlagExt;
+
+            return memPtr;
+        }
+
+
+        /// <summary>
+        /// Reallocate unpooled memory chunk.
+        /// </summary>
+        /// <param name="memPtr">Memory pointer.</param>
+        /// <param name="cap">Minimum capacity.</param>
+        /// <returns></returns>
+        public static void ReallocateUnpooled(long memPtr, int cap)
+        {
+            long dataPtr = Data(memPtr);
+
+            long newDataPtr = Marshal.ReAllocHGlobal((IntPtr)dataPtr, (IntPtr)cap).ToInt64();
+
+            if (dataPtr != newDataPtr)
+                *((long*)memPtr) = newDataPtr; // Write new data address if needed.
+
+            *((int*)(memPtr + MemHdrOffCap)) = cap; // Write new capacity.
+        }
+
+        /// <summary>
+        /// Release unpooled memory chunk.
+        /// </summary>
+        /// <param name="memPtr">Memory pointer.</param>
+        public static void ReleaseUnpooled(long memPtr) 
+        {
+            Marshal.FreeHGlobal((IntPtr)Data(memPtr));
+            Marshal.FreeHGlobal((IntPtr)memPtr);
+        }
+
+        #endregion
+
+        #region POOLED MEMORY
+
+        /// <summary>
+        /// Allocate pool memory.
+        /// </summary>
+        /// <returns>Pool pointer.</returns>
+        public static long AllocatePool()
+        {
+            // 1. Allocate memory.
+            long poolPtr = Marshal.AllocHGlobal((IntPtr)PoolHdrLen).ToInt64();
+
+            // 2. Clear memory.
+            for (int i = 0; i < PoolHdrLen; i += 8)
+                *((long*)(poolPtr + i)) = 0;
+
+            // 3. Set flags for memory chunks.
+            Flags(poolPtr + PoolHdrOffMem1, FlagExt | FlagPooled);
+            Flags(poolPtr + PoolHdrOffMem2, FlagExt | FlagPooled);
+            Flags(poolPtr + PoolHdrOffMem3, FlagExt | FlagPooled);
+
+            return poolPtr;
+        }
+
+        /// <summary>
+        /// Release pool memory.
+        /// </summary>
+        /// <param name="poolPtr">Pool pointer.</param>
+        public static void ReleasePool(long poolPtr)
+        {
+            // Clean predefined memory chunks.
+            long mem = *((long*)(poolPtr + PoolHdrOffMem1));
+
+            if (mem != 0)
+                Marshal.FreeHGlobal((IntPtr)mem);
+
+            mem = *((long*)(poolPtr + PoolHdrOffMem2));
+
+            if (mem != 0)
+                Marshal.FreeHGlobal((IntPtr)mem);
+
+            mem = *((long*)(poolPtr + PoolHdrOffMem3));
+
+            if (mem != 0)
+                Marshal.FreeHGlobal((IntPtr)mem);
+
+            // Clean pool chunk.
+            Marshal.FreeHGlobal((IntPtr)poolPtr);
+        }
+
+        /// <summary>
+        /// Allocate pooled memory chunk.
+        /// </summary>
+        /// <param name="poolPtr">Pool pointer.</param>
+        /// <param name="cap">CalculateCapacity.</param>
+        /// <returns>Memory pointer or <c>0</c> in case there are no free memory chunks in the pool.</returns>
+        public static long AllocatePooled(long poolPtr, int cap)
+        {
+            long memPtr = poolPtr + PoolHdrOffMem1;
+
+            if (IsAcquired(memPtr))
+            {
+                memPtr = poolPtr + PoolHdrOffMem2;
+
+                if (IsAcquired(memPtr))
+                {
+                    memPtr = poolPtr + PoolHdrOffMem3;
+
+                    if (IsAcquired(memPtr))
+                        memPtr = 0;
+                    else
+                        AllocatePooled0(memPtr, cap);
+                }
+                else
+                    AllocatePooled0(memPtr, cap);
+            }
+            else
+                AllocatePooled0(memPtr, cap);
+
+            return memPtr;
+        }
+
+        /// <summary>
+        /// Internal pooled memory chunk allocation routine.
+        /// </summary>
+        /// <param name="memPtr">Memory pointer.</param>
+        /// <param name="cap">CalculateCapacity.</param>
+        private static void AllocatePooled0(long memPtr, int cap) 
+        {
+            long data = *((long*)memPtr);
+
+            if (data == 0) {
+                // First allocation of the chunk.
+                data = Marshal.AllocHGlobal(cap).ToInt64();
+
+                *((long*)memPtr) = data;
+                *((int*)(memPtr + MemHdrOffCap)) = cap;
+            }
+            else {
+                // Ensure that we have enough capacity.
+                int curCap = Capacity(memPtr);
+
+                if (cap > curCap) {
+                    data = Marshal.ReAllocHGlobal((IntPtr)data, (IntPtr)cap).ToInt64();
+
+                    *((long*)memPtr) = data;
+                    *((int*)(memPtr + MemHdrOffCap)) = cap;
+                }
+            }
+
+            Flags(memPtr, FlagExt | FlagPooled | FlagAcquired);
+        }
+
+        /// <summary>
+        /// Reallocate pooled memory chunk.
+        /// </summary>
+        /// <param name="memPtr">Memory pointer.</param>
+        /// <param name="cap">Minimum capacity.</param>
+        public static void ReallocatePooled(long memPtr, int cap) 
+        {
+            long data = *((long*)memPtr);
+
+            int curCap = Capacity(memPtr);
+
+            if (cap > curCap) {
+                data = Marshal.ReAllocHGlobal((IntPtr)data, (IntPtr)cap).ToInt64();
+
+                *((long*)memPtr) = data;
+                *((int*)(memPtr + MemHdrOffCap)) = cap;
+            }
+        }
+
+        /// <summary>
+        /// Release pooled memory chunk.
+        /// </summary>
+        /// <param name="memPtr">Memory pointer.</param>
+        public static void ReleasePooled(long memPtr) 
+        {
+            Flags(memPtr, Flags(memPtr) ^ FlagAcquired);
+        }
+
+        #endregion
+
+        #region MEMCPY
+
+        /** Array copy delegate. */
+        private delegate void MemCopy(byte* a1, byte* a2, int len);
+
+        /** memcpy function handle. */
+        private static readonly MemCopy Memcpy;
+
+        /** Whether src and dest arguments are inverted. */
+        private static readonly bool MemcpyInverted;
+
+        /// <summary>
+        /// Static initializer.
+        /// </summary>
+        [SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")]
+        static PlatformMemoryUtils()
+        {
+            Type type = typeof(Buffer);
+
+            const BindingFlags flags = BindingFlags.Static | BindingFlags.NonPublic;
+            Type[] paramTypes = { typeof(byte*), typeof(byte*), typeof(int) };
+
+            // Assume .Net 4.5.
+            MethodInfo mthd = type.GetMethod("Memcpy", flags, null, paramTypes, null);
+
+            MemcpyInverted = true;
+
+            if (mthd == null)
+            {
+                // Assume .Net 4.0.
+                mthd = type.GetMethod("memcpyimpl", flags, null, paramTypes, null);
+
+                MemcpyInverted = false;
+
+                if (mthd == null)
+                    throw new InvalidOperationException("Unable to get memory copy function delegate.");
+            }
+
+            Memcpy = (MemCopy)Delegate.CreateDelegate(typeof(MemCopy), mthd);
+        }
+
+        /// <summary>
+        /// Unsafe memory copy routine.
+        /// </summary>
+        /// <param name="src">Source.</param>
+        /// <param name="dest">Destination.</param>
+        /// <param name="len">Length.</param>
+        public static void CopyMemory(void* src, void* dest, int len)
+        {
+            CopyMemory((byte*)src, (byte*)dest, len);
+        }
+
+        /// <summary>
+        /// Unsafe memory copy routine.
+        /// </summary>
+        /// <param name="src">Source.</param>
+        /// <param name="dest">Destination.</param>
+        /// <param name="len">Length.</param>
+        public static void CopyMemory(byte* src, byte* dest, int len)
+        {
+            if (MemcpyInverted)
+                Memcpy.Invoke(dest, src, len);
+            else
+                Memcpy.Invoke(src, dest, len);
+        }
+
+        #endregion
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/7b61a097/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/PlatformPooledMemory.cs
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/PlatformPooledMemory.cs b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/PlatformPooledMemory.cs
new file mode 100644
index 0000000..7709ca4
--- /dev/null
+++ b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/PlatformPooledMemory.cs
@@ -0,0 +1,70 @@
+/*
+ * 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.
+ */
+
+namespace Apache.Ignite.Core.Impl.Memory
+{
+    /// <summary>
+    /// Platform pooled memory chunk.
+    /// </summary>
+    internal class PlatformPooledMemory : PlatformMemory
+    {
+        /** Pool. */
+        private readonly PlatformMemoryPool _pool;
+
+        /** Cached stream. */
+        private PlatformMemoryStream _stream;
+
+        /// <summary>
+        /// Constructor.
+        /// </summary>
+        /// <param name="pool">Pool.</param>
+        /// <param name="memPtr">Memory pointer.</param>
+        public PlatformPooledMemory(PlatformMemoryPool pool, long memPtr) : base(memPtr)
+        {
+            this._pool = pool;
+        }
+
+        /** <inheritdoc /> */
+        public override PlatformMemoryStream Stream()
+        {
+            if (_stream == null)
+                _stream = base.Stream();
+            else
+                _stream.Reuse();
+
+            return _stream;
+        }
+
+        /** <inheritdoc /> */
+        public override void Reallocate(int cap)
+        {
+            // Try doubling capacity to avoid excessive allocations.
+            int doubledCap = PlatformMemoryUtils.Capacity(MemPtr) << 1;
+
+            if (doubledCap > cap)
+                cap = doubledCap;
+
+            _pool.Reallocate(MemPtr, cap);
+        }
+
+        /** <inheritdoc /> */
+        public override void Release()
+        {
+            _pool.Release(MemPtr); // Return to the pool.
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/7b61a097/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/PlatformRawMemory.cs
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/PlatformRawMemory.cs b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/PlatformRawMemory.cs
new file mode 100644
index 0000000..6de9f43
--- /dev/null
+++ b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/PlatformRawMemory.cs
@@ -0,0 +1,88 @@
+/*
+ * 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.
+ */
+
+namespace Apache.Ignite.Core.Impl.Memory
+{
+    using System;
+
+    /// <summary>
+    /// Non-resizeable raw memory chunk without metadata header.
+    /// </summary>
+    public class PlatformRawMemory : IPlatformMemory
+    {
+        /** */
+        private readonly long _memPtr;
+
+        /** */
+        private readonly int _size;
+
+        /// <summary>
+        /// Initializes a new instance of the <see cref="PlatformRawMemory"/> class.
+        /// </summary>
+        /// <param name="memPtr">Heap pointer.</param>
+        /// <param name="size">Size.</param>
+        public unsafe PlatformRawMemory(void* memPtr, int size)
+        {
+            _memPtr = (long) memPtr;
+            _size = size;
+        }
+
+        /** <inheritdoc /> */
+        public PlatformMemoryStream Stream()
+        {
+            return BitConverter.IsLittleEndian ? new PlatformMemoryStream(this) :
+                new PlatformBigEndianMemoryStream(this);
+        }
+
+        /** <inheritdoc /> */
+        public long Pointer
+        {
+            get { throw new NotSupportedException(); }
+        }
+
+        /** <inheritdoc /> */
+        public long Data
+        {
+            get { return _memPtr; }
+        }
+
+        /** <inheritdoc /> */
+        public int Capacity
+        {
+            get { return _size; }
+        }
+
+        /** <inheritdoc /> */
+        public int Length
+        {
+            get { return _size; }
+            set { throw new NotSupportedException(); }
+        }
+
+        /** <inheritdoc /> */
+        public void Reallocate(int cap)
+        {
+            throw new NotSupportedException();
+        }
+
+        /** <inheritdoc /> */
+        public void Release()
+        {
+            throw new NotSupportedException();
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ignite/blob/7b61a097/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/PlatformUnpooledMemory.cs
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/PlatformUnpooledMemory.cs b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/PlatformUnpooledMemory.cs
new file mode 100644
index 0000000..26c1bc1
--- /dev/null
+++ b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/PlatformUnpooledMemory.cs
@@ -0,0 +1,52 @@
+/*
+ * 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.
+ */
+
+namespace Apache.Ignite.Core.Impl.Memory
+{
+    /// <summary>
+    /// Platform unpooled memory chunk.
+    /// </summary>
+    internal class PlatformUnpooledMemory : PlatformMemory
+    {
+        /// <summary>
+        /// Constructor.
+        /// </summary>
+        /// <param name="memPtr">Memory pointer.</param>
+        public PlatformUnpooledMemory(long memPtr) : base(memPtr)
+        {
+            // No-op.
+        }
+
+        /** <inheritdoc /> */
+        public override void Reallocate(int cap)
+        {
+            // Try doubling capacity to avoid excessive allocations.
+            int doubledCap = ((PlatformMemoryUtils.Capacity(MemPtr) + 16) << 1) - 16;
+
+            if (doubledCap > cap)
+                cap = doubledCap;
+
+            PlatformMemoryUtils.ReallocateUnpooled(MemPtr, cap);
+        }
+
+        /** <inheritdoc /> */
+        public override void Release()
+        {
+            PlatformMemoryUtils.ReleaseUnpooled(MemPtr);
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/7b61a097/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Portable/Io/IPortableStream.cs
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Portable/Io/IPortableStream.cs b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Portable/Io/IPortableStream.cs
new file mode 100644
index 0000000..8111117
--- /dev/null
+++ b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Portable/Io/IPortableStream.cs
@@ -0,0 +1,320 @@
+/*
+ * 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.
+ */
+
+
+namespace Apache.Ignite.Core.Impl.Portable.IO
+{
+    using System;
+    using System.IO;
+    using System.Text;
+
+    /// <summary>
+    /// Stream capable of working with portable objects.
+    /// </summary>
+    [CLSCompliant(false)]
+    public unsafe interface IPortableStream : IDisposable
+    {
+        /// <summary>
+        /// Write bool.
+        /// </summary>
+        /// <param name="val">Bool value.</param>
+        void WriteBool(bool val);
+
+        /// <summary>
+        /// Read bool.
+        /// </summary>
+        /// <returns>Bool value.</returns>
+        bool ReadBool();
+
+        /// <summary>
+        /// Write bool array.
+        /// </summary>
+        /// <param name="val">Bool array.</param>
+        void WriteBoolArray(bool[] val);
+
+        /// <summary>
+        /// Read bool array.
+        /// </summary>
+        /// <param name="cnt">Count.</param>
+        /// <returns>Bool array.</returns>
+        bool[] ReadBoolArray(int cnt);
+
+        /// <summary>
+        /// Write byte.
+        /// </summary>
+        /// <param name="val">Byte value.</param>
+        void WriteByte(byte val);
+
+        /// <summary>
+        /// Read byte.
+        /// </summary>
+        /// <returns>Byte value.</returns>
+        byte ReadByte();
+
+        /// <summary>
+        /// Write byte array.
+        /// </summary>
+        /// <param name="val">Byte array.</param>
+        void WriteByteArray(byte[] val);
+
+        /// <summary>
+        /// Read byte array.
+        /// </summary>
+        /// <param name="cnt">Count.</param>
+        /// <returns>Byte array.</returns>
+        byte[] ReadByteArray(int cnt);
+
+        /// <summary>
+        /// Write short.
+        /// </summary>
+        /// <param name="val">Short value.</param>
+        void WriteShort(short val);
+
+        /// <summary>
+        /// Read short.
+        /// </summary>
+        /// <returns>Short value.</returns>
+        short ReadShort();
+
+        /// <summary>
+        /// Write short array.
+        /// </summary>
+        /// <param name="val">Short array.</param>
+        void WriteShortArray(short[] val);
+
+        /// <summary>
+        /// Read short array.
+        /// </summary>
+        /// <param name="cnt">Count.</param>
+        /// <returns>Short array.</returns>
+        short[] ReadShortArray(int cnt);
+
+        /// <summary>
+        /// Write char.
+        /// </summary>
+        /// <param name="val">Char value.</param>
+        void WriteChar(char val);
+
+        /// <summary>
+        /// Read char.
+        /// </summary>
+        /// <returns>Char value.</returns>
+        char ReadChar();
+
+        /// <summary>
+        /// Write char array.
+        /// </summary>
+        /// <param name="val">Char array.</param>
+        void WriteCharArray(char[] val);
+
+        /// <summary>
+        /// Read char array.
+        /// </summary>
+        /// <param name="cnt">Count.</param>
+        /// <returns>Char array.</returns>
+        char[] ReadCharArray(int cnt);
+
+        /// <summary>
+        /// Write int.
+        /// </summary>
+        /// <param name="val">Int value.</param>
+        void WriteInt(int val);
+
+        /// <summary>
+        /// Write int to specific position.
+        /// </summary>
+        /// <param name="writePos">Position.</param>
+        /// <param name="val">Value.</param>
+        void WriteInt(int writePos, int val);
+
+        /// <summary>
+        /// Read int.
+        /// </summary>
+        /// <returns>Int value.</returns>
+        int ReadInt();
+
+        /// <summary>
+        /// Write int array.
+        /// </summary>
+        /// <param name="val">Int array.</param>
+        void WriteIntArray(int[] val);
+
+        /// <summary>
+        /// Read int array.
+        /// </summary>
+        /// <param name="cnt">Count.</param>
+        /// <returns>Int array.</returns>
+        int[] ReadIntArray(int cnt);
+        
+        /// <summary>
+        /// Write long.
+        /// </summary>
+        /// <param name="val">Long value.</param>
+        void WriteLong(long val);
+
+        /// <summary>
+        /// Read long.
+        /// </summary>
+        /// <returns>Long value.</returns>
+        long ReadLong();
+
+        /// <summary>
+        /// Write long array.
+        /// </summary>
+        /// <param name="val">Long array.</param>
+        void WriteLongArray(long[] val);
+
+        /// <summary>
+        /// Read long array.
+        /// </summary>
+        /// <param name="cnt">Count.</param>
+        /// <returns>Long array.</returns>
+        long[] ReadLongArray(int cnt);
+
+        /// <summary>
+        /// Write float.
+        /// </summary>
+        /// <param name="val">Float value.</param>
+        void WriteFloat(float val);
+
+        /// <summary>
+        /// Read float.
+        /// </summary>
+        /// <returns>Float value.</returns>
+        float ReadFloat();
+
+        /// <summary>
+        /// Write float array.
+        /// </summary>
+        /// <param name="val">Float array.</param>
+        void WriteFloatArray(float[] val);
+
+        /// <summary>
+        /// Read float array.
+        /// </summary>
+        /// <param name="cnt">Count.</param>
+        /// <returns>Float array.</returns>
+        float[] ReadFloatArray(int cnt);
+
+        /// <summary>
+        /// Write double.
+        /// </summary>
+        /// <param name="val">Double value.</param>
+        void WriteDouble(double val);
+
+        /// <summary>
+        /// Read double.
+        /// </summary>
+        /// <returns>Double value.</returns>
+        double ReadDouble();
+
+        /// <summary>
+        /// Write double array.
+        /// </summary>
+        /// <param name="val">Double array.</param>
+        void WriteDoubleArray(double[] val);
+
+        /// <summary>
+        /// Read double array.
+        /// </summary>
+        /// <param name="cnt">Count.</param>
+        /// <returns>Double array.</returns>
+        double[] ReadDoubleArray(int cnt);
+
+        /// <summary>
+        /// Write string.
+        /// </summary>
+        /// <param name="chars">Characters.</param>
+        /// <param name="charCnt">Char count.</param>
+        /// <param name="byteCnt">Byte count.</param>
+        /// <param name="encoding">Encoding.</param>
+        /// <returns>Amounts of bytes written.</returns>
+        int WriteString(char* chars, int charCnt, int byteCnt, Encoding encoding);
+
+        /// <summary>
+        /// Write arbitrary data.
+        /// </summary>
+        /// <param name="src">Source array.</param>
+        /// <param name="off">Offset</param>
+        /// <param name="cnt">Count.</param>
+        void Write(byte[] src, int off, int cnt);
+
+        /// <summary>
+        /// Read arbitrary data.
+        /// </summary>
+        /// <param name="dest">Destination array.</param>
+        /// <param name="off">Offset.</param>
+        /// <param name="cnt">Count.</param>
+        /// <returns>Amount of bytes read.</returns>
+        void Read(byte[] dest, int off, int cnt);
+
+        /// <summary>
+        /// Write arbitrary data.
+        /// </summary>
+        /// <param name="src">Source.</param>
+        /// <param name="cnt">Count.</param>
+        void Write(byte* src, int cnt);
+
+        /// <summary>
+        /// Read arbitrary data.
+        /// </summary>
+        /// <param name="dest">Destination.</param>
+        /// <param name="cnt">Count.</param>
+        void Read(byte* dest, int cnt);
+        
+        /// <summary>
+        /// Position.
+        /// </summary>
+        int Position
+        {
+            get;
+        }
+
+        /// <summary>
+        /// Gets remaining bytes in the stream.
+        /// </summary>
+        /// <returns>Remaining bytes.</returns>
+        int Remaining();
+
+        /// <summary>
+        /// Gets underlying array, avoiding copying if possible.
+        /// </summary>
+        /// <returns>Underlying array.</returns>
+        byte[] Array();
+
+        /// <summary>
+        /// Gets underlying data in a new array.
+        /// </summary>
+        /// <returns>New array with data.</returns>
+        byte[] ArrayCopy();
+        
+        /// <summary>
+        /// Check whether array passed as argument is the same as the stream hosts.
+        /// </summary>
+        /// <param name="arr">Array.</param>
+        /// <returns><c>True</c> if they are same.</returns>
+        bool IsSameArray(byte[] arr);
+
+        /// <summary>
+        /// Seek to the given positoin.
+        /// </summary>
+        /// <param name="offset">Offset.</param>
+        /// <param name="origin">Seek origin.</param>
+        /// <returns>Position.</returns>
+        int Seek(int offset, SeekOrigin origin);
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/7b61a097/modules/platform/src/main/dotnet/Apache.Ignite.Core/Properties/AssemblyInfo.cs
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Properties/AssemblyInfo.cs b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Properties/AssemblyInfo.cs
index 9d99a3d..4127523 100644
--- a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Properties/AssemblyInfo.cs
+++ b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Properties/AssemblyInfo.cs
@@ -15,7 +15,9 @@
  * limitations under the License.
  */
 
+using System;
 using System.Reflection;
+using System.Runtime.CompilerServices;
 using System.Runtime.InteropServices;
 
 [assembly: AssemblyTitle("Apache.Ignite.Core")]
@@ -33,3 +35,7 @@ using System.Runtime.InteropServices;
 
 [assembly: AssemblyVersion("1.4.1.0")]
 [assembly: AssemblyFileVersion("1.4.1.0")]
+
+[assembly: CLSCompliant(true)]
+
+[assembly: InternalsVisibleTo("Apache.Ignite.Core.Tests")]
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ignite/blob/7b61a097/modules/platform/src/main/dotnet/Apache.Ignite.sln.DotSettings
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/dotnet/Apache.Ignite.sln.DotSettings b/modules/platform/src/main/dotnet/Apache.Ignite.sln.DotSettings
new file mode 100644
index 0000000..187a909
--- /dev/null
+++ b/modules/platform/src/main/dotnet/Apache.Ignite.sln.DotSettings
@@ -0,0 +1,4 @@
+<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
+	<s:Boolean x:Key="/Default/CodeStyle/CSharpUsing/AddImportsToDeepestScope/@EntryValue">True</s:Boolean>
+	
+	<s:Boolean x:Key="/Default/CodeStyle/CSharpUsing/QualifiedUsingAtNestedScope/@EntryValue">True</s:Boolean></wpf:ResourceDictionary>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ignite/blob/7b61a097/modules/platform/src/test/dotnet/Apache.Ignite.Core.Tests/Apache.Ignite.Core.Tests.csproj
----------------------------------------------------------------------
diff --git a/modules/platform/src/test/dotnet/Apache.Ignite.Core.Tests/Apache.Ignite.Core.Tests.csproj b/modules/platform/src/test/dotnet/Apache.Ignite.Core.Tests/Apache.Ignite.Core.Tests.csproj
index 21dc6ce..9e8f9d1 100644
--- a/modules/platform/src/test/dotnet/Apache.Ignite.Core.Tests/Apache.Ignite.Core.Tests.csproj
+++ b/modules/platform/src/test/dotnet/Apache.Ignite.Core.Tests/Apache.Ignite.Core.Tests.csproj
@@ -31,6 +31,13 @@
     <PlatformTarget>x86</PlatformTarget>
     <OutputPath>bin\x86\Release\</OutputPath>
   </PropertyGroup>
+  <PropertyGroup>
+    <SignAssembly>true</SignAssembly>
+  </PropertyGroup>
+  <PropertyGroup>
+    <AssemblyOriginatorKeyFile>
+    </AssemblyOriginatorKeyFile>
+  </PropertyGroup>
   <ItemGroup>
     <Reference Include="nunit-console-runner">
       <HintPath>..\libs\nunit-console-runner.dll</HintPath>
@@ -44,6 +51,7 @@
   </ItemGroup>
   <ItemGroup>
     <Compile Include="IgnitionTest.cs" />
+    <Compile Include="Memory\InteropMemoryTest.cs" />
     <Compile Include="Properties\AssemblyInfo.cs" />
     <Compile Include="TestRunner.cs" />
   </ItemGroup>


[54/59] [abbrv] ignite git commit: IGNITE-1309: Moved platform affinity to Ignite.

Posted by vk...@apache.org.
IGNITE-1309: Moved platform affinity to Ignite.


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

Branch: refs/heads/ignite-884
Commit: 536af49ba0a407fdbc5682f73a48aa07fa3daae0
Parents: d9a1397
Author: vozerov-gridgain <vo...@gridgain.com>
Authored: Wed Aug 26 17:03:39 2015 +0300
Committer: vozerov-gridgain <vo...@gridgain.com>
Committed: Wed Aug 26 17:03:39 2015 +0300

----------------------------------------------------------------------
 .../cache/affinity/PlatformAffinity.java        | 293 +++++++++++++++++++
 1 file changed, 293 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/536af49b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/cache/affinity/PlatformAffinity.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/cache/affinity/PlatformAffinity.java b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/cache/affinity/PlatformAffinity.java
new file mode 100644
index 0000000..d6dfcdb
--- /dev/null
+++ b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/cache/affinity/PlatformAffinity.java
@@ -0,0 +1,293 @@
+/*
+ * 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.platform.cache.affinity;
+
+import org.apache.ignite.*;
+import org.apache.ignite.cache.affinity.*;
+import org.apache.ignite.cluster.*;
+import org.apache.ignite.internal.*;
+import org.apache.ignite.internal.managers.discovery.*;
+import org.apache.ignite.internal.portable.*;
+import org.apache.ignite.internal.processors.platform.*;
+import org.apache.ignite.internal.util.typedef.*;
+import org.apache.ignite.internal.util.typedef.internal.*;
+import org.jetbrains.annotations.*;
+
+import java.util.*;
+
+/**
+ * Native cache wrapper implementation.
+ */
+@SuppressWarnings({"unchecked", "UnusedDeclaration", "TryFinallyCanBeTryWithResources"})
+public class PlatformAffinity extends PlatformAbstractTarget {
+    /** */
+    public static final int OP_AFFINITY_KEY = 1;
+
+    /** */
+    public static final int OP_ALL_PARTITIONS = 2;
+
+    /** */
+    public static final int OP_BACKUP_PARTITIONS = 3;
+
+    /** */
+    public static final int OP_IS_BACKUP = 4;
+
+    /** */
+    public static final int OP_IS_PRIMARY = 5;
+
+    /** */
+    public static final int OP_IS_PRIMARY_OR_BACKUP = 6;
+
+    /** */
+    public static final int OP_MAP_KEY_TO_NODE = 7;
+
+    /** */
+    public static final int OP_MAP_KEY_TO_PRIMARY_AND_BACKUPS = 8;
+
+    /** */
+    public static final int OP_MAP_KEYS_TO_NODES = 9;
+
+    /** */
+    public static final int OP_MAP_PARTITION_TO_NODE = 10;
+
+    /** */
+    public static final int OP_MAP_PARTITION_TO_PRIMARY_AND_BACKUPS = 11;
+
+    /** */
+    public static final int OP_MAP_PARTITIONS_TO_NODES = 12;
+
+    /** */
+    public static final int OP_PARTITION = 13;
+
+    /** */
+    public static final int OP_PRIMARY_PARTITIONS = 14;
+
+    /** */
+    private static final C1<ClusterNode, UUID> TO_NODE_ID = new C1<ClusterNode, UUID>() {
+        @Nullable @Override public UUID apply(ClusterNode node) {
+            return node != null ? node.id() : null;
+        }
+    };
+
+    /** Underlying cache affinity. */
+    private final Affinity<Object> aff;
+
+    /** Discovery manager */
+    private final GridDiscoveryManager discovery;
+
+    /**
+     * Constructor.
+     *
+     * @param platformCtx Context.
+     * @param igniteCtx Ignite context.
+     * @param name Cache name.
+     */
+    public PlatformAffinity(PlatformContext platformCtx, GridKernalContext igniteCtx, @Nullable String name)
+        throws IgniteCheckedException {
+        super(platformCtx);
+
+        this.aff = igniteCtx.grid().affinity(name);
+
+        if (aff == null)
+            throw new IgniteCheckedException("Cache with the given name doesn't exist: " + name);
+
+        discovery = igniteCtx.discovery();
+    }
+
+    /** {@inheritDoc} */
+    @Override protected int processInOp(int type, PortableRawReaderEx reader) throws IgniteCheckedException {
+        switch (type) {
+            case OP_PARTITION:
+                return aff.partition(reader.readObjectDetached());
+
+            case OP_IS_PRIMARY: {
+                UUID nodeId = reader.readUuid();
+
+                Object key = reader.readObjectDetached();
+
+                ClusterNode node = discovery.node(nodeId);
+
+                if (node == null)
+                    return FALSE;
+
+                return aff.isPrimary(node, key) ? TRUE : FALSE;
+            }
+
+            case OP_IS_BACKUP: {
+                UUID nodeId = reader.readUuid();
+
+                Object key = reader.readObjectDetached();
+
+                ClusterNode node = discovery.node(nodeId);
+
+                if (node == null)
+                    return FALSE;
+
+                return aff.isBackup(node, key) ? TRUE : FALSE;
+            }
+
+            case OP_IS_PRIMARY_OR_BACKUP: {
+                UUID nodeId = reader.readUuid();
+
+                Object key = reader.readObjectDetached();
+
+                ClusterNode node = discovery.node(nodeId);
+
+                if (node == null)
+                    return FALSE;
+
+                return aff.isPrimaryOrBackup(node, key) ? TRUE : FALSE;
+            }
+
+            default:
+                return throwUnsupported(type);
+        }
+    }
+
+    /** {@inheritDoc} */
+    @SuppressWarnings({"IfMayBeConditional", "ConstantConditions"})
+    @Override protected void processInOutOp(int type, PortableRawReaderEx reader, PortableRawWriterEx writer,
+        Object arg) throws IgniteCheckedException {
+        switch (type) {
+            case OP_PRIMARY_PARTITIONS: {
+                UUID nodeId = reader.readObject();
+
+                ClusterNode node = discovery.node(nodeId);
+
+                int[] parts = node != null ? aff.primaryPartitions(node) : U.EMPTY_INTS;
+
+                writer.writeIntArray(parts);
+
+                break;
+            }
+
+            case OP_BACKUP_PARTITIONS: {
+                UUID nodeId = reader.readObject();
+
+                ClusterNode node = discovery.node(nodeId);
+
+                int[] parts = node != null ? aff.backupPartitions(node) : U.EMPTY_INTS;
+
+                writer.writeIntArray(parts);
+
+                break;
+            }
+
+            case OP_ALL_PARTITIONS: {
+                UUID nodeId = reader.readObject();
+
+                ClusterNode node = discovery.node(nodeId);
+
+                int[] parts = node != null ? aff.allPartitions(node) : U.EMPTY_INTS;
+
+                writer.writeIntArray(parts);
+
+                break;
+            }
+
+            case OP_AFFINITY_KEY: {
+                Object key = reader.readObjectDetached();
+
+                writer.writeObject(aff.affinityKey(key));
+
+                break;
+            }
+
+            case OP_MAP_KEY_TO_NODE: {
+                Object key = reader.readObjectDetached();
+
+                ClusterNode node = aff.mapKeyToNode(key);
+
+                platformCtx.writeNode(writer, node);
+
+                break;
+            }
+
+            case OP_MAP_PARTITION_TO_NODE: {
+                int part = reader.readObject();
+
+                ClusterNode node = aff.mapPartitionToNode(part);
+
+                platformCtx.writeNode(writer, node);
+
+                break;
+            }
+
+            case OP_MAP_KEY_TO_PRIMARY_AND_BACKUPS: {
+                Object key = reader.readObjectDetached();
+
+                platformCtx.writeNodes(writer, aff.mapKeyToPrimaryAndBackups(key));
+
+                break;
+            }
+
+            case OP_MAP_PARTITION_TO_PRIMARY_AND_BACKUPS: {
+                int part = reader.readObject();
+
+                platformCtx.writeNodes(writer, aff.mapPartitionToPrimaryAndBackups(part));
+
+                break;
+            }
+
+            case OP_MAP_KEYS_TO_NODES: {
+                Collection<Object> keys = reader.readCollection();
+
+                Map<ClusterNode, Collection<Object>> map = aff.mapKeysToNodes(keys);
+
+                writer.writeInt(map.size());
+
+                for (Map.Entry<ClusterNode, Collection<Object>> e : map.entrySet()) {
+                    platformCtx.addNode(e.getKey());
+
+                    writer.writeUuid(e.getKey().id());
+                    writer.writeObject(e.getValue());
+                }
+
+                break;
+            }
+
+            case OP_MAP_PARTITIONS_TO_NODES: {
+                Collection<Integer> parts = reader.readCollection();
+
+                Map<Integer, ClusterNode> map = aff.mapPartitionsToNodes(parts);
+
+                writer.writeInt(map.size());
+
+                for (Map.Entry<Integer, ClusterNode> e : map.entrySet()) {
+                    platformCtx.addNode(e.getValue());
+
+                    writer.writeInt(e.getKey());
+
+                    writer.writeUuid(e.getValue().id());
+                }
+
+                break;
+            }
+
+            default:
+                throwUnsupported(type);
+        }
+    }
+
+    /**
+     * @return Gets number of partitions in cache.
+     */
+    public int partitions() {
+        return aff.partitions();
+    }
+}


[34/59] [abbrv] ignite git commit: Added test.

Posted by vk...@apache.org.
Added test.


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

Branch: refs/heads/ignite-884
Commit: 194df76cbed6e0799f01819851bedabc00d39fab
Parents: c47a706
Author: sboikov <sb...@gridgain.com>
Authored: Wed Aug 26 10:44:49 2015 +0300
Committer: sboikov <sb...@gridgain.com>
Committed: Wed Aug 26 10:44:49 2015 +0300

----------------------------------------------------------------------
 .../IgniteCacheManyAsyncOperationsTest.java     | 107 +++++++++++++++++++
 1 file changed, 107 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/194df76c/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCacheManyAsyncOperationsTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCacheManyAsyncOperationsTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCacheManyAsyncOperationsTest.java
new file mode 100644
index 0000000..ab4f1b8
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCacheManyAsyncOperationsTest.java
@@ -0,0 +1,107 @@
+/*
+ * 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.*;
+import org.apache.ignite.cache.*;
+import org.apache.ignite.configuration.*;
+import org.apache.ignite.lang.*;
+
+import java.util.*;
+
+import static org.apache.ignite.cache.CacheAtomicityMode.*;
+import static org.apache.ignite.cache.CacheMode.*;
+
+/**
+ *
+ */
+public class IgniteCacheManyAsyncOperationsTest extends IgniteCacheAbstractTest {
+    /** {@inheritDoc} */
+    @Override protected int gridCount() {
+        return 2;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected CacheMode cacheMode() {
+        return PARTITIONED;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected CacheAtomicityMode atomicityMode() {
+        return TRANSACTIONAL;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected NearCacheConfiguration nearConfiguration() {
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception {
+        IgniteConfiguration cfg = super.getConfiguration(gridName);
+
+        if (gridName.equals(getTestGridName(2)))
+            cfg.setClientMode(true);
+
+        return cfg;
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testManyAsyncOperations() throws Exception {
+        try (Ignite client = startGrid(gridCount())) {
+            assertTrue(client.configuration().isClientMode());
+
+            IgniteCache<Object, Object> cache = client.cache(null).withAsync();
+
+            final int ASYNC_OPS = cache.getConfiguration(CacheConfiguration.class).getMaxConcurrentAsyncOperations();
+
+            log.info("Number of async operations: " + ASYNC_OPS);
+
+            Map<Integer, byte[]> map = new HashMap<>();
+
+            for (int i = 0; i < 500; i++)
+                map.put(i, new byte[128]);
+
+            for (int iter = 0; iter < 3; iter++) {
+                log.info("Iteration: " + iter);
+
+                List<IgniteFuture<?>> futs = new ArrayList<>(ASYNC_OPS);
+
+                for (int i = 0; i < ASYNC_OPS; i++) {
+                    cache.putAll(map);
+
+                    futs.add(cache.future());
+
+                    if (i % 50 == 0)
+                        log.info("Created futures: " + (i + 1));
+                }
+
+                for (int i = 0; i < ASYNC_OPS; i++) {
+                    IgniteFuture<?> fut = futs.get(i);
+
+                    fut.get();
+
+                    if (i % 50 == 0)
+                        log.info("Done: " + (i + 1));
+                }
+            }
+        }
+    }
+}


[33/59] [abbrv] ignite git commit: Moved "AbstractBootstrap" class to Ignite.

Posted by vk...@apache.org.
Moved "AbstractBootstrap" class to Ignite.


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

Branch: refs/heads/ignite-884
Commit: 203f00c774e6dd2eddf7a530b70c22e75feb3429
Parents: 2225f8d
Author: vozerov-gridgain <vo...@gridgain.com>
Authored: Wed Aug 26 09:41:32 2015 +0300
Committer: vozerov-gridgain <vo...@gridgain.com>
Committed: Wed Aug 26 09:41:32 2015 +0300

----------------------------------------------------------------------
 .../platform/PlatformAbstractBootstrap.java     | 47 ++++++++++++++++++++
 1 file changed, 47 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/203f00c7/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/PlatformAbstractBootstrap.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/PlatformAbstractBootstrap.java b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/PlatformAbstractBootstrap.java
new file mode 100644
index 0000000..4db3c1e
--- /dev/null
+++ b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/PlatformAbstractBootstrap.java
@@ -0,0 +1,47 @@
+/*
+ * 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.platform;
+
+import org.apache.ignite.*;
+import org.apache.ignite.configuration.*;
+import org.apache.ignite.internal.*;
+import org.apache.ignite.internal.processors.platform.memory.*;
+import org.apache.ignite.lang.*;
+
+/**
+ * Base interop bootstrap implementation.
+ */
+public abstract class PlatformAbstractBootstrap implements PlatformBootstrap {
+    /** {@inheritDoc} */
+    @Override public PlatformProcessor start(IgniteConfiguration cfg, long envPtr, long dataPtr) {
+        Ignition.setClientMode(new PlatformExternalMemory(null, dataPtr).input().readBoolean());
+
+        IgniteConfiguration cfg0 = closure(envPtr).apply(cfg);
+
+        IgniteEx node = (IgniteEx) Ignition.start(cfg0);
+
+        return node.context().platform();
+    }
+
+    /**
+     * Get configuration transformer closure.
+     *
+     * @param envPtr Environment pointer.
+     * @return Closure.
+     */
+    protected abstract IgniteClosure<IgniteConfiguration, IgniteConfiguration> closure(long envPtr);
+}


[30/59] [abbrv] ignite git commit: Moving platform classes to "...internal.processors..." package to follow Ignite common approach.

Posted by vk...@apache.org.
http://git-wip-us.apache.org/repos/asf/ignite/blob/2225f8d2/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/callback/PlatformCallbackUtils.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/callback/PlatformCallbackUtils.java b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/callback/PlatformCallbackUtils.java
new file mode 100644
index 0000000..7e9587f
--- /dev/null
+++ b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/callback/PlatformCallbackUtils.java
@@ -0,0 +1,468 @@
+/*
+ * 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.platform.callback;
+
+/**
+ * Platform callback utility methods. Implemented in target platform. All methods in this class must be
+ * package-visible and invoked only through {@link PlatformCallbackGateway}.
+ */
+public class PlatformCallbackUtils {
+    /**
+     * Create cache store.
+     *
+     * @param envPtr Environment pointer.
+     * @param memPtr Memory pointer.
+     * @return Pointer.
+     */
+    static native long cacheStoreCreate(long envPtr, long memPtr);
+
+    /**
+     * @param envPtr Environment pointer.
+     * @param objPtr Object pointer.
+     * @param memPtr Memory pointer.
+     * @param cb Callback.
+     * @return Result.
+     */
+    static native int cacheStoreInvoke(long envPtr, long objPtr, long memPtr, Object cb);
+
+    /**
+     * @param envPtr Environment pointer.
+     * @param objPtr Object pointer.
+     */
+    static native void cacheStoreDestroy(long envPtr, long objPtr);
+
+    /**
+     * Creates cache store session.
+     *
+     * @param envPtr Environment pointer.
+     * @param storePtr Store instance pointer.
+     * @return Session instance pointer.
+     */
+    static native long cacheStoreSessionCreate(long envPtr, long storePtr);
+
+    /**
+     * Creates cache entry filter and returns a pointer.
+     *
+     * @param envPtr Environment pointer.
+     * @param memPtr Memory pointer.
+     * @return Pointer.
+     */
+    static native long cacheEntryFilterCreate(long envPtr, long memPtr);
+
+    /**
+     * @param envPtr Environment pointer.
+     * @param objPtr Pointer.
+     * @param memPtr Memory pointer.
+     * @return Result.
+     */
+    static native int cacheEntryFilterApply(long envPtr, long objPtr, long memPtr);
+
+    /**
+     * @param envPtr Environment pointer.
+     * @param objPtr Pointer.
+     */
+    static native void cacheEntryFilterDestroy(long envPtr, long objPtr);
+
+    /**
+     * Invoke cache entry processor.
+     *
+     * @param envPtr Environment pointer.
+     * @param outMemPtr Output memory pointer.
+     * @param inMemPtr Input memory pointer.
+     */
+    static native void cacheInvoke(long envPtr, long outMemPtr, long inMemPtr);
+
+    /**
+     * Perform native task map. Do not throw exceptions, serializing them to the output stream instead.
+     *
+     * @param envPtr Environment pointer.
+     * @param taskPtr Task pointer.
+     * @param outMemPtr Output memory pointer (exists if topology changed, otherwise {@code 0}).
+     * @param inMemPtr Input memory pointer.
+     */
+    static native void computeTaskMap(long envPtr, long taskPtr, long outMemPtr, long inMemPtr);
+
+    /**
+     * Perform native task job result notification.
+     *
+     * @param envPtr Environment pointer.
+     * @param taskPtr Task pointer.
+     * @param jobPtr Job pointer.
+     * @param memPtr Memory pointer (always zero for local job execution).
+     * @return Job result enum ordinal.
+     */
+    static native int computeTaskJobResult(long envPtr, long taskPtr, long jobPtr, long memPtr);
+
+    /**
+     * Perform native task reduce.
+     *
+     * @param envPtr Environment pointer.
+     * @param taskPtr Task pointer.
+     */
+    static native void computeTaskReduce(long envPtr, long taskPtr);
+
+    /**
+     * Complete task with native error.
+     *
+     * @param envPtr Environment pointer.
+     * @param taskPtr Task pointer.
+     * @param memPtr Memory pointer with exception data or {@code 0} in case of success.
+     */
+    static native void computeTaskComplete(long envPtr, long taskPtr, long memPtr);
+
+    /**
+     * Serialize native job.
+     *
+     * @param envPtr Environment pointer.
+     * @param jobPtr Job pointer.
+     * @param memPtr Memory pointer.
+     * @return {@code True} if serialization succeeded.
+     */
+    static native int computeJobSerialize(long envPtr, long jobPtr, long memPtr);
+
+    /**
+     * Create job in native platform.
+     *
+     * @param envPtr Environment pointer.
+     * @param memPtr Memory pointer.
+     * @return Pointer to job.
+     */
+    static native long computeJobCreate(long envPtr, long memPtr);
+
+    /**
+     * Execute native job on a node other than where it was created.
+     *
+     * @param envPtr Environment pointer.
+     * @param jobPtr Job pointer.
+     * @param cancel Cancel flag.
+     * @param memPtr Memory pointer to write result to for remote job execution or {@code 0} for local job execution.
+     */
+    static native void computeJobExecute(long envPtr, long jobPtr, int cancel, long memPtr);
+
+    /**
+     * Cancel the job.
+     *
+     * @param envPtr Environment pointer.
+     * @param jobPtr Job pointer.
+     */
+    static native void computeJobCancel(long envPtr, long jobPtr);
+
+    /**
+     * Destroy the job.
+     *
+     * @param envPtr Environment pointer.
+     * @param ptr Pointer.
+     */
+    static native void computeJobDestroy(long envPtr, long ptr);
+
+    /**
+     * Invoke local callback.
+     *
+     * @param envPtr Environment pointer.
+     * @param cbPtr Callback pointer.
+     * @param memPtr Memory pointer.
+     */
+    static native void continuousQueryListenerApply(long envPtr, long cbPtr, long memPtr);
+
+    /**
+     * Create filter in native platform.
+     *
+     * @param envPtr Environment pointer.
+     * @param memPtr Memory pointer.
+     * @return Pointer to created filter.
+     */
+    static native long continuousQueryFilterCreate(long envPtr, long memPtr);
+
+    /**
+     * Invoke remote filter.
+     *
+     * @param envPtr Environment pointer.
+     * @param filterPtr Filter pointer.
+     * @param memPtr Memory pointer.
+     * @return Result.
+     */
+    static native int continuousQueryFilterApply(long envPtr, long filterPtr, long memPtr);
+
+    /**
+     * Release remote  filter.
+     *
+     * @param envPtr Environment pointer.
+     * @param filterPtr Filter pointer.
+     */
+    static native void continuousQueryFilterRelease(long envPtr, long filterPtr);
+
+    /**
+     * Notify native data streamer about topology update.
+     *
+     * @param envPtr Environment pointer.
+     * @param ptr Data streamer native pointer.
+     * @param topVer Topology version.
+     * @param topSize Topology size.
+     */
+    static native void dataStreamerTopologyUpdate(long envPtr, long ptr, long topVer, int topSize);
+
+    /**
+     * Invoke stream receiver.
+     *
+     * @param envPtr Environment pointer.
+     * @param ptr Receiver native pointer.
+     * @param cache Cache object.
+     * @param memPtr Stream pointer.
+     * @param keepPortable Portable flag.
+     */
+    static native void dataStreamerStreamReceiverInvoke(long envPtr, long ptr, Object cache, long memPtr,
+        boolean keepPortable);
+
+    /**
+     * Notify future with byte result.
+     *
+     * @param envPtr Environment pointer.
+     * @param futPtr Future pointer.
+     * @param res Result.
+     */
+    static native void futureByteResult(long envPtr, long futPtr, int res);
+
+    /**
+     * Notify future with boolean result.
+     *
+     * @param envPtr Environment pointer.
+     * @param futPtr Future pointer.
+     * @param res Result.
+     */
+    static native void futureBoolResult(long envPtr, long futPtr, int res);
+
+    /**
+     * Notify future with short result.
+     *
+     * @param envPtr Environment pointer.
+     * @param futPtr Future pointer.
+     * @param res Result.
+     */
+    static native void futureShortResult(long envPtr, long futPtr, int res);
+
+    /**
+     * Notify future with byte result.
+     *
+     * @param envPtr Environment pointer.
+     * @param futPtr Future pointer.
+     * @param res Result.
+     */
+    static native void futureCharResult(long envPtr, long futPtr, int res);
+
+    /**
+     * Notify future with int result.
+     *
+     * @param envPtr Environment pointer.
+     * @param futPtr Future pointer.
+     * @param res Result.
+     */
+    static native void futureIntResult(long envPtr, long futPtr, int res);
+
+    /**
+     * Notify future with float result.
+     *
+     * @param envPtr Environment pointer.
+     * @param futPtr Future pointer.
+     * @param res Result.
+     */
+    static native void futureFloatResult(long envPtr, long futPtr, float res);
+
+    /**
+     * Notify future with long result.
+     *
+     * @param envPtr Environment pointer.
+     * @param futPtr Future pointer.
+     * @param res Result.
+     */
+    static native void futureLongResult(long envPtr, long futPtr, long res);
+
+    /**
+     * Notify future with double result.
+     *
+     * @param envPtr Environment pointer.
+     * @param futPtr Future pointer.
+     * @param res Result.
+     */
+    static native void futureDoubleResult(long envPtr, long futPtr, double res);
+
+    /**
+     * Notify future with object result.
+     *
+     * @param envPtr Environment pointer.
+     * @param futPtr Future pointer.
+     * @param memPtr Memory pointer.
+     */
+    static native void futureObjectResult(long envPtr, long futPtr, long memPtr);
+
+    /**
+     * Notify future with null result.
+     *
+     * @param envPtr Environment pointer.
+     * @param futPtr Future pointer.
+     */
+    static native void futureNullResult(long envPtr, long futPtr);
+
+    /**
+     * Notify future with error.
+     *
+     * @param envPtr Environment pointer.
+     * @param futPtr Future pointer.
+     * @param memPtr Pointer to memory with error information.
+     */
+    static native void futureError(long envPtr, long futPtr, long memPtr);
+
+    /**
+     * Creates message filter and returns a pointer.
+     *
+     * @param envPtr Environment pointer.
+     * @param memPtr Memory pointer.
+     * @return Pointer.
+     */
+    static native long messagingFilterCreate(long envPtr, long memPtr);
+
+    /**
+     * @param envPtr Environment pointer.
+     * @param objPtr Pointer.
+     * @param memPtr Memory pointer.
+     * @return Result.
+     */
+    static native int messagingFilterApply(long envPtr, long objPtr, long memPtr);
+
+    /**
+     * @param envPtr Environment pointer.
+     * @param objPtr Pointer.
+     */
+    static native void messagingFilterDestroy(long envPtr, long objPtr);
+
+    /**
+     * Creates event filter and returns a pointer.
+     *
+     * @param envPtr Environment pointer.
+     * @param memPtr Memory pointer.
+     * @return Pointer.
+     */
+    static native long eventFilterCreate(long envPtr, long memPtr);
+
+    /**
+     * @param envPtr Environment pointer.
+     * @param objPtr Pointer.
+     * @param memPtr Memory pointer.
+     * @return Result.
+     */
+    static native int eventFilterApply(long envPtr, long objPtr, long memPtr);
+
+    /**
+     * @param envPtr Environment pointer.
+     * @param objPtr Pointer.
+     */
+    static native void eventFilterDestroy(long envPtr, long objPtr);
+
+    /**
+     * Sends node info to native target.
+     *
+     * @param envPtr Environment pointer.
+     * @param memPtr Ptr to a stream with serialized node.
+     */
+    static native void nodeInfo(long envPtr, long memPtr);
+
+    /**
+     * Kernal start callback.
+     *
+     * @param envPtr Environment pointer.
+     * @param memPtr Memory pointer.
+     */
+    static native void onStart(long envPtr, long memPtr);
+
+    /*
+     * Kernal stop callback.
+     *
+     * @param envPtr Environment pointer.
+     */
+    static native void onStop(long envPtr);
+
+    /**
+     * Lifecycle event callback.
+     *
+     * @param envPtr Environment pointer.
+     * @param ptr Holder pointer.
+     * @param evt Event.
+     */
+    static native void lifecycleEvent(long envPtr, long ptr, int evt);
+
+    /**
+     * Re-allocate external memory chunk.
+     *
+     * @param envPtr Environment pointer.
+     * @param memPtr Cross-platform pointer.
+     * @param cap Capacity.
+     */
+    static native void memoryReallocate(long envPtr, long memPtr, int cap);
+
+    /**
+     * Initializes native service.
+     *
+     * @param envPtr Environment pointer.
+     * @param memPtr Stream pointer.
+     * @return Pointer to the native platform service.
+     */
+    static native long serviceInit(long envPtr, long memPtr);
+
+    /**
+     * Executes native service.
+     *
+     * @param envPtr Environment pointer.
+     * @param svcPtr Pointer to the service in the native platform.
+     * @param memPtr Stream pointer.
+     */
+    static native void serviceExecute(long envPtr, long svcPtr, long memPtr);
+
+    /**
+     * Cancels native service.
+     *
+     * @param envPtr Environment pointer.
+     * @param svcPtr Pointer to the service in the native platform.
+     * @param memPtr Stream pointer.
+     */
+    static native void serviceCancel(long envPtr, long svcPtr, long memPtr);
+
+    /**
+     /**
+     * Invokes service method.
+     *
+     * @param envPtr Environment pointer.
+     * @param svcPtr Pointer to the service in the native platform.
+     * @param outMemPtr Output memory pointer.
+     * @param inMemPtr Input memory pointer.
+     */
+    static native void serviceInvokeMethod(long envPtr, long svcPtr, long outMemPtr, long inMemPtr);
+
+    /**
+     * Invokes cluster node filter.
+     *
+     * @param envPtr Environment pointer.
+     * @param memPtr Stream pointer.
+     */
+    static native int clusterNodeFilterApply(long envPtr, long memPtr);
+
+    /**
+     * Private constructor.
+     */
+    private PlatformCallbackUtils() {
+        // No-op.
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/2225f8d2/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/memory/PlatformAbstractMemory.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/memory/PlatformAbstractMemory.java b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/memory/PlatformAbstractMemory.java
new file mode 100644
index 0000000..fbbabb7
--- /dev/null
+++ b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/memory/PlatformAbstractMemory.java
@@ -0,0 +1,121 @@
+/*
+ * 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.platform.memory;
+
+/**
+ * Interop memory chunk abstraction.
+ */
+public abstract class PlatformAbstractMemory implements PlatformMemory {
+    /** Stream factory. */
+    private static final StreamFactory STREAM_FACTORY = PlatformMemoryUtils.LITTLE_ENDIAN ?
+        new LittleEndianStreamFactory() : new BigEndianStreamFactory();
+
+    /** Cross-platform memory pointer. */
+    protected long memPtr;
+
+    /**
+     * Constructor.
+     *
+     * @param memPtr Cross-platform memory pointer.
+     */
+    protected PlatformAbstractMemory(long memPtr) {
+        this.memPtr = memPtr;
+    }
+
+    /** {@inheritDoc} */
+    @Override public PlatformInputStream input() {
+        return STREAM_FACTORY.createInput(this);
+    }
+
+    /** {@inheritDoc} */
+    @Override public PlatformOutputStream output() {
+        return STREAM_FACTORY.createOutput(this);
+    }
+
+    /** {@inheritDoc} */
+    @Override public long pointer() {
+        return memPtr;
+    }
+
+    /** {@inheritDoc} */
+    @Override public long data() {
+        return PlatformMemoryUtils.data(memPtr);
+    }
+
+    /** {@inheritDoc} */
+    @Override public int capacity() {
+        return PlatformMemoryUtils.capacity(memPtr);
+    }
+
+    /** {@inheritDoc} */
+    @Override public int length() {
+        return PlatformMemoryUtils.length(memPtr);
+    }
+
+    /**
+     * Stream factory.
+     */
+    private static interface StreamFactory {
+        /**
+         * Create input stream.
+         *
+         * @param mem Memory.
+         * @return Input stream.
+         */
+        PlatformInputStreamImpl createInput(PlatformMemory mem);
+
+        /**
+         * Create output stream.
+         *
+         * @param mem Memory.
+         * @return Output stream.
+         */
+        PlatformOutputStreamImpl createOutput(PlatformMemory mem);
+    }
+
+    /**
+     * Stream factory for LITTLE ENDIAN architecture.
+     */
+    private static class LittleEndianStreamFactory implements StreamFactory {
+        /** {@inheritDoc} */
+        @Override public PlatformInputStreamImpl createInput(PlatformMemory mem) {
+            return new PlatformInputStreamImpl(mem);
+        }
+
+        /** {@inheritDoc} */
+        @Override public PlatformOutputStreamImpl createOutput(PlatformMemory mem) {
+            return new PlatformOutputStreamImpl(mem);
+        }
+    }
+
+    /**
+     * Stream factory for BIG ENDIAN architecture.
+     */
+    private static class BigEndianStreamFactory implements StreamFactory {
+        /** {@inheritDoc} */
+        @Override public PlatformInputStreamImpl createInput(PlatformMemory mem) {
+            return new PlatformBigEndianInputStreamImpl(mem);
+        }
+
+        /** {@inheritDoc} */
+        @Override public PlatformOutputStreamImpl createOutput(PlatformMemory mem) {
+            return new PlatformBigEndianOutputStreamImpl(mem);
+        }
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/2225f8d2/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/memory/PlatformBigEndianInputStreamImpl.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/memory/PlatformBigEndianInputStreamImpl.java b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/memory/PlatformBigEndianInputStreamImpl.java
new file mode 100644
index 0000000..b029ee0
--- /dev/null
+++ b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/memory/PlatformBigEndianInputStreamImpl.java
@@ -0,0 +1,126 @@
+/*
+ * 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.platform.memory;
+
+/**
+ * Interop input stream implementation working with BIG ENDIAN architecture.
+ */
+public class PlatformBigEndianInputStreamImpl extends PlatformInputStreamImpl {
+    /**
+     * Constructor.
+     *
+     * @param mem Memory chunk.
+     */
+    public PlatformBigEndianInputStreamImpl(PlatformMemory mem) {
+        super(mem);
+    }
+
+    /** {@inheritDoc} */
+    @Override public short readShort() {
+        return Short.reverseBytes(super.readShort());
+    }
+
+    /** {@inheritDoc} */
+    @Override public short[] readShortArray(int cnt) {
+        short[] res = super.readShortArray(cnt);
+
+        for (int i = 0; i < cnt; i++)
+            res[i] = Short.reverseBytes(res[i]);
+
+        return res;
+    }
+
+    /** {@inheritDoc} */
+    @Override public char readChar() {
+        return Character.reverseBytes(super.readChar());
+    }
+
+    /** {@inheritDoc} */
+    @Override public char[] readCharArray(int cnt) {
+        char[] res = super.readCharArray(cnt);
+
+        for (int i = 0; i < cnt; i++)
+            res[i] = Character.reverseBytes(res[i]);
+
+        return res;
+    }
+
+    /** {@inheritDoc} */
+    @Override public int readInt() {
+        return Integer.reverseBytes(super.readInt());
+    }
+
+    /** {@inheritDoc} */
+    @Override public int readInt(int pos) {
+        return Integer.reverseBytes(super.readInt(pos));
+    }
+
+    /** {@inheritDoc} */
+    @Override public int[] readIntArray(int cnt) {
+        int[] res = super.readIntArray(cnt);
+
+        for (int i = 0; i < cnt; i++)
+            res[i] = Integer.reverseBytes(res[i]);
+
+        return res;
+    }
+
+    /** {@inheritDoc} */
+    @Override public float readFloat() {
+        return Float.intBitsToFloat(Integer.reverseBytes(Float.floatToIntBits(super.readFloat())));
+    }
+
+    /** {@inheritDoc} */
+    @Override public float[] readFloatArray(int cnt) {
+        float[] res = super.readFloatArray(cnt);
+
+        for (int i = 0; i < cnt; i++)
+            res[i] = Float.intBitsToFloat(Integer.reverseBytes(Float.floatToIntBits(res[i])));
+
+        return res;
+    }
+
+    /** {@inheritDoc} */
+    @Override public long readLong() {
+        return Long.reverseBytes(super.readLong());
+    }
+
+    /** {@inheritDoc} */
+    @Override public long[] readLongArray(int cnt) {
+        long[] res = super.readLongArray(cnt);
+
+        for (int i = 0; i < cnt; i++)
+            res[i] = Long.reverseBytes(res[i]);
+
+        return res;
+    }
+
+    /** {@inheritDoc} */
+    @Override public double readDouble() {
+        return Double.longBitsToDouble(Long.reverseBytes(Double.doubleToLongBits(super.readDouble())));
+    }
+
+    /** {@inheritDoc} */
+    @Override public double[] readDoubleArray(int cnt) {
+        double[] res = super.readDoubleArray(cnt);
+
+        for (int i = 0; i < cnt; i++)
+            res[i] = Double.longBitsToDouble(Long.reverseBytes(Double.doubleToLongBits(res[i])));
+
+        return res;
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/2225f8d2/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/memory/PlatformBigEndianOutputStreamImpl.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/memory/PlatformBigEndianOutputStreamImpl.java b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/memory/PlatformBigEndianOutputStreamImpl.java
new file mode 100644
index 0000000..e1c1585
--- /dev/null
+++ b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/memory/PlatformBigEndianOutputStreamImpl.java
@@ -0,0 +1,162 @@
+/*
+ * 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.platform.memory;
+
+import static org.apache.ignite.internal.processors.platform.memory.PlatformMemoryUtils.*;
+
+/**
+ * Interop output stream implementation working with BIG ENDIAN architecture.
+ */
+public class PlatformBigEndianOutputStreamImpl extends PlatformOutputStreamImpl {
+    /**
+     * Constructor.
+     *
+     * @param mem Underlying memory chunk.
+     */
+    public PlatformBigEndianOutputStreamImpl(PlatformMemory mem) {
+        super(mem);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeShort(short val) {
+        super.writeShort(Short.reverseBytes(val));
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeShortArray(short[] val) {
+        int cnt = val.length << 1;
+
+        ensureCapacity(pos + cnt);
+
+        long startPos = data + pos;
+
+        for (short item : val) {
+            UNSAFE.putShort(startPos, Short.reverseBytes(item));
+
+            startPos += 2;
+        }
+
+        shift(cnt);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeChar(char val) {
+        super.writeChar(Character.reverseBytes(val));
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeCharArray(char[] val) {
+        int cnt = val.length << 1;
+
+        ensureCapacity(pos + cnt);
+
+        long startPos = data + pos;
+
+        for (char item : val) {
+            UNSAFE.putChar(startPos, Character.reverseBytes(item));
+
+            startPos += 2;
+        }
+
+        shift(cnt);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeInt(int val) {
+        super.writeInt(Integer.reverseBytes(val));
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeIntArray(int[] val) {
+        int cnt = val.length << 2;
+
+        ensureCapacity(pos + cnt);
+
+        long startPos = data + pos;
+
+        for (int item : val) {
+            UNSAFE.putInt(startPos, Integer.reverseBytes(item));
+
+            startPos += 4;
+        }
+
+        shift(cnt);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeInt(int pos, int val) {
+        super.writeInt(pos, Integer.reverseBytes(val));
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeFloatArray(float[] val) {
+        int cnt = val.length << 2;
+
+        ensureCapacity(pos + cnt);
+
+        long startPos = data + pos;
+
+        for (float item : val) {
+            UNSAFE.putInt(startPos, Integer.reverseBytes(Float.floatToIntBits(item)));
+
+            startPos += 4;
+        }
+
+        shift(cnt);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeLong(long val) {
+        super.writeLong(Long.reverseBytes(val));
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeLongArray(long[] val) {
+        int cnt = val.length << 3;
+
+        ensureCapacity(pos + cnt);
+
+        long startPos = data + pos;
+
+        for (long item : val) {
+            UNSAFE.putLong(startPos, Long.reverseBytes(item));
+
+            startPos += 8;
+        }
+
+        shift(cnt);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeDoubleArray(double[] val) {
+        int cnt = val.length << 3;
+
+        ensureCapacity(pos + cnt);
+
+        long startPos = data + pos;
+
+        for (double item : val) {
+            UNSAFE.putLong(startPos, Long.reverseBytes(Double.doubleToLongBits(item)));
+
+            startPos += 8;
+        }
+
+        shift(cnt);
+    }
+}
+

http://git-wip-us.apache.org/repos/asf/ignite/blob/2225f8d2/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/memory/PlatformExternalMemory.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/memory/PlatformExternalMemory.java b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/memory/PlatformExternalMemory.java
new file mode 100644
index 0000000..0d47aff
--- /dev/null
+++ b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/memory/PlatformExternalMemory.java
@@ -0,0 +1,55 @@
+/*
+ * 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.platform.memory;
+
+import org.apache.ignite.*;
+import org.apache.ignite.internal.processors.platform.callback.*;
+import org.jetbrains.annotations.*;
+
+/**
+ * Interop external memory chunk.
+ */
+public class PlatformExternalMemory extends PlatformAbstractMemory {
+    /** Native gateway. */
+    private final PlatformCallbackGateway gate;
+
+    /**
+     * Constructor.
+     *
+     * @param gate Native gateway.
+     * @param memPtr Memory pointer.
+     */
+    public PlatformExternalMemory(@Nullable PlatformCallbackGateway gate, long memPtr) {
+        super(memPtr);
+
+        this.gate = gate;
+    }
+
+    /** {@inheritDoc} */
+    @Override public void reallocate(int cap) {
+        if (gate == null)
+            throw new IgniteException("Failed to re-allocate external memory chunk because it is read-only.");
+
+        gate.memoryReallocate(memPtr, cap);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void close() {
+        // Do nothing, memory must be released by native platform.
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/2225f8d2/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/memory/PlatformInputStream.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/memory/PlatformInputStream.java b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/memory/PlatformInputStream.java
new file mode 100644
index 0000000..9273e29
--- /dev/null
+++ b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/memory/PlatformInputStream.java
@@ -0,0 +1,30 @@
+/*
+ * 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.platform.memory;
+
+import org.apache.ignite.internal.portable.streams.*;
+
+/**
+ * Interop output stream,
+ */
+public interface PlatformInputStream extends PortableInputStream {
+    /**
+     * Synchronize input. Must be called before start reading data from a memory changed by another platform.
+     */
+    public void synchronize();
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/2225f8d2/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/memory/PlatformInputStreamImpl.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/memory/PlatformInputStreamImpl.java b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/memory/PlatformInputStreamImpl.java
new file mode 100644
index 0000000..68beaee
--- /dev/null
+++ b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/memory/PlatformInputStreamImpl.java
@@ -0,0 +1,323 @@
+/*
+ * 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.platform.memory;
+
+import org.apache.ignite.*;
+
+import static org.apache.ignite.internal.processors.platform.memory.PlatformMemoryUtils.*;
+
+/**
+ * Interop input stream implementation.
+ */
+public class PlatformInputStreamImpl implements PlatformInputStream {
+    /** Underlying memory. */
+    private final PlatformMemory mem;
+
+    /** Real data pointer */
+    private long data;
+
+    /** Amount of available data. */
+    private int len;
+
+    /** Current position. */
+    private int pos;
+
+    /** Heap-copied data. */
+    private byte[] dataCopy;
+
+    /**
+     * Constructor.
+     *
+     * @param mem Underlying memory chunk.
+     */
+    public PlatformInputStreamImpl(PlatformMemory mem) {
+        this.mem = mem;
+
+        data = mem.data();
+        len = mem.length();
+    }
+
+    /** {@inheritDoc} */
+    @Override public byte readByte() {
+        ensureEnoughData(1);
+
+        return UNSAFE.getByte(data + pos++);
+    }
+
+    /** {@inheritDoc} */
+    @Override public byte[] readByteArray(int cnt) {
+        byte[] res = new byte[cnt];
+
+        copyAndShift(res, BYTE_ARR_OFF, cnt);
+
+        return res;
+    }
+
+    /** {@inheritDoc} */
+    @Override public boolean readBoolean() {
+        return readByte() == 1;
+    }
+
+    /** {@inheritDoc} */
+    @Override public boolean[] readBooleanArray(int cnt) {
+        boolean[] res = new boolean[cnt];
+
+        copyAndShift(res, BOOLEAN_ARR_OFF, cnt);
+
+        return res;
+    }
+
+    /** {@inheritDoc} */
+    @Override public short readShort() {
+        ensureEnoughData(2);
+
+        short res = UNSAFE.getShort(data + pos);
+
+        shift(2);
+
+        return res;
+    }
+
+    /** {@inheritDoc} */
+    @Override public short[] readShortArray(int cnt) {
+        int len = cnt << 1;
+
+        short[] res = new short[cnt];
+
+        copyAndShift(res, SHORT_ARR_OFF, len);
+
+        return res;
+    }
+
+    /** {@inheritDoc} */
+    @Override public char readChar() {
+        ensureEnoughData(2);
+
+        char res = UNSAFE.getChar(data + pos);
+
+        shift(2);
+
+        return res;
+    }
+
+    /** {@inheritDoc} */
+    @Override public char[] readCharArray(int cnt) {
+        int len = cnt << 1;
+
+        char[] res = new char[cnt];
+
+        copyAndShift(res, CHAR_ARR_OFF, len);
+
+        return res;
+    }
+
+    /** {@inheritDoc} */
+    @Override public int readInt() {
+        ensureEnoughData(4);
+
+        int res = UNSAFE.getInt(data + pos);
+
+        shift(4);
+
+        return res;
+    }
+
+    /** {@inheritDoc} */
+    @Override public int readInt(int pos) {
+        int delta = pos + 4 - this.pos;
+
+        if (delta > 0)
+            ensureEnoughData(delta);
+
+        return UNSAFE.getInt(data + pos);
+    }
+
+    /** {@inheritDoc} */
+    @Override public int[] readIntArray(int cnt) {
+        int len = cnt << 2;
+
+        int[] res = new int[cnt];
+
+        copyAndShift(res, INT_ARR_OFF, len);
+
+        return res;
+    }
+
+    /** {@inheritDoc} */
+    @Override public float readFloat() {
+        ensureEnoughData(4);
+
+        float res = UNSAFE.getFloat(data + pos);
+
+        shift(4);
+
+        return res;
+    }
+
+    /** {@inheritDoc} */
+    @Override public float[] readFloatArray(int cnt) {
+        int len = cnt << 2;
+
+        float[] res = new float[cnt];
+
+        copyAndShift(res, FLOAT_ARR_OFF, len);
+
+        return res;
+    }
+
+    /** {@inheritDoc} */
+    @Override public long readLong() {
+        ensureEnoughData(8);
+
+        long res = UNSAFE.getLong(data + pos);
+
+        shift(8);
+
+        return res;
+    }
+
+    /** {@inheritDoc} */
+    @Override public long[] readLongArray(int cnt) {
+        int len = cnt << 3;
+
+        long[] res = new long[cnt];
+
+        copyAndShift(res, LONG_ARR_OFF, len);
+
+        return res;
+    }
+
+    /** {@inheritDoc} */
+    @Override public double readDouble() {
+        ensureEnoughData(8);
+
+        double res = UNSAFE.getDouble(data + pos);
+
+        shift(8);
+
+        return res;
+    }
+
+    /** {@inheritDoc} */
+    @Override public double[] readDoubleArray(int cnt) {
+        int len = cnt << 3;
+
+        double[] res = new double[cnt];
+
+        copyAndShift(res, DOUBLE_ARR_OFF, len);
+
+        return res;
+    }
+
+    /** {@inheritDoc} */
+    @Override public int read(byte[] arr, int off, int len) {
+        if (len > remaining())
+            len = remaining();
+
+        copyAndShift(arr, BYTE_ARR_OFF + off, len);
+
+        return len;
+    }
+
+    /** {@inheritDoc} */
+    @Override public int remaining() {
+        return len - pos;
+    }
+
+    /** {@inheritDoc} */
+    @Override public int position() {
+        return pos;
+    }
+
+    /** {@inheritDoc} */
+    @Override public void position(int pos) {
+        if (pos > len)
+            throw new IgniteException("Position is out of bounds: " + pos);
+        else
+            this.pos = pos;
+    }
+
+    /** {@inheritDoc} */
+    @Override public byte[] array() {
+        return arrayCopy();
+    }
+
+    /** {@inheritDoc} */
+    @Override public byte[] arrayCopy() {
+        if (dataCopy == null) {
+            dataCopy = new byte[len];
+
+            UNSAFE.copyMemory(null, data, dataCopy, BYTE_ARR_OFF, dataCopy.length);
+        }
+
+        return dataCopy;
+    }
+
+    /** {@inheritDoc} */
+    @Override public long offheapPointer() {
+        return 0;
+    }
+
+    /** {@inheritDoc} */
+    @Override public boolean hasArray() {
+        return false;
+    }
+
+    /** {@inheritDoc} */
+    @Override public void synchronize() {
+        data = mem.data();
+        len = mem.length();
+    }
+
+    /**
+     * Ensure there is enough data in the stream.
+     *
+     * @param cnt Amount of byte expected to be available.
+     */
+    private void ensureEnoughData(int cnt) {
+        if (remaining() < cnt)
+            throw new IgniteException("Not enough data to read the value [position=" + pos +
+                ", requiredBytes=" + cnt + ", remainingBytes=" + remaining() + ']');
+    }
+
+    /**
+     * Copy required amount of data and shift position.
+     *
+     * @param target Target to copy data to.
+     * @param off Offset.
+     * @param cnt Count.
+     */
+    private void copyAndShift(Object target, long off, int cnt) {
+        ensureEnoughData(cnt);
+
+        UNSAFE.copyMemory(null, data + pos, target, off, cnt);
+
+        shift(cnt);
+    }
+
+    /**
+     * Shift position to the right.
+     *
+     * @param cnt Amount of bytes.
+     */
+    private void shift(int cnt) {
+        pos += cnt;
+
+        assert pos <= len;
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/2225f8d2/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/memory/PlatformMemory.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/memory/PlatformMemory.java b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/memory/PlatformMemory.java
new file mode 100644
index 0000000..9d8f94e
--- /dev/null
+++ b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/memory/PlatformMemory.java
@@ -0,0 +1,77 @@
+/*
+ * 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.platform.memory;
+
+/**
+ * Interop memory chunk.
+ */
+public interface PlatformMemory extends AutoCloseable {
+    /**
+     * Gets input stream.
+     *
+     * @return Input stream.
+     */
+    public PlatformInputStream input();
+
+    /**
+     * Gets output stream.
+     *
+     * @return Output stream.
+     */
+    public PlatformOutputStream output();
+
+    /**
+     * Gets pointer which can be passed between platforms.
+     *
+     * @return Pointer.
+     */
+    public long pointer();
+
+    /**
+     * Gets data pointer.
+     *
+     * @return Data pointer.
+     */
+    public long data();
+
+    /**
+     * Gets capacity.
+     *
+     * @return Capacity.
+     */
+    public int capacity();
+
+    /**
+     * Gets length.
+     *
+     * @return Length.
+     */
+    public int length();
+
+    /**
+     * Reallocate memory chunk.
+     *
+     * @param cap Minimum capacity.
+     */
+    public void reallocate(int cap);
+
+    /**
+     * Close memory releasing it.
+     */
+    @Override void close();
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/2225f8d2/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/memory/PlatformMemoryManager.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/memory/PlatformMemoryManager.java b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/memory/PlatformMemoryManager.java
new file mode 100644
index 0000000..c2233a8
--- /dev/null
+++ b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/memory/PlatformMemoryManager.java
@@ -0,0 +1,46 @@
+/*
+ * 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.platform.memory;
+
+/**
+ * Interop memory manager interface.
+ */
+public interface PlatformMemoryManager {
+    /**
+     * Allocates memory.
+     *
+     * @return Memory.
+     */
+    public PlatformMemory allocate();
+
+    /**
+     * Allocates memory having at least the given capacity.
+     *
+     * @param cap Minimum capacity.
+     * @return Memory.
+     */
+    public PlatformMemory allocate(int cap);
+
+    /**
+     * Gets memory from existing pointer.
+     *
+     * @param memPtr Cross-platform memory pointer.
+     * @return Memory.
+     */
+    public PlatformMemory get(long memPtr);
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/2225f8d2/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/memory/PlatformMemoryManagerImpl.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/memory/PlatformMemoryManagerImpl.java b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/memory/PlatformMemoryManagerImpl.java
new file mode 100644
index 0000000..83388e0
--- /dev/null
+++ b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/memory/PlatformMemoryManagerImpl.java
@@ -0,0 +1,83 @@
+/*
+ * 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.platform.memory;
+
+import org.apache.ignite.internal.processors.platform.callback.*;
+import org.jetbrains.annotations.*;
+
+import static org.apache.ignite.internal.processors.platform.memory.PlatformMemoryUtils.*;
+
+/**
+ * Interop memory manager implementation.
+ */
+public class PlatformMemoryManagerImpl implements PlatformMemoryManager {
+    /** Native gateway. */
+    private final PlatformCallbackGateway gate;
+
+    /** Default allocation capacity. */
+    private final int dfltCap;
+
+    /** Thread-local pool. */
+    private final ThreadLocal<PlatformMemoryPool> threadLocPool = new ThreadLocal<>();
+
+    /**
+     * Constructor.
+     *
+     * @param gate Native gateway.
+     * @param dfltCap Default memory chunk capacity.
+     */
+    public PlatformMemoryManagerImpl(@Nullable PlatformCallbackGateway gate, int dfltCap) {
+        this.gate = gate;
+        this.dfltCap = dfltCap;
+    }
+
+    /** {@inheritDoc} */
+    @Override public PlatformMemory allocate() {
+        return allocate(dfltCap);
+    }
+
+    /** {@inheritDoc} */
+    @Override public PlatformMemory allocate(int cap) {
+        return pool().allocate(cap);
+    }
+
+    /** {@inheritDoc} */
+    @Override public PlatformMemory get(long memPtr) {
+        int flags = flags(memPtr);
+
+        return isExternal(flags) ? new PlatformExternalMemory(gate, memPtr) :
+            isPooled(flags) ? pool().get(memPtr) : new PlatformUnpooledMemory(memPtr);
+    }
+
+    /**
+     * Gets or creates thread-local memory pool.
+     *
+     * @return Memory pool.
+     */
+    private PlatformMemoryPool pool() {
+        PlatformMemoryPool pool = threadLocPool.get();
+
+        if (pool == null) {
+            pool = new PlatformMemoryPool();
+
+            threadLocPool.set(pool);
+        }
+
+        return pool;
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/2225f8d2/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/memory/PlatformMemoryPool.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/memory/PlatformMemoryPool.java b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/memory/PlatformMemoryPool.java
new file mode 100644
index 0000000..75db4b9
--- /dev/null
+++ b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/memory/PlatformMemoryPool.java
@@ -0,0 +1,133 @@
+/*
+ * 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.platform.memory;
+
+import static org.apache.ignite.internal.processors.platform.memory.PlatformMemoryUtils.*;
+
+/**
+ * Memory pool associated with a thread.
+ */
+public class PlatformMemoryPool {
+    /** base pointer. */
+    private final long poolPtr;
+
+    /** First pooled memory chunk. */
+    private PlatformPooledMemory mem1;
+
+    /** Second pooled memory chunk. */
+    private PlatformPooledMemory mem2;
+
+    /** Third pooled memory chunk. */
+    private PlatformPooledMemory mem3;
+
+    /**
+     * Constructor.
+     */
+    public PlatformMemoryPool() {
+        poolPtr = allocatePool();
+
+        sun.misc.Cleaner.create(this, new CleanerRunnable(poolPtr));
+    }
+
+    /**
+     * Allocate memory chunk, optionally pooling it.
+     *
+     * @param cap Minimum capacity.
+     * @return Memory chunk.
+     */
+    public PlatformMemory allocate(int cap) {
+        long memPtr = allocatePooled(poolPtr, cap);
+
+        // memPtr == 0 means that we failed to acquire thread-local memory chunk, so fallback to unpooled memory.
+        return memPtr != 0 ? get(memPtr) : new PlatformUnpooledMemory(allocateUnpooled(cap));
+    }
+
+    /**
+     * Re-allocate existing pool memory chunk.
+     *
+     * @param memPtr Memory pointer.
+     * @param cap Minimum capacity.
+     */
+    void reallocate(long memPtr, int cap) {
+        reallocatePooled(memPtr, cap);
+    }
+
+    /**
+     * Release pooled memory chunk.
+     *
+     * @param memPtr Memory pointer.
+     */
+    void release(long memPtr) {
+        releasePooled(memPtr);
+    }
+
+    /**
+     * Get pooled memory chunk.
+     *
+     * @param memPtr Memory pointer.
+     * @return Memory chunk.
+     */
+    public PlatformMemory get(long memPtr) {
+        long delta = memPtr - poolPtr;
+
+        if (delta == POOL_HDR_OFF_MEM_1) {
+            if (mem1 == null)
+                mem1 = new PlatformPooledMemory(this, memPtr);
+
+            return mem1;
+        }
+        else if (delta == POOL_HDR_OFF_MEM_2) {
+            if (mem2 == null)
+                mem2 = new PlatformPooledMemory(this, memPtr);
+
+            return mem2;
+        }
+        else {
+            assert delta == POOL_HDR_OFF_MEM_3;
+
+            if (mem3 == null)
+                mem3 = new PlatformPooledMemory(this, memPtr);
+
+            return mem3;
+        }
+    }
+
+    /**
+     * Cleaner runnable.
+     */
+    private static class CleanerRunnable implements Runnable {
+        /** Pointer. */
+        private final long poolPtr;
+
+        /**
+         * Constructor.
+         *
+         * @param poolPtr Pointer.
+         */
+        private CleanerRunnable(long poolPtr) {
+            assert poolPtr != 0;
+
+            this.poolPtr = poolPtr;
+        }
+
+        /** {@inheritDoc} */
+        @Override public void run() {
+            PlatformMemoryUtils.releasePool(poolPtr);
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/2225f8d2/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/memory/PlatformMemoryUtils.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/memory/PlatformMemoryUtils.java b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/memory/PlatformMemoryUtils.java
new file mode 100644
index 0000000..c5ca971
--- /dev/null
+++ b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/memory/PlatformMemoryUtils.java
@@ -0,0 +1,468 @@
+/*
+ * 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.platform.memory;
+
+import org.apache.ignite.internal.util.*;
+import sun.misc.*;
+
+import java.nio.*;
+
+/**
+ * Utility classes for memory management.
+ */
+public class PlatformMemoryUtils {
+    /** Unsafe instance. */
+    public static final Unsafe UNSAFE = GridUnsafe.unsafe();
+
+    /** Array offset: boolean. */
+    public static final long BOOLEAN_ARR_OFF = UNSAFE.arrayBaseOffset(boolean[].class);
+
+    /** Array offset: byte. */
+    public static final long BYTE_ARR_OFF = UNSAFE.arrayBaseOffset(byte[].class);
+
+    /** Array offset: short. */
+    public static final long SHORT_ARR_OFF = UNSAFE.arrayBaseOffset(short[].class);
+
+    /** Array offset: char. */
+    public static final long CHAR_ARR_OFF = UNSAFE.arrayBaseOffset(char[].class);
+
+    /** Array offset: int. */
+    public static final long INT_ARR_OFF = UNSAFE.arrayBaseOffset(int[].class);
+
+    /** Array offset: float. */
+    public static final long FLOAT_ARR_OFF = UNSAFE.arrayBaseOffset(float[].class);
+
+    /** Array offset: long. */
+    public static final long LONG_ARR_OFF = UNSAFE.arrayBaseOffset(long[].class);
+
+    /** Array offset: double. */
+    public static final long DOUBLE_ARR_OFF = UNSAFE.arrayBaseOffset(double[].class);
+
+    /** Whether little endian is used on the platform. */
+    public static final boolean LITTLE_ENDIAN = ByteOrder.nativeOrder() == ByteOrder.LITTLE_ENDIAN;
+
+    /** Header length. */
+    public static final int POOL_HDR_LEN = 64;
+
+    /** Pool header offset: first memory chunk. */
+    public static final int POOL_HDR_OFF_MEM_1 = 0;
+
+    /** Pool header offset: second memory chunk. */
+    public static final int POOL_HDR_OFF_MEM_2 = 20;
+
+    /** Pool header offset: third memory chunk. */
+    public static final int POOL_HDR_OFF_MEM_3 = 40;
+
+    /** Memory chunk header length. */
+    public static final int MEM_HDR_LEN = 20;
+
+    /** Offset: capacity. */
+    public static final int MEM_HDR_OFF_CAP = 8;
+
+    /** Offset: length. */
+    public static final int MEM_HDR_OFF_LEN = 12;
+
+    /** Offset: flags. */
+    public static final int MEM_HDR_OFF_FLAGS = 16;
+
+    /** Flag: external. */
+    public static final int FLAG_EXT = 0x1;
+
+    /** Flag: pooled. */
+    public static final int FLAG_POOLED = 0x2;
+
+    /** Flag: whether this pooled memory chunk is acquired. */
+    public static final int FLAG_ACQUIRED = 0x4;
+
+    /** --- COMMON METHODS. --- */
+
+    /**
+     * Gets data pointer for the given memory chunk.
+     *
+     * @param memPtr Memory pointer.
+     * @return Data pointer.
+     */
+    public static long data(long memPtr) {
+        return UNSAFE.getLong(memPtr);
+    }
+
+    /**
+     * Gets capacity for the given memory chunk.
+     *
+     * @param memPtr Memory pointer.
+     * @return Capacity.
+     */
+    public static int capacity(long memPtr) {
+        return UNSAFE.getInt(memPtr + MEM_HDR_OFF_CAP);
+    }
+
+    /**
+     * Sets capacity for the given memory chunk.
+     *
+     * @param memPtr Memory pointer.
+     * @param cap Capacity.
+     */
+    public static void capacity(long memPtr, int cap) {
+        assert !isExternal(memPtr) : "Attempt to update external memory chunk capacity: " + memPtr;
+
+        UNSAFE.putInt(memPtr + MEM_HDR_OFF_CAP, cap);
+    }
+
+    /**
+     * Gets length for the given memory chunk.
+     *
+     * @param memPtr Memory pointer.
+     * @return Length.
+     */
+    public static int length(long memPtr) {
+        return UNSAFE.getInt(memPtr + MEM_HDR_OFF_LEN);
+    }
+
+    /**
+     * Sets length for the given memory chunk.
+     *
+     * @param memPtr Memory pointer.
+     * @param len Length.
+     */
+    public static void length(long memPtr, int len) {
+        UNSAFE.putInt(memPtr + MEM_HDR_OFF_LEN, len);
+    }
+
+    /**
+     * Gets flags for the given memory chunk.
+     *
+     * @param memPtr Memory pointer.
+     * @return Flags.
+     */
+    public static int flags(long memPtr) {
+        return UNSAFE.getInt(memPtr + MEM_HDR_OFF_FLAGS);
+    }
+
+    /**
+     * Sets flags for the given memory chunk.
+     *
+     * @param memPtr Memory pointer.
+     * @param flags Flags.
+     */
+    public static void flags(long memPtr, int flags) {
+        assert !isExternal(memPtr) : "Attempt to update external memory chunk flags: " + memPtr;
+
+        UNSAFE.putInt(memPtr + MEM_HDR_OFF_FLAGS, flags);
+    }
+
+    /**
+     * Check whether this memory chunk is external.
+     *
+     * @param memPtr Memory pointer.
+     * @return {@code True} if owned by native platform.
+     */
+    public static boolean isExternal(long memPtr) {
+        return isExternal(flags(memPtr));
+    }
+
+    /**
+     * Check whether flags denote that this memory chunk is external.
+     *
+     * @param flags Flags.
+     * @return {@code True} if owned by native platform.
+     */
+    public static boolean isExternal(int flags) {
+        return (flags & FLAG_EXT) == FLAG_EXT;
+    }
+
+    /**
+     * Check whether this memory chunk is pooled.
+     *
+     * @param memPtr Memory pointer.
+     * @return {@code True} if pooled.
+     */
+    public static boolean isPooled(long memPtr) {
+        return isPooled(flags(memPtr));
+    }
+
+    /**
+     * Check whether flags denote pooled memory chunk.
+     *
+     * @param flags Flags.
+     * @return {@code True} if pooled.
+     */
+    public static boolean isPooled(int flags) {
+        return (flags & FLAG_POOLED) != 0;
+    }
+
+    /**
+     * Check whether this memory chunk is pooled and acquired.
+     *
+     * @param memPtr Memory pointer.
+     * @return {@code True} if pooled and acquired.
+     */
+    public static boolean isAcquired(long memPtr) {
+        return isAcquired(flags(memPtr));
+    }
+
+    /**
+     * Check whether flags denote pooled and acquired memory chunk.
+     *
+     * @param flags Flags.
+     * @return {@code True} if acquired.
+     */
+    public static boolean isAcquired(int flags) {
+        assert isPooled(flags);
+
+        return (flags & FLAG_ACQUIRED) != 0;
+    }
+
+    /** --- UNPOOLED MEMORY MANAGEMENT. --- */
+
+    /**
+     * Allocate unpooled memory chunk.
+     *
+     * @param cap Minimum capacity.
+     * @return New memory pointer.
+     */
+    public static long allocateUnpooled(int cap) {
+        assert cap > 0;
+
+        long memPtr = UNSAFE.allocateMemory(MEM_HDR_LEN);
+        long dataPtr = UNSAFE.allocateMemory(cap);
+
+        UNSAFE.putLong(memPtr, dataPtr);              // Write address.
+        UNSAFE.putInt(memPtr + MEM_HDR_OFF_CAP, cap); // Write capacity.
+        UNSAFE.putInt(memPtr + MEM_HDR_OFF_LEN, 0);   // Write length.
+        UNSAFE.putInt(memPtr + MEM_HDR_OFF_FLAGS, 0); // Write flags.
+
+        return memPtr;
+    }
+
+    /**
+     * Reallocate unpooled memory chunk.
+     *
+     * @param memPtr Memory pointer.
+     * @param cap Minimum capacity.
+     */
+    public static void reallocateUnpooled(long memPtr, int cap) {
+        assert cap > 0;
+
+        assert !isExternal(memPtr) : "Attempt to reallocate external memory chunk directly: " + memPtr;
+        assert !isPooled(memPtr) : "Attempt to reallocate pooled memory chunk directly: " + memPtr;
+
+        long dataPtr = data(memPtr);
+
+        long newDataPtr = UNSAFE.reallocateMemory(dataPtr, cap);
+
+        if (dataPtr != newDataPtr)
+            UNSAFE.putLong(memPtr, newDataPtr); // Write new data address if needed.
+
+        UNSAFE.putInt(memPtr + MEM_HDR_OFF_CAP, cap); // Write new capacity.
+    }
+
+    /**
+     * Release unpooled memory chunk.
+     *
+     * @param memPtr Memory pointer.
+     */
+    public static void releaseUnpooled(long memPtr) {
+        assert !isExternal(memPtr) : "Attempt to release external memory chunk directly: " + memPtr;
+        assert !isPooled(memPtr) : "Attempt to release pooled memory chunk directly: " + memPtr;
+
+        UNSAFE.freeMemory(data(memPtr));
+        UNSAFE.freeMemory(memPtr);
+    }
+
+    /** --- POOLED MEMORY MANAGEMENT. --- */
+
+    /**
+     * Allocate pool memory.
+     *
+     * @return Pool pointer.
+     */
+    public static long allocatePool() {
+        long poolPtr = UNSAFE.allocateMemory(POOL_HDR_LEN);
+
+        UNSAFE.setMemory(poolPtr, POOL_HDR_LEN, (byte)0);
+
+        flags(poolPtr + POOL_HDR_OFF_MEM_1, FLAG_POOLED);
+        flags(poolPtr + POOL_HDR_OFF_MEM_2, FLAG_POOLED);
+        flags(poolPtr + POOL_HDR_OFF_MEM_3, FLAG_POOLED);
+
+        return poolPtr;
+    }
+
+    /**
+     * Release pool memory.
+     *
+     * @param poolPtr Pool pointer.
+     */
+    public static void releasePool(long poolPtr) {
+        // Clean predefined memory chunks.
+        long mem = UNSAFE.getLong(poolPtr + POOL_HDR_OFF_MEM_1);
+
+        if (mem != 0)
+            UNSAFE.freeMemory(mem);
+
+        mem = UNSAFE.getLong(poolPtr + POOL_HDR_OFF_MEM_2);
+
+        if (mem != 0)
+            UNSAFE.freeMemory(mem);
+
+        mem = UNSAFE.getLong(poolPtr + POOL_HDR_OFF_MEM_3);
+
+        if (mem != 0)
+            UNSAFE.freeMemory(mem);
+
+        // Clean pool chunk.
+        UNSAFE.freeMemory(poolPtr);
+    }
+
+    /**
+     * Allocate pooled memory chunk.
+     *
+     * @param poolPtr Pool pointer.
+     * @param cap Capacity.
+     * @return Cross-platform memory pointer or {@code 0} in case there are no free memory chunks in the pool.
+     */
+    public static long allocatePooled(long poolPtr, int cap) {
+        long memPtr1 = poolPtr + POOL_HDR_OFF_MEM_1;
+
+        if (isAcquired(memPtr1)) {
+            long memPtr2 = poolPtr + POOL_HDR_OFF_MEM_2;
+
+            if (isAcquired(memPtr2)) {
+                long memPtr3 = poolPtr + POOL_HDR_OFF_MEM_3;
+
+                if (isAcquired(memPtr3))
+                    return 0L;
+                else {
+                    allocatePooled0(memPtr3, cap);
+
+                    return memPtr3;
+                }
+            }
+            else {
+                allocatePooled0(memPtr2, cap);
+
+                return memPtr2;
+            }
+        }
+        else {
+            allocatePooled0(memPtr1, cap);
+
+            return memPtr1;
+        }
+    }
+
+    /**
+     * Internal pooled memory chunk allocation routine.
+     *
+     * @param memPtr Memory pointer.
+     * @param cap Capacity.
+     */
+    private static void allocatePooled0(long memPtr, int cap) {
+        assert !isExternal(memPtr);
+        assert isPooled(memPtr);
+        assert !isAcquired(memPtr);
+
+        long data = UNSAFE.getLong(memPtr);
+
+        if (data == 0) {
+            // First allocation of the chunk.
+            data = UNSAFE.allocateMemory(cap);
+
+            UNSAFE.putLong(memPtr, data);
+            UNSAFE.putInt(memPtr + MEM_HDR_OFF_CAP, cap);
+        }
+        else {
+            // Ensure that we have enough capacity.
+            int curCap = capacity(memPtr);
+
+            if (cap > curCap) {
+                data = UNSAFE.reallocateMemory(data, cap);
+
+                UNSAFE.putLong(memPtr, data);
+                UNSAFE.putInt(memPtr + MEM_HDR_OFF_CAP, cap);
+            }
+        }
+
+        flags(memPtr, FLAG_POOLED | FLAG_ACQUIRED);
+    }
+
+    /**
+     * Reallocate pooled memory chunk.
+     *
+     * @param memPtr Memory pointer.
+     * @param cap Minimum capacity.
+     */
+    public static void reallocatePooled(long memPtr, int cap) {
+        assert !isExternal(memPtr);
+        assert isPooled(memPtr);
+        assert isAcquired(memPtr);
+
+        long data = UNSAFE.getLong(memPtr);
+
+        assert data != 0;
+
+        int curCap = capacity(memPtr);
+
+        if (cap > curCap) {
+            data = UNSAFE.reallocateMemory(data, cap);
+
+            UNSAFE.putLong(memPtr, data);
+            UNSAFE.putInt(memPtr + MEM_HDR_OFF_CAP, cap);
+        }
+    }
+
+    /**
+     * Release pooled memory chunk.
+     *
+     * @param memPtr Memory pointer.
+     */
+    public static void releasePooled(long memPtr) {
+        assert !isExternal(memPtr);
+        assert isPooled(memPtr);
+        assert isAcquired(memPtr);
+
+        flags(memPtr, flags(memPtr) ^ FLAG_ACQUIRED);
+    }
+
+    /** --- UTILITY STUFF. --- */
+
+    /**
+     * Reallocate arbitrary memory chunk.
+     *
+     * @param memPtr Memory pointer.
+     * @param cap Capacity.
+     */
+    public static void reallocate(long memPtr, int cap) {
+        int flags = flags(memPtr);
+
+        if (isPooled(flags))
+            reallocatePooled(memPtr, cap);
+        else {
+            assert !isExternal(flags);
+
+            reallocateUnpooled(memPtr, cap);
+        }
+    }
+
+    /**
+     * Constructor.
+     */
+    private PlatformMemoryUtils() {
+        // No-op.
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/2225f8d2/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/memory/PlatformOutputStream.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/memory/PlatformOutputStream.java b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/memory/PlatformOutputStream.java
new file mode 100644
index 0000000..eb2490a
--- /dev/null
+++ b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/memory/PlatformOutputStream.java
@@ -0,0 +1,30 @@
+/*
+ * 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.platform.memory;
+
+import org.apache.ignite.internal.portable.streams.*;
+
+/**
+ * Interop output stream.
+ */
+public interface PlatformOutputStream extends PortableOutputStream {
+    /**
+     * Synchronize output stream with underlying memory
+     */
+    public void synchronize();
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/2225f8d2/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/memory/PlatformOutputStreamImpl.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/memory/PlatformOutputStreamImpl.java b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/memory/PlatformOutputStreamImpl.java
new file mode 100644
index 0000000..6c7c865
--- /dev/null
+++ b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/memory/PlatformOutputStreamImpl.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.platform.memory;
+
+import static org.apache.ignite.internal.processors.platform.memory.PlatformMemoryUtils.*;
+
+/**
+ * Interop output stream implementation.
+ */
+public class PlatformOutputStreamImpl implements PlatformOutputStream {
+    /** Underlying memory chunk. */
+    protected final PlatformMemory mem;
+
+    /** Pointer. */
+    protected long data;
+
+    /** Maximum capacity. */
+    protected int cap;
+
+    /** Current position. */
+    protected int pos;
+
+    /**
+     * Constructor.
+     *
+     * @param mem Underlying memory chunk.
+     */
+    public PlatformOutputStreamImpl(PlatformMemory mem) {
+        this.mem = mem;
+
+        data = mem.data();
+        cap = mem.capacity();
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeByte(byte val) {
+        ensureCapacity(pos + 1);
+
+        UNSAFE.putByte(data + pos++, val);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeByteArray(byte[] val) {
+        copyAndShift(val, BYTE_ARR_OFF, val.length);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeBoolean(boolean val) {
+        writeByte(val ? (byte) 1 : (byte) 0);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeBooleanArray(boolean[] val) {
+        copyAndShift(val, BOOLEAN_ARR_OFF, val.length);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeShort(short val) {
+        ensureCapacity(pos + 2);
+
+        UNSAFE.putShort(data + pos, val);
+
+        shift(2);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeShortArray(short[] val) {
+        copyAndShift(val, SHORT_ARR_OFF, val.length << 1);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeChar(char val) {
+        ensureCapacity(pos + 2);
+
+        UNSAFE.putChar(data + pos, val);
+
+        shift(2);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeCharArray(char[] val) {
+        copyAndShift(val, CHAR_ARR_OFF, val.length << 1);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeInt(int val) {
+        ensureCapacity(pos + 4);
+
+        UNSAFE.putInt(data + pos, val);
+
+        shift(4);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeIntArray(int[] val) {
+        copyAndShift(val, INT_ARR_OFF, val.length << 2);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeInt(int pos, int val) {
+        ensureCapacity(pos + 4);
+
+        UNSAFE.putInt(data + pos, val);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeFloat(float val) {
+        writeInt(Float.floatToIntBits(val));
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeFloatArray(float[] val) {
+        copyAndShift(val, FLOAT_ARR_OFF, val.length << 2);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeLong(long val) {
+        ensureCapacity(pos + 8);
+
+        UNSAFE.putLong(data + pos, val);
+
+        shift(8);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeLongArray(long[] val) {
+        copyAndShift(val, LONG_ARR_OFF, val.length << 3);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeDouble(double val) {
+        writeLong(Double.doubleToLongBits(val));
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeDoubleArray(double[] val) {
+        copyAndShift(val, DOUBLE_ARR_OFF, val.length << 3);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void write(byte[] arr, int off, int len) {
+        copyAndShift(arr, BYTE_ARR_OFF + off, len);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void write(long addr, int cnt) {
+        copyAndShift(null, addr, cnt);
+    }
+
+    /** {@inheritDoc} */
+    @Override public int position() {
+        return pos;
+    }
+
+    /** {@inheritDoc} */
+    @Override public void position(int pos) {
+        ensureCapacity(pos);
+
+        this.pos = pos;
+    }
+
+    /** {@inheritDoc} */
+    @Override public void close() {
+        // No-op.
+    }
+
+    /** {@inheritDoc} */
+    @Override public byte[] array() {
+        assert false;
+
+        throw new UnsupportedOperationException("Should not be called.");
+    }
+
+    /** {@inheritDoc} */
+    @Override public byte[] arrayCopy() {
+        assert false;
+
+        throw new UnsupportedOperationException("Should not be called.");
+    }
+
+    /** {@inheritDoc} */
+    @Override public long offheapPointer() {
+        assert false;
+
+        throw new UnsupportedOperationException("Should not be called.");
+    }
+
+    /** {@inheritDoc} */
+    @Override public boolean hasArray() {
+        assert false;
+
+        throw new UnsupportedOperationException("Should not be called.");
+    }
+
+    /** {@inheritDoc} */
+    @Override public void synchronize() {
+        PlatformMemoryUtils.length(mem.pointer(), pos);
+    }
+
+    /**
+     * Ensure capacity.
+     *
+     * @param reqCap Required byte count.
+     */
+    protected void ensureCapacity(int reqCap) {
+        if (reqCap > cap) {
+            int newCap = cap << 1;
+
+            if (newCap < reqCap)
+                newCap = reqCap;
+
+            mem.reallocate(newCap);
+
+            assert mem.capacity() >= newCap;
+
+            data = mem.data();
+            cap = newCap;
+        }
+    }
+
+    /**
+     * Shift position.
+     *
+     * @param cnt Byte count.
+     */
+    protected void shift(int cnt) {
+        pos += cnt;
+    }
+
+    /**
+     * Copy source object to the stream shifting position afterwards.
+     *
+     * @param src Source.
+     * @param off Offset.
+     * @param len Length.
+     */
+    private void copyAndShift(Object src, long off, int len) {
+        ensureCapacity(pos + len);
+
+        UNSAFE.copyMemory(src, off, null, data + pos, len);
+
+        shift(len);
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/2225f8d2/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/memory/PlatformPooledMemory.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/memory/PlatformPooledMemory.java b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/memory/PlatformPooledMemory.java
new file mode 100644
index 0000000..98a9a58
--- /dev/null
+++ b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/memory/PlatformPooledMemory.java
@@ -0,0 +1,63 @@
+/*
+ * 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.platform.memory;
+
+import static org.apache.ignite.internal.processors.platform.memory.PlatformMemoryUtils.*;
+
+/**
+ * Interop pooled memory chunk.
+ */
+public class PlatformPooledMemory extends PlatformAbstractMemory {
+    /** Owning memory pool. */
+    private final PlatformMemoryPool pool;
+
+    /**
+     * Constructor.
+     *
+     * @param pool Owning memory pool.
+     * @param memPtr Cross-platform memory pointer.
+     */
+    public PlatformPooledMemory(PlatformMemoryPool pool, long memPtr) {
+        super(memPtr);
+
+        assert isPooled(memPtr);
+        assert isAcquired(memPtr);
+
+        this.pool = pool;
+    }
+
+    /** {@inheritDoc} */
+    @Override public void reallocate(int cap) {
+        assert isAcquired(memPtr);
+
+        // Try doubling capacity to avoid excessive allocations.
+        int doubledCap = PlatformMemoryUtils.capacity(memPtr) << 1;
+
+        if (doubledCap > cap)
+            cap = doubledCap;
+
+        pool.reallocate(memPtr, cap);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void close() {
+        assert isAcquired(memPtr);
+
+        pool.release(memPtr); // Return to the pool.
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/2225f8d2/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/memory/PlatformUnpooledMemory.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/memory/PlatformUnpooledMemory.java b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/memory/PlatformUnpooledMemory.java
new file mode 100644
index 0000000..a236dab
--- /dev/null
+++ b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/memory/PlatformUnpooledMemory.java
@@ -0,0 +1,51 @@
+/*
+ * 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.platform.memory;
+
+import static org.apache.ignite.internal.processors.platform.memory.PlatformMemoryUtils.*;
+
+/**
+ * Interop un-pooled memory chunk.
+ */
+public class PlatformUnpooledMemory extends PlatformAbstractMemory {
+    /**
+     * Constructor.
+     *
+     * @param memPtr Cross-platform memory pointer.
+     */
+    public PlatformUnpooledMemory(long memPtr) {
+        super(memPtr);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void reallocate(int cap) {
+        // Try doubling capacity to avoid excessive allocations.
+        int doubledCap = PlatformMemoryUtils.capacity(memPtr) << 1;
+
+        if (doubledCap > cap)
+            cap = doubledCap;
+
+        reallocateUnpooled(memPtr, cap);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void close() {
+        releaseUnpooled(memPtr);
+    }
+}
+

http://git-wip-us.apache.org/repos/asf/ignite/blob/2225f8d2/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/utils/PlatformReaderBiClosure.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/utils/PlatformReaderBiClosure.java b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/utils/PlatformReaderBiClosure.java
new file mode 100644
index 0000000..ea808d7
--- /dev/null
+++ b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/utils/PlatformReaderBiClosure.java
@@ -0,0 +1,34 @@
+/*
+ * 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.platform.utils;
+
+import org.apache.ignite.internal.portable.*;
+import org.apache.ignite.lang.*;
+
+/**
+ * Reader bi-closure.
+ */
+public interface PlatformReaderBiClosure<T1, T2> {
+    /**
+     * Read object from reader.
+     *
+     * @param reader Reader.
+     * @return Object.
+     */
+    IgniteBiTuple<T1, T2> read(PortableRawReaderEx reader);
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/2225f8d2/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/utils/PlatformReaderClosure.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/utils/PlatformReaderClosure.java b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/utils/PlatformReaderClosure.java
new file mode 100644
index 0000000..cd0523c
--- /dev/null
+++ b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/utils/PlatformReaderClosure.java
@@ -0,0 +1,34 @@
+/*
+ * 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.platform.utils;
+
+import org.apache.ignite.internal.portable.*;
+
+/**
+ * Reader closure.
+ */
+public interface PlatformReaderClosure<T> {
+
+    /**
+     * Read object from reader.
+     *
+     * @param reader Reader.
+     * @return Object.
+     */
+    T read(PortableRawReaderEx reader);
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/2225f8d2/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/utils/PlatformWriterBiClosure.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/utils/PlatformWriterBiClosure.java b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/utils/PlatformWriterBiClosure.java
new file mode 100644
index 0000000..89a73b0
--- /dev/null
+++ b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/utils/PlatformWriterBiClosure.java
@@ -0,0 +1,34 @@
+/*
+ * 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.platform.utils;
+
+import org.apache.ignite.internal.portable.*;
+
+/**
+ * Interop writer bi-closure.
+ */
+public interface PlatformWriterBiClosure<T1, T2> {
+    /**
+     * Write values.
+     *
+     * @param writer Writer.
+     * @param val1 Value 1.
+     * @param val2 Value 2.
+     */
+    public void write(PortableRawWriterEx writer, T1 val1, T2 val2);
+}


[39/59] [abbrv] ignite git commit: IGNITE-1303: Created PlatformContext abstraction.

Posted by vk...@apache.org.
IGNITE-1303: Created PlatformContext abstraction.


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

Branch: refs/heads/ignite-884
Commit: 08be80ffee4b24506802cb22130903cb1e749873
Parents: ed974f3
Author: vozerov-gridgain <vo...@gridgain.com>
Authored: Wed Aug 26 12:05:51 2015 +0300
Committer: vozerov-gridgain <vo...@gridgain.com>
Committed: Wed Aug 26 12:05:51 2015 +0300

----------------------------------------------------------------------
 .../processors/platform/PlatformContext.java    | 107 +++++++++++++++++++
 1 file changed, 107 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/08be80ff/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/PlatformContext.java
----------------------------------------------------------------------
diff --git a/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/PlatformContext.java b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/PlatformContext.java
new file mode 100644
index 0000000..0385f46
--- /dev/null
+++ b/modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/PlatformContext.java
@@ -0,0 +1,107 @@
+/*
+ * 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.platform;
+
+import org.apache.ignite.cluster.*;
+import org.apache.ignite.internal.*;
+import org.apache.ignite.internal.portable.*;
+import org.apache.ignite.internal.processors.platform.callback.*;
+import org.apache.ignite.internal.processors.platform.memory.*;
+
+import java.util.*;
+
+/**
+ * Platform context. Acts as an entry point for platform operations.
+ */
+public interface PlatformContext {
+    /**
+     * Gets kernal context.
+     *
+     * @return Kernal context.
+     */
+    public GridKernalContext kernalContext();
+
+    /**
+     * Gets platform memory manager.
+     *
+     * @return Memory manager.
+     */
+    public PlatformMemoryManager memory();
+
+    /**
+     * Gets platform callback gateway.
+     *
+     * @return Callback gateway.
+     */
+    public PlatformCallbackGateway gateway();
+
+    /**
+     * Get memory reader.
+     *
+     * @param mem Memory.
+     * @return Reader.
+     */
+    public PortableRawReaderEx reader(PlatformMemory mem);
+
+    /**
+     * Get memory reader.
+     *
+     * @param in Input.
+     * @return Reader.
+     */
+    public PortableRawReaderEx reader(PlatformInputStream in);
+
+    /**
+     * Get memory writer.
+     *
+     * @param mem Memory.
+     * @return Writer.
+     */
+    public PortableRawWriterEx writer(PlatformMemory mem);
+
+    /**
+     * Get memory writer.
+     *
+     * @param out Output.
+     * @return Writer.
+     */
+    public PortableRawWriterEx writer(PlatformOutputStream out);
+
+    /**
+     * Sends node info to native platform, if necessary.
+     *
+     * @param node Node.
+     */
+    public void addNode(ClusterNode node);
+
+    /**
+     * Writes a node id to a stream and sends node info to native platform, if necessary.
+     *
+     * @param writer Writer.
+     * @param node Node.
+     */
+    public void writeNode(PortableRawWriterEx writer, ClusterNode node);
+
+    /**
+     * Writes multiple node ids to a stream and sends node info to native platform, if necessary.
+     *
+     * @param writer Writer.
+     * @param nodes Nodes.
+     */
+    public void writeNodes(PortableRawWriterEx writer, Collection<ClusterNode> nodes);
+}


[56/59] [abbrv] ignite git commit: Restored backward compatibility for cache objects

Posted by vk...@apache.org.
Restored backward compatibility for cache objects


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

Branch: refs/heads/ignite-884
Commit: 38b3ffdaf2944cb908c45e22e3a1b1b834cf3b6c
Parents: 2938a9b
Author: Valentin Kulichenko <va...@gmail.com>
Authored: Wed Aug 26 15:39:12 2015 -0700
Committer: Valentin Kulichenko <va...@gmail.com>
Committed: Wed Aug 26 15:39:12 2015 -0700

----------------------------------------------------------------------
 .../processors/cacheobject/IgniteCacheObjectProcessor.java         | 2 +-
 .../processors/cacheobject/IgniteCacheObjectProcessorImpl.java     | 2 +-
 .../ignite/internal/processors/query/GridQueryProcessor.java       | 2 +-
 3 files changed, 3 insertions(+), 3 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/38b3ffda/modules/core/src/main/java/org/apache/ignite/internal/processors/cacheobject/IgniteCacheObjectProcessor.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cacheobject/IgniteCacheObjectProcessor.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cacheobject/IgniteCacheObjectProcessor.java
index dc0d1e5..b9b6132 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cacheobject/IgniteCacheObjectProcessor.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cacheobject/IgniteCacheObjectProcessor.java
@@ -78,7 +78,7 @@ public interface IgniteCacheObjectProcessor extends GridProcessor {
      *
      * @return {@code true} If portable objects are enabled.
      */
-    public boolean isPortableEnabled();
+    public boolean isPortableEnabled(CacheConfiguration<?, ?> ccfg);
 
     /**
      * @param obj Portable object to get field from.

http://git-wip-us.apache.org/repos/asf/ignite/blob/38b3ffda/modules/core/src/main/java/org/apache/ignite/internal/processors/cacheobject/IgniteCacheObjectProcessorImpl.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cacheobject/IgniteCacheObjectProcessorImpl.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cacheobject/IgniteCacheObjectProcessorImpl.java
index 3e59b10..e8f7781 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cacheobject/IgniteCacheObjectProcessorImpl.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cacheobject/IgniteCacheObjectProcessorImpl.java
@@ -233,7 +233,7 @@ public class IgniteCacheObjectProcessorImpl extends GridProcessorAdapter impleme
     }
 
     /** {@inheritDoc} */
-    @Override public boolean isPortableEnabled() {
+    @Override public boolean isPortableEnabled(CacheConfiguration<?, ?> ccfg) {
         return false;
     }
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/38b3ffda/modules/core/src/main/java/org/apache/ignite/internal/processors/query/GridQueryProcessor.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/query/GridQueryProcessor.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/query/GridQueryProcessor.java
index f3ad4b2..c8b8166 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/query/GridQueryProcessor.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/query/GridQueryProcessor.java
@@ -140,7 +140,7 @@ public class GridQueryProcessor extends GridProcessorAdapter {
 
                     TypeId typeId;
 
-                    if (valCls == null || ctx.cacheObjects().isPortableEnabled()) {
+                    if (valCls == null || ctx.cacheObjects().isPortableEnabled(ccfg)) {
                         processPortableMeta(meta, desc);
 
                         typeId = new TypeId(ccfg.getName(), ctx.cacheObjects().typeId(meta.getValueType()));


[24/59] [abbrv] ignite git commit: IGNITE-1281 Fixed direct marshalling logic for last-removed field. Closes #32

Posted by vk...@apache.org.
http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/GridCacheSqlQuery.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/GridCacheSqlQuery.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/GridCacheSqlQuery.java
index 77bbe39..c0db018 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/GridCacheSqlQuery.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/GridCacheSqlQuery.java
@@ -55,6 +55,9 @@ public class GridCacheSqlQuery implements Message {
     @GridDirectTransient
     private LinkedHashMap<String, ?> cols;
 
+    /** Field kept for backward compatibility. */
+    private String alias;
+
     /**
      * For {@link Message}.
      */
@@ -149,7 +152,7 @@ public class GridCacheSqlQuery implements Message {
 
         switch (writer.state()) {
             case 0:
-                if (!writer.writeString("alias", null))
+                if (!writer.writeString("alias", alias))
                     return false;
 
                 writer.incrementState();
@@ -180,7 +183,7 @@ public class GridCacheSqlQuery implements Message {
 
         switch (reader.state()) {
             case 0:
-                reader.readString("alias");
+                alias = reader.readString("alias");
 
                 if (!reader.isLastRead())
                     return false;
@@ -205,7 +208,7 @@ public class GridCacheSqlQuery implements Message {
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridCacheSqlQuery.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/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 060afb9..02ec7ac 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
@@ -279,7 +279,7 @@ public class CacheContinuousQueryEntry implements GridCacheDeployable, Message {
 
         }
 
-        return true;
+        return reader.afterMessageRead(CacheContinuousQueryEntry.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/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 e9070a5..e7a11d0 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
@@ -987,7 +987,7 @@ public class IgniteTxEntry implements GridPeerDeployAware, Message {
 
         }
 
-        return true;
+        return reader.afterMessageRead(IgniteTxEntry.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/IgniteTxKey.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/IgniteTxKey.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/IgniteTxKey.java
index f80f960..bbb7559 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/IgniteTxKey.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/IgniteTxKey.java
@@ -167,7 +167,7 @@ public class IgniteTxKey implements Message {
 
         }
 
-        return true;
+        return reader.afterMessageRead(IgniteTxKey.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/TxEntryValueHolder.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/TxEntryValueHolder.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/TxEntryValueHolder.java
index 0bd3d52..4c41e21 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/TxEntryValueHolder.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/TxEntryValueHolder.java
@@ -222,7 +222,7 @@ public class TxEntryValueHolder implements Message {
 
         }
 
-        return true;
+        return reader.afterMessageRead(TxEntryValueHolder.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/version/GridCacheRawVersionedEntry.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/version/GridCacheRawVersionedEntry.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/version/GridCacheRawVersionedEntry.java
index 87fe976..86a9b1b 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/version/GridCacheRawVersionedEntry.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/version/GridCacheRawVersionedEntry.java
@@ -307,7 +307,7 @@ public class GridCacheRawVersionedEntry<K, V> extends DataStreamerEntry implemen
         assert key != null;
         assert !(val != null && valBytes != null);
 
-        return true;
+        return reader.afterMessageRead(GridCacheRawVersionedEntry.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/version/GridCacheVersion.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/version/GridCacheVersion.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/version/GridCacheVersion.java
index 8df54c8..a72c5c2 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/version/GridCacheVersion.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/version/GridCacheVersion.java
@@ -326,7 +326,7 @@ public class GridCacheVersion implements Message, Comparable<GridCacheVersion>,
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridCacheVersion.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/version/GridCacheVersionEx.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/version/GridCacheVersionEx.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/version/GridCacheVersionEx.java
index 812d656..5e848d5 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/version/GridCacheVersionEx.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/version/GridCacheVersionEx.java
@@ -137,7 +137,7 @@ public class GridCacheVersionEx extends GridCacheVersion {
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridCacheVersionEx.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/clock/GridClockDeltaSnapshotMessage.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/clock/GridClockDeltaSnapshotMessage.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/clock/GridClockDeltaSnapshotMessage.java
index dc015b7..23bc179 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/clock/GridClockDeltaSnapshotMessage.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/clock/GridClockDeltaSnapshotMessage.java
@@ -126,7 +126,7 @@ public class GridClockDeltaSnapshotMessage implements Message {
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridClockDeltaSnapshotMessage.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/clock/GridClockDeltaVersion.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/clock/GridClockDeltaVersion.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/clock/GridClockDeltaVersion.java
index ffb02f7..941a1fa 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/clock/GridClockDeltaVersion.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/clock/GridClockDeltaVersion.java
@@ -165,7 +165,7 @@ public class GridClockDeltaVersion implements Message, Comparable<GridClockDelta
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridClockDeltaVersion.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/continuous/GridContinuousMessage.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/continuous/GridContinuousMessage.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/continuous/GridContinuousMessage.java
index fe50fd8..e521a0c 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/continuous/GridContinuousMessage.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/continuous/GridContinuousMessage.java
@@ -248,7 +248,7 @@ public class GridContinuousMessage implements Message {
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridContinuousMessage.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/datastreamer/DataStreamerEntry.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/datastreamer/DataStreamerEntry.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/datastreamer/DataStreamerEntry.java
index 88fda8f..7eadb04 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/datastreamer/DataStreamerEntry.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/datastreamer/DataStreamerEntry.java
@@ -150,7 +150,7 @@ public class DataStreamerEntry implements Map.Entry<KeyCacheObject, CacheObject>
 
         }
 
-        return true;
+        return reader.afterMessageRead(DataStreamerEntry.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/datastreamer/DataStreamerRequest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/datastreamer/DataStreamerRequest.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/datastreamer/DataStreamerRequest.java
index 0d24ee0..fa08b7b 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/datastreamer/DataStreamerRequest.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/datastreamer/DataStreamerRequest.java
@@ -466,7 +466,7 @@ public class DataStreamerRequest implements Message {
 
         }
 
-        return true;
+        return reader.afterMessageRead(DataStreamerRequest.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/datastreamer/DataStreamerResponse.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/datastreamer/DataStreamerResponse.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/datastreamer/DataStreamerResponse.java
index 8aee0d5..e753e32 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/datastreamer/DataStreamerResponse.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/datastreamer/DataStreamerResponse.java
@@ -151,7 +151,7 @@ public class DataStreamerResponse implements Message {
 
         }
 
-        return true;
+        return reader.afterMessageRead(DataStreamerResponse.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsAckMessage.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsAckMessage.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsAckMessage.java
index f52c6de..b551b7b 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsAckMessage.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsAckMessage.java
@@ -177,7 +177,7 @@ public class IgfsAckMessage extends IgfsCommunicationMessage {
 
         }
 
-        return true;
+        return reader.afterMessageRead(IgfsAckMessage.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsBlockKey.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsBlockKey.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsBlockKey.java
index b86eb29..efb84d4 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsBlockKey.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsBlockKey.java
@@ -240,7 +240,7 @@ public final class IgfsBlockKey implements Message, Externalizable, Comparable<I
 
         }
 
-        return true;
+        return reader.afterMessageRead(IgfsBlockKey.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsBlocksMessage.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsBlocksMessage.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsBlocksMessage.java
index fbf2796..120745c 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsBlocksMessage.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsBlocksMessage.java
@@ -158,7 +158,7 @@ public class IgfsBlocksMessage extends IgfsCommunicationMessage {
 
         }
 
-        return true;
+        return reader.afterMessageRead(IgfsBlocksMessage.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsCommunicationMessage.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsCommunicationMessage.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsCommunicationMessage.java
index 309daf1..c2c24ca 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsCommunicationMessage.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsCommunicationMessage.java
@@ -69,7 +69,7 @@ public abstract class IgfsCommunicationMessage implements Message {
         if (!reader.beforeMessageRead())
             return false;
 
-        return true;
+        return reader.afterMessageRead(IgfsCommunicationMessage.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsDeleteMessage.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsDeleteMessage.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsDeleteMessage.java
index 2196525..8656745 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsDeleteMessage.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsDeleteMessage.java
@@ -167,7 +167,7 @@ public class IgfsDeleteMessage extends IgfsCommunicationMessage {
 
         }
 
-        return true;
+        return reader.afterMessageRead(IgfsDeleteMessage.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsFileAffinityRange.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsFileAffinityRange.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsFileAffinityRange.java
index 9736f10..d18ea82 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsFileAffinityRange.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsFileAffinityRange.java
@@ -56,6 +56,9 @@ public class IgfsFileAffinityRange implements Message, Externalizable {
     /** Range end offset (endOff + 1 divisible by block size). */
     private long endOff;
 
+    /** Field kept for backward compatibility. */
+    private boolean done;
+
     /**
      * Empty constructor required by {@link Externalizable}.
      */
@@ -265,7 +268,7 @@ public class IgfsFileAffinityRange implements Message, Externalizable {
 
             case 1:
                 // The field 'done' was removed, but its writing preserved for compatibility reasons.
-                if (!writer.writeBoolean("done", false))
+                if (!writer.writeBoolean("done", done))
                     return false;
 
                 writer.incrementState();
@@ -311,7 +314,7 @@ public class IgfsFileAffinityRange implements Message, Externalizable {
 
             case 1:
                 // field 'done' was removed, but reading preserved for compatibility reasons.
-                reader.readBoolean("done");
+                done = reader.readBoolean("done");
 
                 if (!reader.isLastRead())
                     return false;
@@ -344,7 +347,7 @@ public class IgfsFileAffinityRange implements Message, Externalizable {
 
         }
 
-        return true;
+        return reader.afterMessageRead(IgfsFileAffinityRange.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsFragmentizerRequest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsFragmentizerRequest.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsFragmentizerRequest.java
index 9223009..cf657e3 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsFragmentizerRequest.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsFragmentizerRequest.java
@@ -139,7 +139,7 @@ public class IgfsFragmentizerRequest extends IgfsCommunicationMessage {
 
         }
 
-        return true;
+        return reader.afterMessageRead(IgfsFragmentizerRequest.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsFragmentizerResponse.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsFragmentizerResponse.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsFragmentizerResponse.java
index 9ba6920..6dd7534 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsFragmentizerResponse.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsFragmentizerResponse.java
@@ -101,7 +101,7 @@ public class IgfsFragmentizerResponse extends IgfsCommunicationMessage {
 
         }
 
-        return true;
+        return reader.afterMessageRead(IgfsFragmentizerResponse.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsSyncMessage.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsSyncMessage.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsSyncMessage.java
index 0fb683c..60b56ac 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsSyncMessage.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsSyncMessage.java
@@ -132,7 +132,7 @@ public class IgfsSyncMessage extends IgfsCommunicationMessage {
 
         }
 
-        return true;
+        return reader.afterMessageRead(IgfsSyncMessage.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/messages/GridQueryCancelRequest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/messages/GridQueryCancelRequest.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/messages/GridQueryCancelRequest.java
index c1daa6e..e679ed4 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/messages/GridQueryCancelRequest.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/messages/GridQueryCancelRequest.java
@@ -99,7 +99,7 @@ public class GridQueryCancelRequest implements Message {
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridQueryCancelRequest.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/messages/GridQueryFailResponse.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/messages/GridQueryFailResponse.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/messages/GridQueryFailResponse.java
index a959193..6fd607c 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/messages/GridQueryFailResponse.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/messages/GridQueryFailResponse.java
@@ -125,7 +125,7 @@ public class GridQueryFailResponse implements Message {
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridQueryFailResponse.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/messages/GridQueryNextPageRequest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/messages/GridQueryNextPageRequest.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/messages/GridQueryNextPageRequest.java
index 474cd55..8e95ab8 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/messages/GridQueryNextPageRequest.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/messages/GridQueryNextPageRequest.java
@@ -152,7 +152,7 @@ public class GridQueryNextPageRequest implements Message {
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridQueryNextPageRequest.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/messages/GridQueryNextPageResponse.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/messages/GridQueryNextPageResponse.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/messages/GridQueryNextPageResponse.java
index 0f62ae9..d06e118 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/messages/GridQueryNextPageResponse.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/messages/GridQueryNextPageResponse.java
@@ -29,6 +29,7 @@ import java.util.*;
 /**
  * Next page response.
  */
+@IgniteCodeGeneratingFail
 public class GridQueryNextPageResponse implements Message {
     /** */
     private static final long serialVersionUID = 0L;
@@ -268,7 +269,7 @@ public class GridQueryNextPageResponse implements Message {
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridQueryNextPageResponse.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/messages/GridQueryRequest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/messages/GridQueryRequest.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/messages/GridQueryRequest.java
index 47d1f44..2b04c52 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/messages/GridQueryRequest.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/messages/GridQueryRequest.java
@@ -31,6 +31,7 @@ import java.util.*;
 /**
  * Query request.
  */
+@IgniteCodeGeneratingFail
 public class GridQueryRequest implements Message {
     /** */
     private static final long serialVersionUID = 0L;
@@ -222,6 +223,7 @@ public class GridQueryRequest implements Message {
                     return false;
 
                 writer.incrementState();
+
         }
 
         return true;
@@ -290,9 +292,10 @@ public class GridQueryRequest implements Message {
                     return false;
 
                 reader.incrementState();
+
         }
 
-        return true;
+        return reader.afterMessageRead(GridQueryRequest.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/handlers/task/GridTaskResultRequest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/handlers/task/GridTaskResultRequest.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/handlers/task/GridTaskResultRequest.java
index 3802222..951b1e0 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/handlers/task/GridTaskResultRequest.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/handlers/task/GridTaskResultRequest.java
@@ -153,7 +153,7 @@ public class GridTaskResultRequest implements Message {
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridTaskResultRequest.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/handlers/task/GridTaskResultResponse.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/handlers/task/GridTaskResultResponse.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/handlers/task/GridTaskResultResponse.java
index 66421a1..d29c525 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/handlers/task/GridTaskResultResponse.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/handlers/task/GridTaskResultResponse.java
@@ -199,7 +199,7 @@ public class GridTaskResultResponse implements Message {
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridTaskResultResponse.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/util/GridByteArrayList.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/util/GridByteArrayList.java b/modules/core/src/main/java/org/apache/ignite/internal/util/GridByteArrayList.java
index de5dd47..83939c0 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/util/GridByteArrayList.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/util/GridByteArrayList.java
@@ -461,7 +461,7 @@ public class GridByteArrayList implements Message, Externalizable {
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridByteArrayList.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/util/GridLongList.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/util/GridLongList.java b/modules/core/src/main/java/org/apache/ignite/internal/util/GridLongList.java
index f056f37..1711f03 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/util/GridLongList.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/util/GridLongList.java
@@ -559,7 +559,7 @@ public class GridLongList implements Message, Externalizable {
 
         }
 
-        return true;
+        return reader.afterMessageRead(GridLongList.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/internal/util/nio/GridDirectParser.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/util/nio/GridDirectParser.java b/modules/core/src/main/java/org/apache/ignite/internal/util/nio/GridDirectParser.java
index d632cac..939ad0a 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/util/nio/GridDirectParser.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/util/nio/GridDirectParser.java
@@ -62,7 +62,7 @@ public class GridDirectParser implements GridNioParser {
         if (msg == null && buf.hasRemaining()) {
             msg = msgFactory.create(buf.get());
 
-            ses.addMeta(READER_META_KEY, reader = formatter.reader(msgFactory));
+            ses.addMeta(READER_META_KEY, reader = formatter.reader(msgFactory, msg.getClass()));
         }
 
         boolean finished = false;

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/plugin/extensions/communication/MessageFormatter.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/plugin/extensions/communication/MessageFormatter.java b/modules/core/src/main/java/org/apache/ignite/plugin/extensions/communication/MessageFormatter.java
index 6176561..85f6045 100644
--- a/modules/core/src/main/java/org/apache/ignite/plugin/extensions/communication/MessageFormatter.java
+++ b/modules/core/src/main/java/org/apache/ignite/plugin/extensions/communication/MessageFormatter.java
@@ -41,7 +41,8 @@ public interface MessageFormatter extends Extension {
      * Creates new message reader instance.
      *
      * @param factory Message factory.
+     * @param msgCls Message class to read.
      * @return Message reader.
      */
-    public MessageReader reader(MessageFactory factory);
+    public MessageReader reader(MessageFactory factory, Class<? extends Message> msgCls);
 }

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/plugin/extensions/communication/MessageReader.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/plugin/extensions/communication/MessageReader.java b/modules/core/src/main/java/org/apache/ignite/plugin/extensions/communication/MessageReader.java
index 833e851..11ea97d 100644
--- a/modules/core/src/main/java/org/apache/ignite/plugin/extensions/communication/MessageReader.java
+++ b/modules/core/src/main/java/org/apache/ignite/plugin/extensions/communication/MessageReader.java
@@ -35,9 +35,22 @@ public interface MessageReader {
      */
     public void setBuffer(ByteBuffer buf);
 
+    /**
+     * Callback that must be invoked by a message implementation before message body started decoding.
+     *
+     * @return {@code True} if reading can proceed, {@code false} otherwise.
+     */
     public boolean beforeMessageRead();
 
     /**
+     * Callback that must be invoked by a message implementation after message body finished decoding.
+     *
+     * @param msgCls Message class finishing read stage.
+     * @return {@code True} if reading can proceed, {@code false} otherwise.
+     */
+    public boolean afterMessageRead(Class<? extends Message> msgCls);
+
+    /**
      * Reads {@code byte} value.
      *
      * @param name Field name.

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/spi/IgniteSpiAdapter.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/spi/IgniteSpiAdapter.java b/modules/core/src/main/java/org/apache/ignite/spi/IgniteSpiAdapter.java
index f809d82..0d08171 100644
--- a/modules/core/src/main/java/org/apache/ignite/spi/IgniteSpiAdapter.java
+++ b/modules/core/src/main/java/org/apache/ignite/spi/IgniteSpiAdapter.java
@@ -684,7 +684,7 @@ public abstract class IgniteSpiAdapter implements IgniteSpi, IgniteSpiManagement
                         throw new IgniteException("Failed to write message, node is not started.");
                     }
 
-                    @Override public MessageReader reader(MessageFactory factory) {
+                    @Override public MessageReader reader(MessageFactory factory, Class<? extends Message> msgCls) {
                         throw new IgniteException("Failed to read message, node is not started.");
                     }
                 };

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/spi/collision/jobstealing/JobStealingRequest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/spi/collision/jobstealing/JobStealingRequest.java b/modules/core/src/main/java/org/apache/ignite/spi/collision/jobstealing/JobStealingRequest.java
index 9d9c222..8b95149 100644
--- a/modules/core/src/main/java/org/apache/ignite/spi/collision/jobstealing/JobStealingRequest.java
+++ b/modules/core/src/main/java/org/apache/ignite/spi/collision/jobstealing/JobStealingRequest.java
@@ -95,7 +95,7 @@ public class JobStealingRequest implements Message {
 
         }
 
-        return true;
+        return reader.afterMessageRead(JobStealingRequest.class);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/main/java/org/apache/ignite/spi/communication/tcp/TcpCommunicationSpi.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/spi/communication/tcp/TcpCommunicationSpi.java b/modules/core/src/main/java/org/apache/ignite/spi/communication/tcp/TcpCommunicationSpi.java
index b706edf..4022cf6 100644
--- a/modules/core/src/main/java/org/apache/ignite/spi/communication/tcp/TcpCommunicationSpi.java
+++ b/modules/core/src/main/java/org/apache/ignite/spi/communication/tcp/TcpCommunicationSpi.java
@@ -1510,13 +1510,13 @@ public class TcpCommunicationSpi extends IgniteSpiAdapter
                         return impl.writer();
                     }
 
-                    @Override public MessageReader reader(MessageFactory factory) {
+                    @Override public MessageReader reader(MessageFactory factory, Class<? extends Message> msgCls) {
                         if (impl == null)
                             impl = getSpiContext().messageFormatter();
 
                         assert impl != null;
 
-                        return impl.reader(factory);
+                        return impl.reader(factory, msgCls);
                     }
                 };
 
@@ -2845,13 +2845,13 @@ public class TcpCommunicationSpi extends IgniteSpiAdapter
                         return impl.writer();
                     }
 
-                    @Override public MessageReader reader(MessageFactory factory) {
+                    @Override public MessageReader reader(MessageFactory factory, Class<? extends Message> msgCls) {
                         if (impl == null)
                             impl = getSpiContext().messageFormatter();
 
                         assert impl != null;
 
-                        return impl.reader(factory);
+                        return impl.reader(factory, msgCls);
                     }
                 };
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/89e94b63/modules/core/src/test/java/org/apache/ignite/testframework/GridSpiTestContext.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/testframework/GridSpiTestContext.java b/modules/core/src/test/java/org/apache/ignite/testframework/GridSpiTestContext.java
index 08268af..038af02 100644
--- a/modules/core/src/test/java/org/apache/ignite/testframework/GridSpiTestContext.java
+++ b/modules/core/src/test/java/org/apache/ignite/testframework/GridSpiTestContext.java
@@ -474,7 +474,7 @@ public class GridSpiTestContext implements IgniteSpiContext {
                     return new DirectMessageWriter();
                 }
 
-                @Override public MessageReader reader(MessageFactory factory) {
+                @Override public MessageReader reader(MessageFactory factory, Class<? extends Message> msgCls) {
                     return new DirectMessageReader(factory, this);
                 }
             };


[18/59] [abbrv] ignite git commit: IGNITE-1287: Moved memory management code to Ignite.

Posted by vk...@apache.org.
http://git-wip-us.apache.org/repos/asf/ignite/blob/7b61a097/modules/platform/src/test/dotnet/Apache.Ignite.Core.Tests/Memory/InteropMemoryTest.cs
----------------------------------------------------------------------
diff --git a/modules/platform/src/test/dotnet/Apache.Ignite.Core.Tests/Memory/InteropMemoryTest.cs b/modules/platform/src/test/dotnet/Apache.Ignite.Core.Tests/Memory/InteropMemoryTest.cs
new file mode 100644
index 0000000..e32e622
--- /dev/null
+++ b/modules/platform/src/test/dotnet/Apache.Ignite.Core.Tests/Memory/InteropMemoryTest.cs
@@ -0,0 +1,213 @@
+/*
+ * 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.
+ */
+
+namespace Apache.Ignite.Core.Tests.Memory
+{
+    using System;
+    using Apache.Ignite.Core.Impl.Memory;
+    using NUnit.Framework;
+
+    /// <summary>
+    /// Tests for interop memory.
+    /// </summary>
+    public class InteropMemoryTest
+    {
+        /// <summary>
+        /// Test pooled memory.
+        /// </summary>
+        [Test]
+        public void TestPooled()
+        {
+            PlatformMemoryManager mgr = new PlatformMemoryManager(256);
+
+            var mem1 = mgr.Allocate();
+            Assert.IsTrue(mem1 is PlatformPooledMemory);
+            Assert.IsTrue(mem1.Capacity >= 256);
+            Assert.IsTrue(mem1.Pointer > 0);
+            Assert.IsTrue(mem1.Data > 0);
+            Assert.AreEqual(0, mem1.Length);
+
+            mem1.Reallocate(512);
+
+            Assert.IsTrue(mem1.Capacity >= 512);
+            Assert.IsTrue(mem1.Pointer > 0);
+            Assert.IsTrue(mem1.Data > 0);
+            Assert.AreEqual(0, mem1.Length);
+
+            mem1.Length = 128;
+            Assert.AreEqual(128, mem1.Length);
+
+            mem1.Release();
+
+            Assert.AreSame(mem1, mgr.Allocate());
+            Assert.IsTrue(mem1.Capacity >= 512);
+            Assert.IsTrue(mem1.Pointer > 0);
+            Assert.IsTrue(mem1.Data > 0);
+            Assert.AreEqual(128, mem1.Length);
+
+            IPlatformMemory mem2 = mgr.Allocate();
+            Assert.IsTrue(mem2 is PlatformPooledMemory);
+
+            IPlatformMemory mem3 = mgr.Allocate();
+            Assert.IsTrue(mem3 is PlatformPooledMemory);
+
+            mem1.Release();
+            Assert.AreSame(mem1, mgr.Allocate());
+
+            mem2.Release();
+            Assert.AreSame(mem2, mgr.Allocate());
+
+            mem3.Release();
+            Assert.AreSame(mem3, mgr.Allocate());
+
+            mem1.Release();
+            mem2.Release();
+
+            Assert.AreSame(mem1, mgr.Allocate());
+            Assert.AreSame(mem2, mgr.Allocate());
+
+            IPlatformMemory unpooled = mgr.Allocate();
+
+            try
+            {
+                Assert.IsTrue(unpooled is PlatformUnpooledMemory);
+            }
+            finally
+            {
+                unpooled.Release();
+            }
+        }
+
+        /// <summary>
+        /// Test unpooled memory.
+        /// </summary>
+        [Test]
+        public void TestUnpooled()
+        {
+            PlatformMemoryManager mgr = new PlatformMemoryManager(256);
+
+            for (int i = 0; i < 3; i++)
+                mgr.Allocate();
+
+            IPlatformMemory mem1 = mgr.Allocate();
+            Assert.IsTrue(mem1 is PlatformUnpooledMemory);
+            Assert.IsTrue(mem1.Capacity >= 256);
+            Assert.IsTrue(mem1.Pointer > 0);
+            Assert.IsTrue(mem1.Data > 0);
+            Assert.AreEqual(0, mem1.Length);
+
+            mem1.Reallocate(512);
+            Assert.IsTrue(mem1.Capacity >= 512);
+            Assert.IsTrue(mem1.Pointer > 0);
+            Assert.IsTrue(mem1.Data > 0);
+            Assert.AreEqual(0, mem1.Length);
+
+            mem1.Length = 128;
+            Assert.AreEqual(128, mem1.Length);
+
+            mem1.Release();
+
+            IPlatformMemory mem2 = mgr.Allocate();
+            Assert.AreNotSame(mem1, mem2);
+            Assert.IsTrue(mem2.Capacity >= 256);
+            Assert.IsTrue(mem2.Pointer > 0);
+            Assert.IsTrue(mem2.Data > 0);
+            Assert.AreEqual(0, mem2.Length);
+
+            mem2.Release();
+        }
+
+        /// <summary>
+        /// Test pooled memory stream reallocation initiated from stream.
+        /// </summary>
+        [Test]
+        public void TestPooledStreamReallocate()
+        {
+            IPlatformMemory mem = new PlatformMemoryManager(256).Allocate();
+
+            try
+            {
+                Assert.IsTrue(mem is PlatformPooledMemory);
+
+                CheckStreamReallocate(mem);
+            }
+            finally
+            {
+                mem.Release();
+            }
+        }
+
+        /// <summary>
+        /// Test unpooled memory stream reallocation initiated from stream.
+        /// </summary>
+        [Test]
+        public void TestUnpooledStreamReallocate()
+        {
+            PlatformMemoryManager mgr = new PlatformMemoryManager(256);
+
+            for (int i = 0; i < 3; i++)
+                mgr.Allocate();
+
+            IPlatformMemory mem = mgr.Allocate();
+
+            try
+            {
+                Assert.IsTrue(mem is PlatformUnpooledMemory);
+
+                CheckStreamReallocate(mem);
+            }
+            finally
+            {
+                mem.Release();
+            }
+        }
+
+        /// <summary>
+        /// Check stream reallocation.
+        /// </summary>
+        /// <param name="mem">Memory.</param>
+        private void CheckStreamReallocate(IPlatformMemory mem)
+        {
+            Assert.IsTrue(mem.Capacity >= 256);
+
+            int dataLen = 2048 + 13;
+
+            Random rand = new Random();
+
+            byte[] data = new byte[dataLen];
+
+            for (int i = 0; i < data.Length; i++)
+                data[i] = (byte)rand.Next(0, 255);
+
+            PlatformMemoryStream stream = mem.Stream();
+
+            stream.WriteByteArray(data);
+
+            stream.SynchronizeOutput();
+
+            Assert.IsTrue(mem.Capacity >= dataLen);
+
+            stream.Reset();
+
+            stream.SynchronizeInput();
+
+            byte[] data0 = stream.ReadByteArray(dataLen);
+
+            Assert.AreEqual(data, data0);
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/7b61a097/modules/platform/src/test/dotnet/Apache.Ignite.Core.Tests/TestRunner.cs
----------------------------------------------------------------------
diff --git a/modules/platform/src/test/dotnet/Apache.Ignite.Core.Tests/TestRunner.cs b/modules/platform/src/test/dotnet/Apache.Ignite.Core.Tests/TestRunner.cs
index feb91bc..73c9bcb 100644
--- a/modules/platform/src/test/dotnet/Apache.Ignite.Core.Tests/TestRunner.cs
+++ b/modules/platform/src/test/dotnet/Apache.Ignite.Core.Tests/TestRunner.cs
@@ -31,9 +31,9 @@ namespace Apache.Ignite.Core.Tests
 
             //TestOne(typeof(ContinuousQueryAtomiclBackupTest), "TestInitialQuery");
 
-            TestAll(typeof(IgnitionTest));
+            //TestAll(typeof(IgnitionTest));
 
-            //TestAllInAssembly();
+            TestAllInAssembly();
         }
 
         private static void TestOne(Type testClass, string method)


[20/59] [abbrv] ignite git commit: WIP.

Posted by vk...@apache.org.
WIP.


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

Branch: refs/heads/ignite-884
Commit: 75e04faebe7d9b452f3a7436f3cdfba9171a1ee2
Parents: 7b61a09
Author: vozerov-gridgain <vo...@gridgain.com>
Authored: Tue Aug 25 15:35:23 2015 +0300
Committer: vozerov-gridgain <vo...@gridgain.com>
Committed: Tue Aug 25 15:35:23 2015 +0300

----------------------------------------------------------------------
 .../internal/portable/PortableRawWriterEx.java    | 16 ++++++++++++++++
 .../internal/portable/PortableWriterExImpl.java   | 18 ++++--------------
 2 files changed, 20 insertions(+), 14 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/75e04fae/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableRawWriterEx.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableRawWriterEx.java b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableRawWriterEx.java
index d3e65f0..b0d6c71 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableRawWriterEx.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableRawWriterEx.java
@@ -41,4 +41,20 @@ public interface PortableRawWriterEx extends PortableRawWriter, AutoCloseable {
      * Cleans resources.
      */
     @Override public void close();
+
+    /**
+     * Reserve a room for an integer.
+     *
+     * @return Position in the stream where value is to be written.
+     */
+    public int reserveInt();
+
+    /**
+     * Write int value at the specific position.
+     *
+     * @param pos Position.
+     * @param val Value.
+     * @throws PortableException If failed.
+     */
+    public void writeInt(int pos, int val) throws PortableException;
 }

http://git-wip-us.apache.org/repos/asf/ignite/blob/75e04fae/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableWriterExImpl.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableWriterExImpl.java b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableWriterExImpl.java
index f801632..e100e13 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableWriterExImpl.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableWriterExImpl.java
@@ -1663,23 +1663,13 @@ public class PortableWriterExImpl implements PortableWriter, PortableRawWriterEx
         // No-op.
     }
 
-    /**
-     * Reserve a room for an integer.
-     *
-     * @return Position in the stream where value is to be written.
-     */
-    public int reserveInt() {
+    /** {@inheritDoc} */
+    @Override public int reserveInt() {
         return reserve(LEN_INT);
     }
 
-    /**
-     * Write int value at the specific position.
-     *
-     * @param pos Position.
-     * @param val Value.
-     * @throws PortableException If failed.
-     */
-    public void writeInt(int pos, int val) throws PortableException {
+     /** {@inheritDoc} */
+    @Override public void writeInt(int pos, int val) throws PortableException {
         wCtx.out.writeInt(pos, val);
     }