xtern commented on a change in pull request #7648: IGNITE-12857 Put custom 
objects via REST
URL: https://github.com/apache/ignite/pull/7648#discussion_r409891652
 
 

 ##########
 File path: 
modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/IgniteBinaryObjectJsonDeserializer.java
 ##########
 @@ -0,0 +1,342 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.rest.protocols.http.jetty;
+
+import com.fasterxml.jackson.core.JsonParser;
+import com.fasterxml.jackson.core.ObjectCodec;
+import com.fasterxml.jackson.databind.DeserializationContext;
+import com.fasterxml.jackson.databind.JsonDeserializer;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.node.JsonNodeType;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import org.apache.ignite.binary.BinaryObject;
+import org.apache.ignite.binary.BinaryObjectBuilder;
+import org.apache.ignite.binary.BinaryObjectException;
+import org.apache.ignite.binary.BinaryType;
+import org.apache.ignite.internal.GridKernalContext;
+import org.apache.ignite.internal.binary.BinaryClassDescriptor;
+import org.apache.ignite.internal.binary.BinaryFieldMetadata;
+import org.apache.ignite.internal.binary.BinaryObjectImpl;
+import org.apache.ignite.internal.binary.BinaryTypeImpl;
+import org.apache.ignite.internal.binary.BinaryUtils;
+import org.apache.ignite.internal.binary.GridBinaryMarshaller;
+import org.apache.ignite.internal.processors.query.QueryTypeDescriptorImpl;
+import org.apache.ignite.internal.util.IgniteUtils;
+import org.jetbrains.annotations.Nullable;
+
+/**
+ * JSON deserializer into the Ignite binary object.
+ */
+public class IgniteBinaryObjectJsonDeserializer extends 
JsonDeserializer<BinaryObjectImpl> {
+    /** Property name to set binary type name. */
+    public static final String BINARY_TYPE_PROPERTY = "binaryTypeName";
+
+    /** Property name to set cache name. */
+    public static final String CACHE_NAME_PROPERTY = "cacheName";
+
+    /** Kernal context. */
+    private final GridKernalContext ctx;
+
+    /**
+     * @param ctx Kernal context.
+     */
+    public IgniteBinaryObjectJsonDeserializer(GridKernalContext ctx) {
+        assert ctx != null;
+
+        this.ctx = ctx;
+    }
+
+    /** {@inheritDoc} */
+    @Override public BinaryObjectImpl deserialize(JsonParser parser, 
DeserializationContext dCtx) throws IOException {
+        String type = (String)dCtx.findInjectableValue(BINARY_TYPE_PROPERTY, 
null, null);
+        String cacheName = 
(String)dCtx.findInjectableValue(CACHE_NAME_PROPERTY, null, null);
+
+        assert type != null;
+
+        if (ctx.marshallerContext().isSystemType(type))
+            throw new IllegalArgumentException("Cannot make binary object 
[type=" + type + "]");
+
+        ObjectCodec mapper = parser.getCodec();
+        JsonNode jsonTree = mapper.readTree(parser);
+
+        return (BinaryObjectImpl)deserialize0(cacheName, type, jsonTree, 
mapper);
+    }
+
+    /**
+     * @param cacheName Cache name.
+     * @param type Type name.
+     * @param node JSON node.
+     * @param mapper JSON object mapper.
+     * @return Deserialized object.
+     * @throws IOException In case of error.
+     */
+    private Object deserialize0(String cacheName, String type, JsonNode node, 
ObjectCodec mapper) throws IOException {
+        if (ctx.marshallerContext().isSystemType(type)) {
+            Class<?> cls = IgniteUtils.classForName(type, null);
+
+            if (cls != null)
+                return mapper.treeToValue(node, cls);
+        }
+
+        BinaryType binType = ctx.cacheObjects().binary().type(type);
+
+        Deserializer deserializer = binType instanceof BinaryTypeImpl ?
+            new BinaryTypeDeserializer(cacheName, (BinaryTypeImpl)binType, 
mapper) :
+            new Deserializer(cacheName, type, mapper);
+
+        return deserializer.deserialize(node);
+    }
+
+    /**
+     * JSON deserializer creates a new binary type using JSON data types.
+     */
+    private class Deserializer {
+        /** New binary type name. */
+        private final String type;
+
+        /** Cache query meta. */
+        protected final Map<String, Class<?>> qryFields;
+
+        /** Cache name. */
+        protected final String cacheName;
+
+        /** JSON object mapper. */
+        protected final ObjectCodec mapper;
+
+        /**
+         * @param cacheName Cache name.
+         * @param type Type name.
+         * @param mapper JSON object mapper.
+         */
+        public Deserializer(@Nullable String cacheName, String type, 
ObjectCodec mapper) {
+            this.type = type;
+            this.mapper = mapper;
+            this.cacheName = cacheName;
+
+            qryFields = qryFields();
+        }
+
+        /**
+         * @return Mapping from field name to its type.
+         */
+        private Map<String, Class<?>> qryFields() {
+            if (ctx.query().moduleEnabled()) {
+                QueryTypeDescriptorImpl desc = 
ctx.query().typeDescriptor(cacheName, type);
+
+                if (desc != null)
+                    return desc.fields();
+            }
+
+            return Collections.emptyMap();
+        }
+
+        /**
+         * Deserialize JSON tree.
+         *
+         * @param tree JSON tree node.
+         * @return Binary object.
+         * @throws IOException In case of error.
+         */
+        public BinaryObject deserialize(JsonNode tree) throws IOException {
+            return binaryValue(type, tree);
+        }
+
+        /**
+         * @param type Ignite binary type name.
+         * @param tree JSON tree node.
+         * @return Binary object.
+         * @throws IOException In case of error.
+         */
+        private BinaryObject binaryValue(String type, JsonNode tree) throws 
IOException {
+            BinaryObjectBuilder builder = ctx.cacheObjects().builder(type);
+
+            Iterator<Map.Entry<String, JsonNode>> itr = tree.fields();
+
+            while (itr.hasNext()) {
+                Map.Entry<String, JsonNode> entry = itr.next();
+
+                String field = entry.getKey();
+                Object val = readValue(field, entry.getValue());
+
+                builder.setField(field, val);
+            }
+
+            return builder.build();
+        }
+
+        /**
+         * @param field Field name.
+         * @param jsonNode JSON node.
+         * @return value.
+         * @throws IOException In case of error.
+         */
+        protected Object readValue(String field, JsonNode jsonNode) throws 
IOException {
+            JsonNodeType nodeType = jsonNode.getNodeType();
+
+            if (nodeType == JsonNodeType.BINARY)
+                return jsonNode.binaryValue();
+
+            if (nodeType == JsonNodeType.BOOLEAN)
+                return jsonNode.booleanValue();
+
+            Class<?> cls = qryFields.get(field.toUpperCase());
+
+            if (cls != null)
+                return mapper.treeToValue(jsonNode, cls);
+
+            switch (nodeType) {
+                case ARRAY:
+                    List<Object> list = new ArrayList<>(jsonNode.size());
+                    Iterator<JsonNode> itr = jsonNode.elements();
+
+                    while (itr.hasNext())
+                        list.add(readValue(field, itr.next()));
+
+                    return list;
+
+                case NUMBER:
+                    return jsonNode.numberValue();
+
+                case OBJECT:
+                    return mapper.treeToValue(jsonNode, cls);
+
+                case STRING:
+                    return jsonNode.asText();
+
+                default:
+                    return null;
+            }
+        }
+    }
+
+    /**
+     * JSON deserializer using the existing Ignite binary type.
+     */
+    private class BinaryTypeDeserializer extends Deserializer {
+        /** Binary type. */
+        private final BinaryTypeImpl binType;
+
+        /** Binary class descriptor. */
+        private final BinaryClassDescriptor binClsDesc;
+
+        /**
+         * @param cacheName Cache name.
+         * @param binaryType Binary type.
+         * @param mapper JSON object mapper.
+         */
+        public BinaryTypeDeserializer(@Nullable String cacheName, 
BinaryTypeImpl binaryType, ObjectCodec mapper) {
+            super(cacheName, binaryType.typeName(), mapper);
+
+            binType = binaryType;
+            binClsDesc = binaryClassDescriptor();
+        }
+
+        /** {@inheritDoc} */
+        @Override public BinaryObject deserialize(JsonNode tree) throws 
IOException {
+            BinaryObjectBuilder builder = 
ctx.cacheObjects().builder(binType.typeName());
+            Map<String, BinaryFieldMetadata> metas = 
binType.metadata().fieldsMap();
+
+            Iterator<Map.Entry<String, JsonNode>> itr = tree.fields();
+
+            while (itr.hasNext()) {
+                Map.Entry<String, JsonNode> entry = itr.next();
+
+                String field = entry.getKey();
+                JsonNode node = tree.get(field);
+                BinaryFieldMetadata meta = metas.get(field);
+
+                Object val = meta != null ?
+                    readValue(meta.typeId(), field, node, binType) : 
readValue(field, node);
+
+                builder.setField(field, val);
+            }
+
+            return builder.build();
+        }
+
+        /**
+         * Extract and cast JSON node value into required object format.
+         *
+         * @param type Field type.
+         * @param field Field name.
+         * @param node JSON node.
+         * @param parentType Parent type.
+         * @return Extracted value.
+         * @throws IOException if failed.
+         */
+        private Object readValue(int type, String field, JsonNode node, 
BinaryTypeImpl parentType) throws IOException {
+            Class<?> baseCls;
+
+            switch (type) {
+                case GridBinaryMarshaller.MAP:
+                    baseCls = Map.class;
+
+                    break;
+                case GridBinaryMarshaller.OBJ_ARR:
+                case GridBinaryMarshaller.COL:
+                case GridBinaryMarshaller.OBJ:
+                case GridBinaryMarshaller.ENUM:
+                    baseCls = fieldClass(field);
+
+                    if (baseCls == null)
+                        return readValue(field, node);
+
+                    break;
+                default:
+                    baseCls = BinaryUtils.FLAG_TO_CLASS.get((byte)type);
+            }
+
+            if (baseCls != null)
+                return mapper.treeToValue(node, baseCls);
+
+            return deserialize0(cacheName, parentType.fieldTypeName(field), 
node, mapper);
+        }
+
+        /**
+         * @return Class descriptor for current binary type or {@code null} if 
the class was not found.
+         */
+        private @Nullable BinaryClassDescriptor binaryClassDescriptor() {
+            try {
+                return binType.context().descriptorForTypeId(false, 
binType.typeId(),null,false);
 
 Review comment:
   done

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


With regards,
Apache Git Services

Reply via email to