Implement acl/group resource in cloud account server.
[platform/upstream/iotivity.git] / cloud / account / src / main / java / org / iotivity / cloud / accountserver / db / MongoDB.java
1 /*
2  * //******************************************************************
3  * //
4  * // Copyright 2016 Samsung Electronics All Rights Reserved.
5  * //
6  * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
7  * //
8  * // Licensed under the Apache License, Version 2.0 (the "License");
9  * // you may not use this file except in compliance with the License.
10  * // You may obtain a copy of the License at
11  * //
12  * //      http://www.apache.org/licenses/LICENSE-2.0
13  * //
14  * // Unless required by applicable law or agreed to in writing, software
15  * // distributed under the License is distributed on an "AS IS" BASIS,
16  * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * // See the License for the specific language governing permissions and
18  * // limitations under the License.
19  * //
20  * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
21  */
22 package org.iotivity.cloud.accountserver.db;
23
24 import java.util.ArrayList;
25 import java.util.HashMap;
26 import java.util.Iterator;
27 import java.util.Map;
28 import java.util.Map.Entry;
29 import java.util.Set;
30
31 import org.bson.Document;
32 import org.iotivity.cloud.util.Log;
33
34 import com.mongodb.MongoClient;
35 import com.mongodb.client.MongoCollection;
36 import com.mongodb.client.MongoCursor;
37 import com.mongodb.client.MongoDatabase;
38 import com.mongodb.client.model.IndexOptions;
39 import com.mongodb.client.result.DeleteResult;
40
41 /**
42  *
43  * This class provides a set of APIs to use MongoDB APIs.
44  *
45  */
46 public class MongoDB {
47
48     private MongoClient   mongoClient = null;
49     private MongoDatabase db          = null;
50
51     /**
52      * API creating MongoClient and initializing MongoDatabase
53      *
54      * @param dbname
55      *            database name to create MongoDatabase
56      * @throws Exception
57      */
58     public MongoDB(String dbname) throws Exception {
59
60         mongoClient = new MongoClient();
61         mongoClient.dropDatabase(dbname);
62         db = mongoClient.getDatabase(dbname);
63     }
64
65     /**
66      * API for creating collection
67      *
68      * @param tableName
69      *            collection name
70      */
71     public void createTable(String tableName) {
72
73         db.createCollection(tableName);
74     }
75
76     /**
77      * API for creating index
78      *
79      * @param tableName
80      *            collection name
81      * @param keys
82      *            key fields of collection
83      */
84     public void createIndex(String tablename, ArrayList<String> keys) {
85
86         Document doc = new Document();
87
88         for (String key : keys) {
89
90             doc.append(key, 1);
91         }
92
93         IndexOptions options = new IndexOptions();
94         options.unique(true);
95
96         db.getCollection(tablename).createIndex(doc, options);
97     }
98
99     /**
100      * API for deleting collection
101      *
102      * @param tableName
103      *            collection name
104      */
105     public void deleteTable(String tableName) {
106
107         db.getCollection(tableName).drop();
108     }
109
110     /**
111      * API for getting database object
112      *
113      */
114     public MongoDatabase getMongoDatabase() {
115
116         return db;
117     }
118
119     public Boolean insertRecord(String tableName, Document doc) {
120
121         if (tableName == null || doc == null)
122             return false;
123
124         MongoCollection<Document> collection = db.getCollection(tableName);
125
126         try {
127
128             if (collection.find(doc).first() == null) {
129
130                 collection.insertOne(doc);
131
132             } else {
133
134                 Log.w("DB insert failed due to duplecated one.");
135                 return false;
136             }
137
138         } catch (Exception e) {
139
140             e.printStackTrace();
141             return false;
142         }
143
144         showRecord(tableName);
145
146         return true;
147     }
148
149     public Boolean insertAndReplaceRecord(String tableName, Document filter,
150             Document doc) {
151
152         if (tableName == null || filter == null || doc == null)
153             return false;
154
155         MongoCollection<Document> collection = db.getCollection(tableName);
156
157         try {
158
159             if (collection.findOneAndReplace(filter, doc) == null) {
160
161                 collection.insertOne(doc);
162             }
163
164         } catch (Exception e) {
165
166             e.printStackTrace();
167             return false;
168         }
169
170         showRecord(tableName);
171
172         return true;
173     }
174
175     public Boolean updateRecord(String tableName, Document filter,
176             Document record) {
177
178         if (tableName == null || filter == null || record == null)
179             return false;
180
181         MongoCollection<Document> collection = db.getCollection(tableName);
182
183         if (collection.findOneAndReplace(filter, record) == null) {
184
185             Log.w("DB update failed due to no matched record!");
186             return false;
187         }
188
189         showRecord(tableName);
190
191         return true;
192     }
193
194     public Boolean deleteRecord(String tableName, Document record) {
195
196         if (tableName == null || record == null)
197             return false;
198
199         MongoCollection<Document> collection = db.getCollection(tableName);
200
201         try {
202
203             DeleteResult result = collection.deleteMany(record);
204
205             if (result.getDeletedCount() == 0) {
206                 Log.w("DB delete failed due to no mached record!");
207                 return false;
208             }
209
210         } catch (Exception e) {
211
212             e.printStackTrace();
213             return false;
214         }
215
216         showRecord(tableName);
217
218         return true;
219     }
220
221     public ArrayList<HashMap<String, Object>> selectRecord(String tableName,
222             Document doc) {
223
224         if (tableName == null || doc == null)
225             return null;
226
227         MongoCollection<Document> collection = db.getCollection(tableName);
228         MongoCursor<Document> cursor = collection.find(doc).iterator();
229
230         ArrayList<HashMap<String, Object>> recordList = new ArrayList<HashMap<String, Object>>();
231
232         try {
233
234             while (cursor.hasNext()) {
235                 Document selectedDoc = cursor.next();
236                 recordList.add(convertDocumentToHashMap(selectedDoc));
237             }
238
239         } finally {
240
241             cursor.close();
242         }
243
244         return recordList;
245     }
246
247     private HashMap<String, Object> convertDocumentToHashMap(Document doc) {
248         HashMap<String, Object> resourceMap = new HashMap<String, Object>();
249
250         Set<Entry<String, Object>> entrySet = doc.entrySet();
251         Iterator<Entry<String, Object>> entryIter = entrySet.iterator();
252
253         while (entryIter.hasNext()) {
254
255             Map.Entry<String, Object> entry = (Map.Entry<String, Object>) entryIter
256                     .next();
257
258             String entryKey = entry.getKey();
259
260             // remove a mongoDB index
261             if (entry.getValue() != null && !entryKey.equals("_id")) {
262
263                 resourceMap.put(entry.getKey(), entry.getValue());
264             }
265         }
266
267         return resourceMap;
268     }
269
270     private void showRecord(String tableName) {
271
272         MongoCollection<Document> collection = db.getCollection(tableName);
273         MongoCursor<Document> cursor = collection.find().iterator();
274
275         Log.i("<" + tableName + ">");
276
277         HashMap<String, Object> records = null;
278         int index = 0;
279         while (cursor.hasNext()) {
280
281             Document doc = cursor.next();
282             records = convertDocumentToHashMap(doc);
283
284             Log.i("[" + index + "] " + records.toString());
285             index++;
286         }
287
288         cursor.close();
289     }
290 }