8024a036204f34dec87609f350a075562f536408
[ovsdb.git] / library / impl / src / main / java / org / opendaylight / ovsdb / lib / schema / BaseType.java
1 /*
2  * Copyright © 2014, 2017 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.error.TyperException;
12 import org.slf4j.Logger;
13
14 public abstract class BaseType<E extends BaseType<E>> {
15     private static final Logger LOG = org.slf4j.LoggerFactory.getLogger(BaseType.class);
16
17     public static BaseType fromJson(final JsonNode json, final String keyorval) {
18         if (json.isValueNode()) {
19             return fromString(json.asText().trim());
20         }
21
22         final JsonNode type = json.get(keyorval);
23         if (type == null) {
24             throw new TyperException("Not a type");
25         }
26         if (type.isTextual()) {
27             //json like  "string"
28             return fromString(type.asText());
29         }
30         if (type.isObject()) {
31             //json like  {"type" : "string", "enum": ["set", ["access", "native-tagged"]]}" for key or value
32             final JsonNode nestedType = type.get("type");
33             if (nestedType != null) {
34                 final BaseType ret = fromString(nestedType.asText());
35                 if (ret != null) {
36                     ret.fillConstraints(type);
37                     return ret;
38                 }
39             }
40         }
41
42         return null;
43     }
44
45     abstract void fillConstraints(JsonNode type);
46
47     public abstract Object toValue(JsonNode value);
48
49     public abstract void validate(Object value);
50
51     private static BaseType fromString(final String type) {
52         switch (type) {
53             case "boolean":
54                 return new BooleanBaseType();
55             case "integer":
56                 return new IntegerBaseType();
57             case "real":
58                 return new RealBaseType();
59             case "string":
60                 return new StringBaseType();
61             case "uuid":
62                 return new UuidBaseType();
63             default:
64                 LOG.debug("Unknown base type {}", type);
65                 return null;
66         }
67     }
68
69 }