Code ReOrganization and Re-Architecture changes
[ovsdb.git] / library / src / main / java / org / opendaylight / ovsdb / lib / schema / DatabaseSchema.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.schema;
11
12 import com.fasterxml.jackson.databind.JsonNode;
13 import org.opendaylight.ovsdb.lib.operations.TransactionBuilder;
14 import org.slf4j.Logger;
15 import org.slf4j.LoggerFactory;
16
17 import java.util.HashMap;
18 import java.util.Iterator;
19 import java.util.Map;
20 import java.util.Set;
21
22
23 public class DatabaseSchema {
24
25     public static Logger logger = LoggerFactory.getLogger(DatabaseSchema.class);
26
27     public Map<String, TableSchema> tables;
28
29     public DatabaseSchema(Map<String, TableSchema> tables) {
30         this.tables = tables;
31     }
32
33     public Set<String> getTables() {
34         return this.tables.keySet();
35     }
36
37     public boolean hasTable(String table) {
38         return this.getTables().contains(table);
39     }
40
41     public TableSchema getTable(String table) {
42         return this.tables.get(table);
43     }
44
45     public static DatabaseSchema fromJson(JsonNode json) {
46         if (!json.isObject() || !json.has("tables")) {
47             //todo specific types of exception
48             throw new RuntimeException("bad databaseschema root, expected \"tables\" as child");
49         }
50
51         Map<String, TableSchema> tables = new HashMap<>();
52         //Iterator<Map.Entry<String,JsonNode>> fields = json.fields();
53         for (Iterator<Map.Entry<String, JsonNode>> iter = json.get("tables").fields(); iter.hasNext(); ) {
54             Map.Entry<String, JsonNode> table = iter.next();
55             logger.debug("Read schema for table[{}]:{}", table.getKey(), table.getValue());
56
57             tables.put(table.getKey(), TableSchema.fromJson(table.getKey(), table.getValue()));
58         }
59
60         return new DatabaseSchema(tables);
61     }
62
63     public TransactionBuilder beginTransaction() {
64         return new TransactionBuilder(this);
65     }
66
67     public <E extends TableSchema<E>> TableSchema<E> table(String tableName) {
68         //todo : error handling
69         return tables.get(tableName);
70     }
71
72     public <E extends TableSchema<E>> E table(String tableName, Class<E> clazz) {
73         TableSchema<E> table = table(tableName);
74         return table.as(clazz);
75     }
76 }