Imported Upstream version 1.1.0
[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.Constants;
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
55         mongoClient = new MongoClient();
56         mongoClient.dropDatabase(dbname);
57         db = mongoClient.getDatabase(dbname);
58     }
59
60     /**
61      * API creating collection
62      * 
63      * @param tableName
64      *            collection name
65      */
66     public void createTable(String tableName) {
67
68         db.createCollection(tableName);
69     }
70
71     /**
72      * API deleting collection
73      * 
74      * @param tableName
75      *            collection name
76      */
77     public void deleteTable(String tableName) {
78
79         db.getCollection(tableName).drop();
80     }
81
82     /**
83      * API getting database object
84      * 
85      */
86     public MongoDatabase getMongoDatabase() {
87
88         return db;
89     }
90
91     /**
92      * API for storing session information of user
93      * 
94      * @param UserSession
95      *            session information of user
96      */
97     public void createResource(UserSession userSession) {
98
99         Document doc = createDocument(userSession);
100         MongoCollection<Document> collection = db
101                 .getCollection(Constants.SESSION_TABLE);
102
103         if (collection.findOneAndReplace(Filters.and(
104                 Filters.eq(Constants.USER_ID, doc.get(Constants.USER_ID)),
105                 Filters.eq(Constants.SESSION_CODE, doc.get(Constants.SESSION_CODE))),
106                 doc) == null) {
107
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(Filters.and(
127                 Filters.eq(Constants.USER_ID, doc.get(Constants.USER_ID)),
128                 Filters.eq(Constants.DEVICE_ID, doc.get(Constants.DEVICE_ID))), doc) == null) {
129
130             collection.insertOne(doc);
131         }
132
133         return;
134     }
135
136     /**
137      * API for getting user identifier corresponding with session code from
138      * database
139      * 
140      * @param sessionCode
141      *            session code
142      * @return String - user identifier
143      */
144     public String getUserId(String sessionCode) {
145
146         String userId = null;
147
148         MongoCollection<Document> collection = db
149                 .getCollection(Constants.SESSION_TABLE);
150
151         MongoCursor<Document> cursor = collection.find(
152                 Filters.eq(Constants.SESSION_CODE, sessionCode)).iterator();
153
154         try {
155
156             while (cursor.hasNext()) {
157
158                 Document doc = cursor.next();
159                 UserSession userSession = convertSessionDocToResource(doc);
160
161                 userId = userSession.getUserId();
162                 break;
163             }
164
165         } finally {
166
167             cursor.close();
168         }
169
170         return userId;
171     }
172
173     /**
174      * API for getting devices corresponding with user identifier from database
175      * 
176      * @param userId
177      *            user identifier
178      */
179     public ArrayList<String> getDevices(String userId) {
180
181         ArrayList<String> deviceList = new ArrayList<String>();
182
183         MongoCollection<Document> collection = db
184                 .getCollection(Constants.DEVICE_TABLE);
185
186         MongoCursor<Document> cursor = collection.find(
187                 Filters.eq(Constants.USER_ID, userId)).iterator();
188
189         try {
190
191             while (cursor.hasNext()) {
192
193                 Document doc = cursor.next();
194                 UserDevice userDeivce = convertDeviceDocToResource(doc);
195
196                 deviceList.add(userDeivce.getDeviceId());
197             }
198
199         } finally {
200
201             cursor.close();
202         }
203
204         return deviceList;
205     }
206
207     public void printResources() {
208
209         ArrayList<UserDevice> dlist = readDeviceResources();
210         int size = dlist.size();
211
212         Logger.i("*Table: " + Constants.DEVICE_TABLE);
213         for (int i = 0; i < size; i++) {
214
215             UserDevice item = dlist.get(i);
216
217             Logger.i("[" + i + "]" + item.getUserId() + ", "
218                     + item.getDeviceId());
219         }
220
221         ArrayList<UserSession> slist = readSessionResources();
222         size = slist.size();
223
224         Logger.i("*Table: " + Constants.SESSION_TABLE);
225
226         for (int i = 0; i < size; i++) {
227
228             UserSession item = slist.get(i);
229
230             Logger.i("[" + i + "]" + item.getUserId() + ", "
231                     + item.getSessionCode());
232
233         }
234     }
235
236     private Document createDocument(UserSession userSession) {
237
238         Document doc = new Document(Constants.USER_ID, userSession.getUserId())
239                 .append(Constants.SESSION_CODE, userSession.getSessionCode());
240
241         return doc;
242     }
243
244     private Document createDocument(UserDevice userDevice) {
245
246         Document doc = new Document(Constants.USER_ID, userDevice.getUserId())
247                 .append(Constants.DEVICE_ID, userDevice.getDeviceId());
248
249         return doc;
250     }
251
252     private UserSession convertSessionDocToResource(Document doc) {
253
254         UserSession userSession = new UserSession();
255
256         userSession.setUserId(doc.getString(Constants.USER_ID));
257         userSession.setSessionCode(doc.getString(Constants.SESSION_CODE));
258
259         return userSession;
260     }
261
262     private UserDevice convertDeviceDocToResource(Document doc) {
263
264         UserDevice userDevice = new UserDevice();
265
266         userDevice.setUserId(doc.getString(Constants.USER_ID));
267         userDevice.setDeviceId(doc.getString(Constants.DEVICE_ID));
268
269         return userDevice;
270     }
271
272     private ArrayList<UserSession> readSessionResources() {
273
274         ArrayList<UserSession> userSessionList = new ArrayList<UserSession>();
275
276         MongoCollection<Document> collection = db
277                 .getCollection(Constants.SESSION_TABLE);
278         MongoCursor<Document> cursor = collection.find().iterator();
279
280         while (cursor.hasNext()) {
281
282             Document doc = cursor.next();
283             userSessionList.add(convertSessionDocToResource(doc));
284         }
285
286         cursor.close();
287
288         return userSessionList;
289     }
290
291     private ArrayList<UserDevice> readDeviceResources() {
292
293         ArrayList<UserDevice> userDeviceList = new ArrayList<UserDevice>();
294
295         MongoCollection<Document> collection = db
296                 .getCollection(Constants.DEVICE_TABLE);
297         MongoCursor<Document> cursor = collection.find().iterator();
298
299         while (cursor.hasNext()) {
300
301             Document doc = cursor.next();
302             userDeviceList.add(convertDeviceDocToResource(doc));
303         }
304
305         cursor.close();
306
307         return userDeviceList;
308     }
309
310 }