Merge branch 'cloud-interface'
[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.text.DateFormat;
25 import java.text.SimpleDateFormat;
26 import java.util.ArrayList;
27 import java.util.Date;
28
29 import org.bson.Document;
30 import org.iotivity.cloud.accountserver.Constants;
31 import org.iotivity.cloud.util.Logger;
32
33 import com.mongodb.MongoClient;
34 import com.mongodb.client.MongoCollection;
35 import com.mongodb.client.MongoCursor;
36 import com.mongodb.client.MongoDatabase;
37 import com.mongodb.client.model.Filters;
38
39 /**
40  *
41  * This class provides a set of APIs to use MongoDB APIs.
42  *
43  */
44 public class MongoDB {
45
46     private MongoClient   mongoClient = null;
47     private MongoDatabase db          = null;
48
49     /**
50      * API creating MongoClient and initializing MongoDatabase
51      * 
52      * @param dbname
53      *            database name to create MongoDatabase
54      * @throws Exception
55      */
56     public MongoDB(String dbname) throws Exception {
57
58         mongoClient = new MongoClient();
59         mongoClient.dropDatabase(dbname);
60         db = mongoClient.getDatabase(dbname);
61     }
62
63     /**
64      * API creating collection
65      * 
66      * @param tableName
67      *            collection name
68      */
69     public void createTable(String tableName) {
70
71         db.createCollection(tableName);
72     }
73
74     /**
75      * API deleting collection
76      * 
77      * @param tableName
78      *            collection name
79      */
80     public void deleteTable(String tableName) {
81
82         db.getCollection(tableName).drop();
83     }
84
85     /**
86      * API getting database object
87      * 
88      */
89     public MongoDatabase getMongoDatabase() {
90
91         return db;
92     }
93
94     public void createResource(UserToken userToken) {
95         Document doc = createDocument(userToken);
96         MongoCollection<Document> collection = db
97                 .getCollection(Constants.TOKEN_TABLE);
98
99         if (collection.findOneAndReplace(
100                 Filters.and(
101                         Filters.eq(Constants.KEY_USER_ID,
102                                 doc.get(Constants.KEY_USER_ID)),
103                         Filters.eq(Constants.KEY_ACCESS_TOKEN,
104                                 doc.get(Constants.KEY_ACCESS_TOKEN)),
105                         Filters.eq(Constants.KEY_REFRESH_TOKEN,
106                                 doc.get(Constants.KEY_REFRESH_TOKEN))),
107                 doc) == null) {
108             collection.insertOne(doc);
109         }
110
111         return;
112     }
113
114     /**
115      * API for inserting device information of user
116      * 
117      * @param UserDevice
118      *            device information of user
119      */
120     public void createResource(UserDevice userDevice) {
121
122         Document doc = createDocument(userDevice);
123         MongoCollection<Document> collection = db
124                 .getCollection(Constants.DEVICE_TABLE);
125
126         if (collection.findOneAndReplace(
127                 Filters.and(
128                         Filters.eq(Constants.KEY_USER_ID,
129                                 doc.get(Constants.KEY_USER_ID)),
130                         Filters.eq(Constants.KEY_DEVICE_ID,
131                                 doc.get(Constants.KEY_DEVICE_ID))),
132                 doc) == null) {
133
134             collection.insertOne(doc);
135         }
136
137         return;
138     }
139
140     /**
141      * API for getting user identifier corresponding with session code from
142      * database
143      * 
144      * @param sessionCode
145      *            session code
146      * @return String - user identifier
147      */
148     public String getUserIdByAccessToken(String token) {
149
150         String userId = null;
151
152         MongoCollection<Document> collection = db
153                 .getCollection(Constants.TOKEN_TABLE);
154
155         MongoCursor<Document> cursor = collection
156                 .find(Filters.eq(Constants.KEY_ACCESS_TOKEN, token)).iterator();
157
158         try {
159
160             while (cursor.hasNext()) {
161
162                 Document doc = cursor.next();
163                 UserToken userToken = convertTokenDocToResource(doc);
164
165                 userId = userToken.getUserId();
166                 break;
167             }
168
169         } finally {
170
171             cursor.close();
172         }
173
174         return userId;
175     }
176
177     public String getUserIdByRefreshToken(String token) {
178
179         String userId = null;
180
181         MongoCollection<Document> collection = db
182                 .getCollection(Constants.TOKEN_TABLE);
183
184         MongoCursor<Document> cursor = collection
185                 .find(Filters.eq(Constants.KEY_REFRESH_TOKEN, token))
186                 .iterator();
187
188         try {
189
190             while (cursor.hasNext()) {
191
192                 Document doc = cursor.next();
193                 UserToken userToken = convertTokenDocToResource(doc);
194
195                 userId = userToken.getUserId();
196                 break;
197             }
198
199         } finally {
200
201             cursor.close();
202         }
203
204         return userId;
205     }
206
207     /**
208      * API for getting devices corresponding with user identifier from database
209      * 
210      * @param userId
211      *            user identifier
212      */
213     public ArrayList<String> getDevices(String userId) {
214
215         ArrayList<String> deviceList = new ArrayList<>();
216
217         MongoCollection<Document> collection = db
218                 .getCollection(Constants.DEVICE_TABLE);
219
220         MongoCursor<Document> cursor = collection
221                 .find(Filters.eq(Constants.KEY_USER_ID, userId)).iterator();
222
223         try {
224
225             while (cursor.hasNext()) {
226
227                 Document doc = cursor.next();
228                 UserDevice userDeivce = convertDeviceDocToResource(doc);
229
230                 deviceList.add(userDeivce.getDeviceId());
231             }
232
233         } finally {
234
235             cursor.close();
236         }
237
238         return deviceList;
239     }
240
241     public Boolean hasAccessToken(String token) {
242
243         Boolean hasAccessToken = false;
244
245         MongoCollection<Document> collection = db
246                 .getCollection(Constants.TOKEN_TABLE);
247
248         MongoCursor<Document> cursor = collection
249                 .find(Filters.eq(Constants.KEY_ACCESS_TOKEN, token)).iterator();
250
251         if (cursor.hasNext())
252             hasAccessToken = true;
253
254         cursor.close();
255
256         return hasAccessToken;
257     }
258
259     public Boolean hasRefreshToken(String token) {
260
261         Boolean hasRefreshToken = false;
262
263         MongoCollection<Document> collection = db
264                 .getCollection(Constants.TOKEN_TABLE);
265
266         MongoCursor<Document> cursor = collection
267                 .find(Filters.eq(Constants.KEY_REFRESH_TOKEN, token))
268                 .iterator();
269
270         if (cursor.hasNext())
271             hasRefreshToken = true;
272
273         cursor.close();
274
275         return hasRefreshToken;
276     }
277
278     public Boolean updateResource(UserToken oldUserToken,
279             UserToken newUserToken) {
280
281         Boolean updateResource = false;
282         String userId = oldUserToken.getUserId();
283         String oldRefreshToken = oldUserToken.getRefreshToken();
284
285         Document doc = createDocument(newUserToken);
286
287         MongoCollection<Document> collection = db
288                 .getCollection(Constants.TOKEN_TABLE);
289
290         // update
291         if (collection.findOneAndReplace(
292                 Filters.and(Filters.eq(Constants.KEY_USER_ID, userId), Filters
293                         .eq(Constants.KEY_REFRESH_TOKEN, oldRefreshToken)),
294                 doc) != null) {
295
296             // collection.insertOne(doc);
297             updateResource = true;
298
299         } else {
300             Logger.e("UpdateResource failed!");
301         }
302
303         return updateResource;
304     }
305
306     public String getIssuedTime(String accessToken) {
307
308         MongoCollection<Document> collection = db
309                 .getCollection(Constants.TOKEN_TABLE);
310
311         MongoCursor<Document> cursor = collection
312                 .find(Filters.eq(Constants.KEY_ACCESS_TOKEN, accessToken))
313                 .iterator();
314
315         String issuedTime = null;
316
317         try {
318
319             while (cursor.hasNext()) {
320
321                 Document doc = cursor.next();
322                 UserToken userToken = convertTokenDocToResource(doc);
323
324                 issuedTime = userToken.getIssuedTime();
325                 break;
326             }
327
328         } finally {
329
330             cursor.close();
331         }
332
333         return issuedTime;
334
335     }
336
337     public void printResources() {
338
339         ArrayList<UserDevice> dlist = readDeviceResources();
340         int size = dlist.size();
341         
342         Logger.i("[" + Constants.DEVICE_TABLE + "]Table");
343         for (int i = 0; i < size; i++) {
344
345             UserDevice item = dlist.get(i);
346
347             Logger.i("[" + i + "]" + item.getUserId() + ", "
348                     + item.getDeviceId());
349         }
350
351         /*
352          * ArrayList<UserSession> slist = readSessionResources(); size =
353          * slist.size();
354          * 
355          * Logger.i("*Table: " + Constants.SESSION_TABLE);
356          * 
357          * for (int i = 0; i < size; i++) {
358          * 
359          * UserSession item = slist.get(i);
360          * 
361          * Logger.i("[" + i + "]" + item.getUserId() + ", " +
362          * item.getSessionCode());
363          * 
364          * }
365          */
366
367         ArrayList<UserToken> tlist = readUserTokenResources();
368         size = tlist.size();
369
370         Logger.i("[" + Constants.TOKEN_TABLE + "]Table");
371
372         for (int i = 0; i < size; i++) {
373
374             UserToken item = tlist.get(i);
375
376             Logger.i("[" + i + "]" + item.getUserId() + "/"
377                     + item.getAccessToken() + "/" + item.getRefreshToken() + "/"
378                     + item.getIssuedTime());
379
380         }
381     }
382
383     private Document createDocument(UserToken userToken) {
384
385         String userId = userToken.getUserId();
386         String accessToken = userToken.getAccessToken();
387         String refreshToken = userToken.getRefreshToken();
388
389         DateFormat f = new SimpleDateFormat("yyyyMMddkkmm");
390         Date currentDate = new Date();
391
392         String issuedTime = f.format(currentDate);
393
394         Document doc = new Document(Constants.KEY_USER_ID, userId)
395                 .append(Constants.KEY_ACCESS_TOKEN, accessToken)
396                 .append(Constants.KEY_REFRESH_TOKEN, refreshToken)
397                 .append(Constants.KEY_ISSUED_TIME, issuedTime);
398
399         return doc;
400     }
401
402     private Document createDocument(UserDevice userDevice) {
403
404         Document doc = new Document(Constants.KEY_USER_ID,
405                 userDevice.getUserId()).append(Constants.KEY_DEVICE_ID,
406                         userDevice.getDeviceId());
407
408         return doc;
409     }
410
411     private UserToken convertTokenDocToResource(Document doc) {
412
413         UserToken userToken = new UserToken();
414
415         String userId = doc.getString(Constants.KEY_USER_ID);
416         String accessToken = doc.getString(Constants.KEY_ACCESS_TOKEN);
417         String refreshToken = doc.getString(Constants.KEY_REFRESH_TOKEN);
418         String issuedTime = doc.getString(Constants.KEY_ISSUED_TIME);
419
420         // Logger.d("issuedTime: " + issuedTime);
421         userToken.setUserToken(userId, accessToken, refreshToken);
422         userToken.setIssuedTime(issuedTime);
423
424         return userToken;
425     }
426
427     private UserDevice convertDeviceDocToResource(Document doc) {
428
429         UserDevice userDevice = new UserDevice();
430
431         userDevice.setUserId(doc.getString(Constants.KEY_USER_ID));
432         userDevice.setDeviceId(doc.getString(Constants.KEY_DEVICE_ID));
433
434         return userDevice;
435     }
436
437     private ArrayList<UserToken> readUserTokenResources() {
438
439         ArrayList<UserToken> userTokenList = new ArrayList<>();
440
441         MongoCollection<Document> collection = db
442                 .getCollection(Constants.TOKEN_TABLE);
443         MongoCursor<Document> cursor = collection.find().iterator();
444
445         while (cursor.hasNext()) {
446
447             Document doc = cursor.next();
448             userTokenList.add(convertTokenDocToResource(doc));
449         }
450
451         cursor.close();
452
453         return userTokenList;
454     }
455
456     private ArrayList<UserDevice> readDeviceResources() {
457
458         ArrayList<UserDevice> userDeviceList = new ArrayList<>();
459
460         MongoCollection<Document> collection = db
461                 .getCollection(Constants.DEVICE_TABLE);
462         MongoCursor<Document> cursor = collection.find().iterator();
463
464         while (cursor.hasNext()) {
465
466             Document doc = cursor.next();
467             userDeviceList.add(convertDeviceDocToResource(doc));
468         }
469
470         cursor.close();
471
472         return userDeviceList;
473     }
474
475 }