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

[01/19] ignite git commit: master - Fixed RAT excludes.

Repository: ignite
Updated Branches:
  refs/heads/ignite-1093 ccdbd27dd -> 35f3b5d6d


master - Fixed RAT excludes.


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

Branch: refs/heads/ignite-1093
Commit: 321b78a758450a5bf45d3fdeca42e88edca549c4
Parents: ff666ca
Author: Alexey Goncharuk <ag...@gridgain.com>
Authored: Mon Aug 24 12:19:15 2015 -0700
Committer: Alexey Goncharuk <ag...@gridgain.com>
Committed: Mon Aug 24 12:19:15 2015 -0700

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


http://git-wip-us.apache.org/repos/asf/ignite/blob/321b78a7/parent/pom.xml
----------------------------------------------------------------------
diff --git a/parent/pom.xml b/parent/pom.xml
index efa6494..49aa36f 100644
--- a/parent/pom.xml
+++ b/parent/pom.xml
@@ -725,6 +725,10 @@
                                         <exclude>ipc/shmem/igniteshmem/.deps/*</exclude><!--tmp files-->
                                         <exclude>ipc/shmem/igniteshmem/libigniteshmem.la</exclude><!--tmp (not under VCS)-->
                                         <exclude>ipc/shmem/igniteshmem/libigniteshmem_la-org_apache_ignite_internal_util_ipc_shmem_IpcSharedMemoryUtils.lo</exclude><!--tmp (not under VCS)-->
+                                        <!--platform-->
+                                        <exclude>src/main/dotnet/Apache.Ignite.Core/Apache.Ignite.Core.csproj</exclude>
+                                        <exclude>src/main/dotnet/Apache.Ignite.sln</exclude>
+                                        <exclude>src/test/dotnet/Apache.Ignite.Core.Tests/Apache.Ignite.Core.Tests.csproj</exclude>
                                     </excludes>
                                 </configuration>
                             </execution>


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

Posted by sb...@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;
+    }
+}


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

Posted by sb...@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();
+}


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

Posted by sb...@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);
+    }
+}


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

Posted by sb...@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;
+        }
+    }
+}


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

Posted by sb...@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);
+        }
+    }
+}


[15/19] ignite git commit: ignite-1258: portable objects API support in Ignite

Posted by sb...@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;
+        }
+    }
+}


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

Posted by sb...@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;
+    }
+}


[17/19] ignite git commit: ignite-1258: updated classnames.properties file

Posted by sb...@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-1093
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


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

Posted by sb...@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");
+        }
+    }
+}


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

Posted by sb...@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


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

Posted by sb...@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);
+    }
+}


[16/19] ignite git commit: ignite-1258: portable objects API support in Ignite

Posted by sb...@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-1093
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;
+    }
+}


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

Posted by sb...@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;
+    }
+}


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

Posted by sb...@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/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-->


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

Posted by sb...@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>

[19/19] ignite git commit: Merge remote-tracking branch 'remotes/origin/master' into ignite-1093

Posted by sb...@apache.org.
Merge remote-tracking branch 'remotes/origin/master' into ignite-1093

Conflicts:
	modules/core/src/main/java/org/apache/ignite/internal/managers/communication/GridIoMessageFactory.java


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

Branch: refs/heads/ignite-1093
Commit: 35f3b5d6d4dc076811b31a11a5d97289411abb61
Parents: ccdbd27 3fbb99c
Author: Anton Vinogradov <vi...@gmail.com>
Authored: Tue Aug 25 12:04:02 2015 +0300
Committer: Anton Vinogradov <vi...@gmail.com>
Committed: Tue Aug 25 12:04:02 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/GridKernalContext.java      |    6 +
 .../ignite/internal/GridKernalContextImpl.java  |   15 +-
 .../org/apache/ignite/internal/IgniteEx.java    |    1 +
 .../apache/ignite/internal/IgniteKernal.java    |   13 +-
 .../communication/GridIoMessageFactory.java     |    8 +-
 .../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    |   70 +-
 .../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 +-
 .../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 -
 .../visor/cache/VisorCacheClearTask.java        |   11 +-
 .../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 +
 .../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 +-
 .../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 +
 .../tcp/TcpDiscoverySpiStartStopSelfTest.java   |    2 +-
 .../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 +
 .../ignite/internal/platform/Platform.java      |   39 -
 .../internal/platform/PlatformBootstrap.java    |    5 +-
 .../internal/platform/PlatformIgnition.java     |   19 +-
 .../platform/memory/PlatformInputStream.java    |    4 +-
 .../platform/memory/PlatformOutputStream.java   |    4 +-
 .../org/apache/ignite/IgniteSpringBean.java     |    7 +
 parent/pom.xml                                  |   12 +
 174 files changed, 31887 insertions(+), 688 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/35f3b5d6/modules/core/src/main/java/org/apache/ignite/configuration/CacheConfiguration.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/ignite/blob/35f3b5d6/modules/core/src/main/java/org/apache/ignite/internal/managers/communication/GridIoMessageFactory.java
----------------------------------------------------------------------
diff --cc modules/core/src/main/java/org/apache/ignite/internal/managers/communication/GridIoMessageFactory.java
index 7ddbfb7,2acfd2b..9d25de2
--- 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
@@@ -601,11 -602,11 +602,16 @@@ public class GridIoMessageFactory imple
                  break;
  
              case 113:
+                 msg = new PortableObjectImpl();
+ 
+                 break;
+ 
 -            // [-3..112] - this
++            case 114:
 +                msg = new GridDhtPartitionSupplyMessageV2();
 +
 +                break;
 +
-             // [-3..113] - this
++            // [-3..114] - this
              // [120..123] - DR
              // [-4..-22] - SQL
              default:

http://git-wip-us.apache.org/repos/asf/ignite/blob/35f3b5d6/modules/core/src/main/java/org/apache/ignite/spi/discovery/tcp/TcpDiscoverySpi.java
----------------------------------------------------------------------


[18/19] ignite git commit: IGNITE-1288: Implemented basic platform processor infrastructure.

Posted by sb...@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-1093
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();


[02/19] ignite git commit: ignite-1205 - Disabled disco data exchange for daemon nodes. Closes #17.

Posted by sb...@apache.org.
ignite-1205 - Disabled disco data exchange for daemon nodes. Closes #17.


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

Branch: refs/heads/ignite-1093
Commit: 2ce02098150dfd66dc7442c60adcf89096c1a270
Parents: 321b78a
Author: Valentin Kulichenko <va...@gmail.com>
Authored: Mon Aug 24 17:33:23 2015 -0700
Committer: Valentin Kulichenko <va...@gmail.com>
Committed: Mon Aug 24 17:33:23 2015 -0700

----------------------------------------------------------------------
 .../processors/cache/GridCacheProcessor.java    | 63 ++++----------------
 .../visor/cache/VisorCacheClearTask.java        | 11 ++--
 .../spi/discovery/tcp/TcpDiscoverySpi.java      |  9 ++-
 .../GridCacheDaemonNodeAbstractSelfTest.java    |  9 +--
 .../local/GridCacheDaemonNodeLocalSelfTest.java | 30 ----------
 .../tcp/TcpDiscoverySpiStartStopSelfTest.java   |  2 +-
 6 files changed, 27 insertions(+), 97 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/2ce02098/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 a7d6bf6..287b3c7 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
@@ -536,15 +536,6 @@ public class GridCacheProcessor extends GridProcessorAdapter {
     /** {@inheritDoc} */
     @SuppressWarnings( {"unchecked"})
     @Override public void start() throws IgniteCheckedException {
-        if (ctx.config().isDaemon()) {
-            sharedCtx = createSharedContext(ctx, CU.startStoreSessionListeners(ctx, null));
-
-            for (GridCacheSharedManager mgr : sharedCtx.managers())
-                mgr.start(sharedCtx);
-
-            return;
-        }
-
         DeploymentMode depMode = ctx.config().getDeploymentMode();
 
         if (!F.isEmpty(ctx.config().getCacheConfiguration())) {
@@ -574,6 +565,9 @@ public class GridCacheProcessor extends GridProcessorAdapter {
             !ctx.config().getTransactionConfiguration().isTxSerializableEnabled());
 
         for (int i = 0; i < cfgs.length; i++) {
+            if (ctx.config().isDaemon() && !CU.isMarshallerCache(cfgs[i].getName()))
+                continue;
+
             checkSerializable(cfgs[i]);
 
             CacheConfiguration<?, ?> cfg = new CacheConfiguration(cfgs[i]);
@@ -691,49 +685,9 @@ public class GridCacheProcessor extends GridProcessorAdapter {
     @SuppressWarnings("unchecked")
     @Override public void onKernalStart() throws IgniteCheckedException {
         try {
-            if (ctx.config().isDaemon()) {
-                for (CacheConfiguration ccfg : ctx.config().getCacheConfiguration()) {
-                    if (CU.isMarshallerCache(ccfg.getName())) {
-                        CacheObjectContext cacheObjCtx = ctx.cacheObjects().contextForCache(ccfg);
-
-                        initialize(internalCachesNames().contains(maskNull(ccfg.getName())), ccfg, cacheObjCtx);
-
-                        GridCacheContext ctx = createCache(ccfg, null, CacheType.MARSHALLER, cacheObjCtx, true);
-
-                        ctx.dynamicDeploymentId(IgniteUuid.randomUuid());
-
-                        sharedCtx.addCacheContext(ctx);
-
-                        GridCacheAdapter cache = ctx.cache();
-
-                        String name = ccfg.getName();
-
-                        caches.put(maskNull(name), cache);
-
-                        startCache(cache);
-
-                        break;
-                    }
-                }
-
-                marshallerCache().context().preloader().syncFuture().listen(new CIX1<IgniteInternalFuture<?>>() {
-                    @Override public void applyx(IgniteInternalFuture<?> f) throws IgniteCheckedException {
-                        ctx.marshallerContext().onMarshallerCachePreloaded(ctx);
-                    }
-                });
-
-                for (GridCacheSharedManager<?, ?> mgr : sharedCtx.managers())
-                    mgr.onKernalStart(false);
-
-                for (GridCacheAdapter<?, ?> cache : caches.values())
-                    onKernalStart(cache);
-
-                return;
-            }
-
             ClusterNode locNode = ctx.discovery().localNode();
 
-            if (!getBoolean(IGNITE_SKIP_CONFIGURATION_CONSISTENCY_CHECK)) {
+            if (!ctx.config().isDaemon() && !getBoolean(IGNITE_SKIP_CONFIGURATION_CONSISTENCY_CHECK)) {
                 for (ClusterNode n : ctx.discovery().remoteNodes()) {
                     if (n.attribute(ATTR_CONSISTENCY_CHECK_SKIPPED))
                         continue;
@@ -765,6 +719,9 @@ public class GridCacheProcessor extends GridProcessorAdapter {
 
             // Start dynamic caches received from collect discovery data.
             for (DynamicCacheDescriptor desc : registeredCaches.values()) {
+                if (ctx.config().isDaemon() && !CU.isMarshallerCache(desc.cacheConfiguration().getName()))
+                    continue;
+
                 boolean started = desc.onStart();
 
                 assert started : "Failed to change started flag for locally configured cache: " + desc;
@@ -805,7 +762,8 @@ public class GridCacheProcessor extends GridProcessorAdapter {
             cacheStartedLatch.countDown();
         }
 
-        ctx.marshallerContext().onMarshallerCacheStarted(ctx);
+        if (!ctx.config().isDaemon())
+            ctx.marshallerContext().onMarshallerCacheStarted(ctx);
 
         marshallerCache().context().preloader().syncFuture().listen(new CIX1<IgniteInternalFuture<?>>() {
             @Override public void applyx(IgniteInternalFuture<?> f) throws IgniteCheckedException {
@@ -863,7 +821,7 @@ public class GridCacheProcessor extends GridProcessorAdapter {
         }
 
         assert caches.containsKey(CU.MARSH_CACHE_NAME) : "Marshaller cache should be started";
-        assert caches.containsKey(CU.UTILITY_CACHE_NAME) : "Utility cache should be started";
+        assert ctx.config().isDaemon() || caches.containsKey(CU.UTILITY_CACHE_NAME) : "Utility cache should be started";
     }
 
     /** {@inheritDoc} */
@@ -3429,4 +3387,3 @@ public class GridCacheProcessor extends GridProcessorAdapter {
         }
     }
 }
-

http://git-wip-us.apache.org/repos/asf/ignite/blob/2ce02098/modules/core/src/main/java/org/apache/ignite/internal/visor/cache/VisorCacheClearTask.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/visor/cache/VisorCacheClearTask.java b/modules/core/src/main/java/org/apache/ignite/internal/visor/cache/VisorCacheClearTask.java
index 4b588b6..2ba489d 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/visor/cache/VisorCacheClearTask.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/visor/cache/VisorCacheClearTask.java
@@ -47,17 +47,17 @@ public class VisorCacheClearTask extends VisorOneNodeTask<String, IgniteBiTuple<
         private static final long serialVersionUID = 0L;
 
         /** */
-        @JobContextResource
-        private ComputeJobContext jobCtx;
+        private final String cacheName;
 
         /** */
         private final IgniteInClosure<IgniteFuture<Integer>> lsnr;
 
         /** */
-        private final IgniteFuture<Integer>[] futs = new IgniteFuture[3];
+        private IgniteFuture<Integer>[] futs;
 
         /** */
-        private final String cacheName;
+        @JobContextResource
+        private ComputeJobContext jobCtx;
 
         /**
          * Create job.
@@ -110,6 +110,9 @@ public class VisorCacheClearTask extends VisorOneNodeTask<String, IgniteBiTuple<
 
         /** {@inheritDoc} */
         @Override protected IgniteBiTuple<Integer, Integer> run(final String cacheName) {
+            if (futs == null)
+                futs = new IgniteFuture[3];
+
             if (futs[0] == null || futs[1] == null || futs[2] == null) {
                 IgniteCache cache = ignite.cache(cacheName);
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/2ce02098/modules/core/src/main/java/org/apache/ignite/spi/discovery/tcp/TcpDiscoverySpi.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/spi/discovery/tcp/TcpDiscoverySpi.java b/modules/core/src/main/java/org/apache/ignite/spi/discovery/tcp/TcpDiscoverySpi.java
index d6a4081..e683dad 100644
--- a/modules/core/src/main/java/org/apache/ignite/spi/discovery/tcp/TcpDiscoverySpi.java
+++ b/modules/core/src/main/java/org/apache/ignite/spi/discovery/tcp/TcpDiscoverySpi.java
@@ -1602,10 +1602,12 @@ public class TcpDiscoverySpi extends IgniteSpiAdapter implements DiscoverySpi, T
      * @return Marshalled exchange data.
      */
     protected Map<Integer, byte[]> collectExchangeData(UUID nodeId) {
+        if (locNode.isDaemon())
+            return Collections.emptyMap();
+
         Map<Integer, Serializable> data = exchange.collect(nodeId);
 
-        if (data == null)
-            return null;
+        assert data != null;
 
         Map<Integer, byte[]> data0 = U.newHashMap(data.size());
 
@@ -1635,6 +1637,9 @@ public class TcpDiscoverySpi extends IgniteSpiAdapter implements DiscoverySpi, T
         Map<Integer, byte[]> data,
         ClassLoader clsLdr)
     {
+        if (locNode.isDaemon())
+            return;
+
         Map<Integer, Serializable> data0 = U.newHashMap(data.size());
 
         for (Map.Entry<Integer, byte[]> entry : data.entrySet()) {

http://git-wip-us.apache.org/repos/asf/ignite/blob/2ce02098/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/GridCacheDaemonNodeAbstractSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/GridCacheDaemonNodeAbstractSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/GridCacheDaemonNodeAbstractSelfTest.java
index ebac314..4badba9 100644
--- a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/GridCacheDaemonNodeAbstractSelfTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/GridCacheDaemonNodeAbstractSelfTest.java
@@ -169,16 +169,11 @@ public abstract class GridCacheDaemonNodeAbstractSelfTest extends GridCommonAbst
             Ignite g2 = startGrid(4);
 
             for (long i = 0; i < Integer.MAX_VALUE; i = (i << 1) + 1) {
-                ClusterNode n;
-
                 // Call mapKeyToNode for normal node.
-                assertNotNull(n = g1.cluster().mapKeyToNode(null, i));
+                assertNotNull(g1.cluster().mapKeyToNode(null, i));
 
                 // Call mapKeyToNode for daemon node.
-                if (cacheMode() == PARTITIONED)
-                    assertEquals(n, g2.cluster().mapKeyToNode(null, i));
-                else
-                    assertNotNull(g2.cluster().mapKeyToNode(null, i));
+                assertNull(g2.cluster().mapKeyToNode(null, i));
             }
         }
         finally {

http://git-wip-us.apache.org/repos/asf/ignite/blob/2ce02098/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/local/GridCacheDaemonNodeLocalSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/local/GridCacheDaemonNodeLocalSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/local/GridCacheDaemonNodeLocalSelfTest.java
index 346dccd..752e8df 100644
--- a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/local/GridCacheDaemonNodeLocalSelfTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/local/GridCacheDaemonNodeLocalSelfTest.java
@@ -31,34 +31,4 @@ public class GridCacheDaemonNodeLocalSelfTest extends GridCacheDaemonNodeAbstrac
     @Override protected CacheMode cacheMode() {
         return LOCAL;
     }
-
-    /** {@inheritDoc} */
-    @Override public void testMapKeyToNode() throws Exception {
-        try {
-            // Start normal nodes.
-            Ignite g1 = startGridsMultiThreaded(3);
-
-            // Start daemon node.
-            daemon = true;
-
-            Ignite g2 = startGrid(4);
-
-            for (long i = 0; i < Integer.MAX_VALUE; i = (i << 1) + 1) {
-                // Call mapKeyToNode for normal node.
-                g1.cluster().mapKeyToNode(null, i);
-
-                try {
-                    g2.cluster().mapKeyToNode(null, i);
-
-                    assert false;
-                }
-                catch (IgniteException e) {
-                    info("Caught expected exception: " + e);
-                }
-            }
-        }
-        finally {
-            stopAllGrids();
-        }
-    }
 }

http://git-wip-us.apache.org/repos/asf/ignite/blob/2ce02098/modules/core/src/test/java/org/apache/ignite/spi/discovery/tcp/TcpDiscoverySpiStartStopSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/spi/discovery/tcp/TcpDiscoverySpiStartStopSelfTest.java b/modules/core/src/test/java/org/apache/ignite/spi/discovery/tcp/TcpDiscoverySpiStartStopSelfTest.java
index 1ce0bcd..f309bdb 100644
--- a/modules/core/src/test/java/org/apache/ignite/spi/discovery/tcp/TcpDiscoverySpiStartStopSelfTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/spi/discovery/tcp/TcpDiscoverySpiStartStopSelfTest.java
@@ -46,7 +46,7 @@ public class TcpDiscoverySpiStartStopSelfTest extends GridSpiStartStopAbstractTe
     public DiscoverySpiDataExchange getDataExchange() {
         return new DiscoverySpiDataExchange() {
             @Override public Map<Integer, Serializable> collect(UUID nodeId) {
-                return null;
+                return Collections.emptyMap();
             }
 
             @Override public void onExchange(UUID joiningNodeId, UUID nodeId, Map<Integer, Serializable> data) {