Refactor ColumnType
[ovsdb.git] / library / impl / src / main / java / org / opendaylight / ovsdb / lib / schema / AtomicColumnType.java
1 /*
2  * Copyright (c) 2014, 2015 EBay Software Foundation and others. All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.ovsdb.lib.schema;
9
10 import com.fasterxml.jackson.databind.JsonNode;
11 import org.opendaylight.ovsdb.lib.notation.OvsdbSet;
12
13 final class AtomicColumnType extends ColumnType {
14     AtomicColumnType(final BaseType baseType) {
15         super(baseType, 1, 1);
16     }
17
18     AtomicColumnType(final BaseType baseType, final long min, final long max) {
19         super(baseType, min, max);
20     }
21
22     /**
23      * Creates a ColumnType from the JsonNode if the implementation knows how to, returns null otherwise.
24      *
25      * @param json the JSONNode object that needs to converted
26      * @return a valid SubType or Null (if the JsonNode does not represent the subtype)
27      */
28     static AtomicColumnType fromJsonNode(final JsonNode json) {
29         if (json.isObject() && json.has("value")) {
30             return null;
31         }
32         BaseType jsonBaseType = BaseType.fromJson(json, "key");
33         return jsonBaseType == null ? null : new AtomicColumnType(jsonBaseType, minFromJson(json), maxFromJson(json));
34     }
35
36     @Override
37     public Object valueFromJson(final JsonNode value) {
38         if (isMultiValued()) {
39             OvsdbSet<Object> result = new OvsdbSet<>();
40             if (value.isArray()) {
41                 if (value.size() == 2) {
42                     if (value.get(0).isTextual() && "set".equals(value.get(0).asText())) {
43                         for (JsonNode node: value.get(1)) {
44                             result.add(getBaseType().toValue(node));
45                         }
46                     } else {
47                         result.add(getBaseType().toValue(value));
48                     }
49                 }
50             } else {
51                 result.add(getBaseType().toValue(value));
52             }
53             return result;
54         } else {
55             return getBaseType().toValue(value);
56         }
57     }
58 }