Merge branch 'master' into windows-port
[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
26 import org.bson.Document;
27 import org.iotivity.cloud.accountserver.Const;
28 import org.iotivity.cloud.util.Logger;
29
30 import com.mongodb.MongoClient;
31 import com.mongodb.client.MongoCollection;
32 import com.mongodb.client.MongoCursor;
33 import com.mongodb.client.MongoDatabase;
34 import com.mongodb.client.model.Filters;
35
36 /**
37  *
38  * This class provides a set of APIs to use MongoDB APIs.
39  *
40  */
41 public class MongoDB {
42
43     private MongoClient   mongoClient = null;
44     private MongoDatabase db          = null;
45
46     /**
47      * API creating MongoClient and initializing MongoDatabase
48      * 
49      * @param dbname
50      *            database name to create MongoDatabase
51      * @throws Exception
52      */
53     public MongoDB(String dbname) throws Exception {
54         mongoClient = new MongoClient();
55         mongoClient.dropDatabase(dbname);
56         db = mongoClient.getDatabase(dbname);
57     }
58
59     /**
60      * API creating collection
61      * 
62      * @param tableName
63      *            collection name
64      */
65     public void createTable(String tableName) {
66         db.createCollection(tableName);
67     }
68
69     /**
70      * API deleting collection
71      * 
72      * @param tableName
73      *            collection name
74      */
75     public void deleteTable(String tableName) {
76         db.getCollection(tableName).drop();
77     }
78
79     public MongoDatabase getMongoDatabase() {
80         return db;
81     }
82
83     /**
84      * API for storing information of authorized users
85      * 
86      * @param accountInfo
87      *            information of authorized users
88      * @param tablename
89      *            table name of mongoDB
90      */
91     public void createResource(UserSession userSession) {
92
93         Document doc = createDocument(userSession);
94         MongoCollection<Document> collection = db
95                 .getCollection(Const.SESSION_TABLE);
96
97         if (collection.findOneAndReplace(Filters.and(
98                 Filters.eq(Const.USER_ID, doc.get(Const.USER_ID)),
99                 Filters.eq(Const.SESSION_CODE, doc.get(Const.SESSION_CODE))),
100                 doc) == null) {
101
102             collection.insertOne(doc);
103         }
104
105         return;
106     }
107
108     public void createResource(UserDevice userDevice) {
109
110         Document doc = createDocument(userDevice);
111         MongoCollection<Document> collection = db
112                 .getCollection(Const.DEVICE_TABLE);
113
114         if (collection.findOneAndReplace(
115                 Filters.and(Filters.eq(Const.USER_ID, doc.get(Const.USER_ID)),
116                         Filters.eq(Const.DEVICE_ID, doc.get(Const.DEVICE_ID))),
117                 doc) == null) {
118
119             collection.insertOne(doc);
120         }
121
122         return;
123     }
124
125     private Document createDocument(UserSession userSession) {
126
127         Document doc = new Document(Const.USER_ID, userSession.getUserId())
128                 .append(Const.SESSION_CODE, userSession.getSessionCode());
129
130         return doc;
131     }
132
133     private Document createDocument(UserDevice userDevice) {
134
135         Document doc = new Document(Const.USER_ID, userDevice.getUserId())
136                 .append(Const.DEVICE_ID, userDevice.getDeviceId());
137
138         return doc;
139     }
140
141     private UserSession convertSessionDocToResource(Document doc) {
142
143         UserSession userSession = new UserSession();
144
145         userSession.setUserId(doc.getString(Const.USER_ID));
146         userSession.setSessionCode(doc.getString(Const.SESSION_CODE));
147
148         return userSession;
149     }
150
151     private UserDevice convertDeviceDocToResource(Document doc) {
152
153         UserDevice userDevice = new UserDevice();
154
155         userDevice.setUserId(doc.getString(Const.USER_ID));
156         userDevice.setDeviceId(doc.getString(Const.DEVICE_ID));
157
158         return userDevice;
159     }
160
161     public String getUserId(String sessionCode) {
162
163         String userId = null;
164
165         MongoCollection<Document> collection = db
166                 .getCollection(Const.SESSION_TABLE);
167
168         MongoCursor<Document> cursor = collection
169                 .find(Filters.eq(Const.SESSION_CODE, sessionCode)).iterator();
170
171         try {
172
173             while (cursor.hasNext()) {
174
175                 Document doc = cursor.next();
176                 UserSession userSession = convertSessionDocToResource(doc);
177
178                 userId = userSession.getUserId();
179                 break;
180             }
181
182         } finally {
183
184             cursor.close();
185         }
186
187         return userId;
188     }
189
190     /**
191      * API for getting devices according to user from mongoDB
192      * 
193      * @param userId
194      *            user identifier
195      * @param tablename
196      *            table name of mongoDB
197      */
198     public ArrayList<String> getDevices(String userId) {
199
200         ArrayList<String> deviceList = new ArrayList<String>();
201
202         MongoCollection<Document> collection = db
203                 .getCollection(Const.DEVICE_TABLE);
204
205         MongoCursor<Document> cursor = collection
206                 .find(Filters.eq(Const.USER_ID, userId)).iterator();
207
208         try {
209
210             while (cursor.hasNext()) {
211
212                 Document doc = cursor.next();
213                 UserDevice userDeivce = convertDeviceDocToResource(doc);
214
215                 deviceList.add(userDeivce.getDeviceId());
216             }
217
218         } finally {
219
220             cursor.close();
221         }
222
223         return deviceList;
224     }
225
226     private ArrayList<UserSession> readSessionResources() {
227
228         ArrayList<UserSession> userSessionList = new ArrayList<UserSession>();
229
230         MongoCollection<Document> collection = db
231                 .getCollection(Const.SESSION_TABLE);
232         MongoCursor<Document> cursor = collection.find().iterator();
233
234         while (cursor.hasNext()) {
235
236             Document doc = cursor.next();
237             userSessionList.add(convertSessionDocToResource(doc));
238         }
239
240         cursor.close();
241
242         return userSessionList;
243     }
244
245     private ArrayList<UserDevice> readDeviceResources() {
246
247         ArrayList<UserDevice> userDeviceList = new ArrayList<UserDevice>();
248
249         MongoCollection<Document> collection = db
250                 .getCollection(Const.DEVICE_TABLE);
251         MongoCursor<Document> cursor = collection.find().iterator();
252
253         while (cursor.hasNext()) {
254
255             Document doc = cursor.next();
256             userDeviceList.add(convertDeviceDocToResource(doc));
257         }
258
259         cursor.close();
260
261         return userDeviceList;
262     }
263
264     public void printResources() {
265
266         ArrayList<UserDevice> dlist = readDeviceResources();
267         int size = dlist.size();
268
269         Logger.i("*Table: " + Const.DEVICE_TABLE);
270         for (int i = 0; i < size; i++) {
271
272             UserDevice item = dlist.get(i);
273
274             Logger.i("[" + i + "]" + item.getUserId() + ", "
275                     + item.getDeviceId());
276         }
277
278         ArrayList<UserSession> slist = readSessionResources();
279         size = slist.size();
280
281         Logger.i("*Table: " + Const.SESSION_TABLE);
282
283         for (int i = 0; i < size; i++) {
284
285             UserSession item = slist.get(i);
286
287             Logger.i("[" + i + "]" + item.getUserId() + ", "
288                     + item.getSessionCode());
289
290         }
291     }
292
293 }