Add license info to new files
[ovsdb.git] / ovsdb / src / main / java / org / opendaylight / ovsdb / lib / meta / TableSchema.java
1 /*
2  * Copyright (C) 2014 EBay Software Foundation
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  * Authors : Ashwin Raveendran
9  */
10 package org.opendaylight.ovsdb.lib.meta;
11
12 import com.fasterxml.jackson.databind.JsonNode;
13 import org.opendaylight.ovsdb.Insert;
14 import org.slf4j.Logger;
15 import org.slf4j.LoggerFactory;
16
17 import java.lang.reflect.Constructor;
18 import java.util.HashMap;
19 import java.util.Iterator;
20 import java.util.Map;
21
22
23 public class TableSchema<E extends TableSchema<E>> {
24     protected static final Logger logger = LoggerFactory.getLogger(TableSchema.class);
25     private String name;
26     private Map<String, ColumnSchema> columns;
27
28     public TableSchema() {
29     }
30
31     public TableSchema(String name, Map<String, ColumnSchema> columns) {
32         this.name = name;
33         this.columns = columns;
34     }
35
36     public static TableSchema fromJson(String tableName, JsonNode json) {
37
38         if (!json.isObject() || !json.has("columns")) {
39             //todo specific types of exception
40             throw new RuntimeException("bad tableschema root, expected \"columns\" as child");
41         }
42
43         Map<String, ColumnSchema> columns = new HashMap<>();
44         for (Iterator<Map.Entry<String, JsonNode>> iter = json.get("columns").fields(); iter.hasNext(); ) {
45             Map.Entry<String, JsonNode> column = iter.next();
46             logger.debug("%s:%s", tableName, column.getKey());
47             columns.put(column.getKey(), ColumnSchema.fromJson(column.getKey(), column.getValue()));
48         }
49
50        TableSchema tableSchema = new TableSchema(tableName, columns);
51        return tableSchema;
52     }
53
54     public <E extends TableSchema<E>> E as(Class<E> clazz) {
55         try {
56             Constructor<E> e = clazz.getConstructor(TableSchema.class);
57             return e.newInstance(this);
58         } catch (Exception e) {
59             throw new RuntimeException("exception constructing instance of clazz " + clazz, e);
60         }
61     }
62
63     public Insert<E> insert() {
64         return new Insert<>(this);
65     }
66
67
68
69     public <D> ColumnSchema<E, D> column(String column) {
70         //todo exception handling
71         return columns.get(column);
72     }
73
74     public String getName() {
75         return name;
76     }
77
78     public void setName(String name) {
79         this.name = name;
80     }
81
82     public static class AnyTableSchema extends TableSchema<AnyTableSchema>{}
83 }