Merge branch 'master' into notification-service
[platform/upstream/iotivity.git] / cloud / account / src / main / java / org / iotivity / cloud / accountserver / db / MongoDB.java
index 149fb5e..6750b56 100644 (file)
@@ -1,31 +1,34 @@
 /*
- *******************************************************************
- *
- * Copyright 2016 Samsung Electronics All Rights Reserved.
- *
- *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ * //******************************************************************
+ * //
+ * // Copyright 2016 Samsung Electronics All Rights Reserved.
+ * //
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ * //
+ * // Licensed under the Apache License, Version 2.0 (the "License");
+ * // you may not use this file except in compliance with the License.
+ * // You may obtain a copy of the License at
+ * //
+ * //      http://www.apache.org/licenses/LICENSE-2.0
+ * //
+ * // Unless required by applicable law or agreed to in writing, software
+ * // distributed under the License is distributed on an "AS IS" BASIS,
+ * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * // See the License for the specific language governing permissions and
+ * // limitations under the License.
+ * //
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
  */
 package org.iotivity.cloud.accountserver.db;
 
+import java.text.DateFormat;
+import java.text.SimpleDateFormat;
 import java.util.ArrayList;
+import java.util.Date;
 
 import org.bson.Document;
-import org.iotivity.cloud.accountserver.Const;
-import org.iotivity.cloud.util.Logger;
+import org.iotivity.cloud.accountserver.Constants;
+import org.iotivity.cloud.util.Log;
 
 import com.mongodb.MongoClient;
 import com.mongodb.client.MongoCollection;
@@ -45,12 +48,13 @@ public class MongoDB {
 
     /**
      * API creating MongoClient and initializing MongoDatabase
-     * 
+     *
      * @param dbname
      *            database name to create MongoDatabase
      * @throws Exception
      */
     public MongoDB(String dbname) throws Exception {
+
         mongoClient = new MongoClient();
         mongoClient.dropDatabase(dbname);
         db = mongoClient.getDatabase(dbname);
@@ -58,62 +62,73 @@ public class MongoDB {
 
     /**
      * API creating collection
-     * 
+     *
      * @param tableName
      *            collection name
      */
     public void createTable(String tableName) {
+
         db.createCollection(tableName);
     }
 
     /**
      * API deleting collection
-     * 
+     *
      * @param tableName
      *            collection name
      */
     public void deleteTable(String tableName) {
+
         db.getCollection(tableName).drop();
     }
 
+    /**
+     * API getting database object
+     *
+     */
     public MongoDatabase getMongoDatabase() {
+
         return db;
     }
 
-    /**
-     * API for storing information of authorized users
-     * 
-     * @param accountInfo
-     *            information of authorized users
-     * @param tablename
-     *            table name of mongoDB
-     */
-    public void createResource(UserSession userSession) {
-
-        Document doc = createDocument(userSession);
+    public void createResource(UserToken userToken) {
+        Document doc = createDocument(userToken);
         MongoCollection<Document> collection = db
-                .getCollection(Const.SESSION_TABLE);
+                .getCollection(Constants.TOKEN_TABLE);
 
-        if (collection.findOneAndReplace(Filters.and(
-                Filters.eq(Const.USER_ID, doc.get(Const.USER_ID)),
-                Filters.eq(Const.SESSION_CODE, doc.get(Const.SESSION_CODE))),
+        if (collection.findOneAndReplace(
+                Filters.and(
+                        Filters.eq(Constants.KEY_USER_ID,
+                                doc.get(Constants.KEY_USER_ID)),
+                        Filters.eq(Constants.KEY_ACCESS_TOKEN,
+                                doc.get(Constants.KEY_ACCESS_TOKEN)),
+                        Filters.eq(Constants.KEY_REFRESH_TOKEN,
+                                doc.get(Constants.KEY_REFRESH_TOKEN))),
                 doc) == null) {
-
             collection.insertOne(doc);
         }
 
         return;
     }
 
+    /**
+     * API for inserting device information of user
+     *
+     * @param UserDevice
+     *            device information of user
+     */
     public void createResource(UserDevice userDevice) {
 
         Document doc = createDocument(userDevice);
         MongoCollection<Document> collection = db
-                .getCollection(Const.DEVICE_TABLE);
+                .getCollection(Constants.DEVICE_TABLE);
 
         if (collection.findOneAndReplace(
-                Filters.and(Filters.eq(Const.USER_ID, doc.get(Const.USER_ID)),
-                        Filters.eq(Const.DEVICE_ID, doc.get(Const.DEVICE_ID))),
+                Filters.and(
+                        Filters.eq(Constants.KEY_USER_ID,
+                                doc.get(Constants.KEY_USER_ID)),
+                        Filters.eq(Constants.KEY_DEVICE_ID,
+                                doc.get(Constants.KEY_DEVICE_ID))),
                 doc) == null) {
 
             collection.insertOne(doc);
@@ -122,60 +137,62 @@ public class MongoDB {
         return;
     }
 
-    private Document createDocument(UserSession userSession) {
-
-        Document doc = new Document(Const.USER_ID, userSession.getUserId())
-                .append(Const.SESSION_CODE, userSession.getSessionCode());
-
-        return doc;
-    }
-
-    private Document createDocument(UserDevice userDevice) {
+    /**
+     * API for getting user identifier corresponding with session code from
+     * database
+     *
+     * @param sessionCode
+     *            session code
+     * @return String - user identifier
+     */
+    public String getUserIdByAccessToken(String token) {
 
-        Document doc = new Document(Const.USER_ID, userDevice.getUserId())
-                .append(Const.DEVICE_ID, userDevice.getDeviceId());
+        String userId = null;
 
-        return doc;
-    }
+        MongoCollection<Document> collection = db
+                .getCollection(Constants.TOKEN_TABLE);
 
-    private UserSession convertSessionDocToResource(Document doc) {
+        MongoCursor<Document> cursor = collection
+                .find(Filters.eq(Constants.KEY_ACCESS_TOKEN, token)).iterator();
 
-        UserSession userSession = new UserSession();
+        try {
 
-        userSession.setUserId(doc.getString(Const.USER_ID));
-        userSession.setSessionCode(doc.getString(Const.SESSION_CODE));
+            while (cursor.hasNext()) {
 
-        return userSession;
-    }
+                Document doc = cursor.next();
+                UserToken userToken = convertTokenDocToResource(doc);
 
-    private UserDevice convertDeviceDocToResource(Document doc) {
+                userId = userToken.getUserId();
+                break;
+            }
 
-        UserDevice userDevice = new UserDevice();
+        } finally {
 
-        userDevice.setUserId(doc.getString(Const.USER_ID));
-        userDevice.setDeviceId(doc.getString(Const.DEVICE_ID));
+            cursor.close();
+        }
 
-        return userDevice;
+        return userId;
     }
 
-    public String getUserId(String sessionCode) {
+    public String getUserIdByRefreshToken(String token) {
 
         String userId = null;
 
         MongoCollection<Document> collection = db
-                .getCollection(Const.SESSION_TABLE);
+                .getCollection(Constants.TOKEN_TABLE);
 
         MongoCursor<Document> cursor = collection
-                .find(Filters.eq(Const.SESSION_CODE, sessionCode)).iterator();
+                .find(Filters.eq(Constants.KEY_REFRESH_TOKEN, token))
+                .iterator();
 
         try {
 
             while (cursor.hasNext()) {
 
                 Document doc = cursor.next();
-                UserSession userSession = convertSessionDocToResource(doc);
+                UserToken userToken = convertTokenDocToResource(doc);
 
-                userId = userSession.getUserId();
+                userId = userToken.getUserId();
                 break;
             }
 
@@ -188,22 +205,20 @@ public class MongoDB {
     }
 
     /**
-     * API for getting devices according to user from mongoDB
-     * 
+     * API for getting devices corresponding with user identifier from database
+     *
      * @param userId
      *            user identifier
-     * @param tablename
-     *            table name of mongoDB
      */
     public ArrayList<String> getDevices(String userId) {
 
-        ArrayList<String> deviceList = new ArrayList<String>();
+        ArrayList<String> deviceList = new ArrayList<>();
 
         MongoCollection<Document> collection = db
-                .getCollection(Const.DEVICE_TABLE);
+                .getCollection(Constants.DEVICE_TABLE);
 
         MongoCursor<Document> cursor = collection
-                .find(Filters.eq(Const.USER_ID, userId)).iterator();
+                .find(Filters.eq(Constants.KEY_USER_ID, userId)).iterator();
 
         try {
 
@@ -223,42 +238,100 @@ public class MongoDB {
         return deviceList;
     }
 
-    private ArrayList<UserSession> readSessionResources() {
+    public Boolean hasAccessToken(String token) {
 
-        ArrayList<UserSession> userSessionList = new ArrayList<UserSession>();
+        Boolean hasAccessToken = false;
 
         MongoCollection<Document> collection = db
-                .getCollection(Const.SESSION_TABLE);
-        MongoCursor<Document> cursor = collection.find().iterator();
+                .getCollection(Constants.TOKEN_TABLE);
 
-        while (cursor.hasNext()) {
+        MongoCursor<Document> cursor = collection
+                .find(Filters.eq(Constants.KEY_ACCESS_TOKEN, token)).iterator();
 
-            Document doc = cursor.next();
-            userSessionList.add(convertSessionDocToResource(doc));
-        }
+        if (cursor.hasNext())
+            hasAccessToken = true;
 
         cursor.close();
 
-        return userSessionList;
+        return hasAccessToken;
     }
 
-    private ArrayList<UserDevice> readDeviceResources() {
+    public Boolean hasRefreshToken(String token) {
 
-        ArrayList<UserDevice> userDeviceList = new ArrayList<UserDevice>();
+        Boolean hasRefreshToken = false;
 
         MongoCollection<Document> collection = db
-                .getCollection(Const.DEVICE_TABLE);
-        MongoCursor<Document> cursor = collection.find().iterator();
+                .getCollection(Constants.TOKEN_TABLE);
 
-        while (cursor.hasNext()) {
+        MongoCursor<Document> cursor = collection
+                .find(Filters.eq(Constants.KEY_REFRESH_TOKEN, token))
+                .iterator();
 
-            Document doc = cursor.next();
-            userDeviceList.add(convertDeviceDocToResource(doc));
-        }
+        if (cursor.hasNext())
+            hasRefreshToken = true;
 
         cursor.close();
 
-        return userDeviceList;
+        return hasRefreshToken;
+    }
+
+    public Boolean updateResource(UserToken oldUserToken,
+            UserToken newUserToken) {
+
+        Boolean updateResource = false;
+        String userId = oldUserToken.getUserId();
+        String oldRefreshToken = oldUserToken.getRefreshToken();
+
+        Document doc = createDocument(newUserToken);
+
+        MongoCollection<Document> collection = db
+                .getCollection(Constants.TOKEN_TABLE);
+
+        // update
+        if (collection.findOneAndReplace(
+                Filters.and(Filters.eq(Constants.KEY_USER_ID, userId), Filters
+                        .eq(Constants.KEY_REFRESH_TOKEN, oldRefreshToken)),
+                doc) != null) {
+
+            // collection.insertOne(doc);
+            updateResource = true;
+
+        } else {
+            Log.e("UpdateResource failed!");
+        }
+
+        return updateResource;
+    }
+
+    public String getIssuedTime(String accessToken) {
+
+        MongoCollection<Document> collection = db
+                .getCollection(Constants.TOKEN_TABLE);
+
+        MongoCursor<Document> cursor = collection
+                .find(Filters.eq(Constants.KEY_ACCESS_TOKEN, accessToken))
+                .iterator();
+
+        String issuedTime = null;
+
+        try {
+
+            while (cursor.hasNext()) {
+
+                Document doc = cursor.next();
+                UserToken userToken = convertTokenDocToResource(doc);
+
+                issuedTime = userToken.getIssuedTime();
+                break;
+            }
+
+        } finally {
+
+            cursor.close();
+        }
+
+        return issuedTime;
+
     }
 
     public void printResources() {
@@ -266,28 +339,137 @@ public class MongoDB {
         ArrayList<UserDevice> dlist = readDeviceResources();
         int size = dlist.size();
 
-        Logger.i("*Table: " + Const.DEVICE_TABLE);
+        Log.i("[" + Constants.DEVICE_TABLE + "]Table");
         for (int i = 0; i < size; i++) {
 
             UserDevice item = dlist.get(i);
 
-            Logger.i("[" + i + "]" + item.getUserId() + ", "
+            Log.i("[" + i + "]" + item.getUserId() + ", "
                     + item.getDeviceId());
         }
 
-        ArrayList<UserSession> slist = readSessionResources();
-        size = slist.size();
-
-        Logger.i("*Table: " + Const.SESSION_TABLE);
+        /*
+         * ArrayList<UserSession> slist = readSessionResources(); size =
+         * slist.size();
+         *
+         * Log.i("*Table: " + Constants.SESSION_TABLE);
+         *
+         * for (int i = 0; i < size; i++) {
+         *
+         * UserSession item = slist.get(i);
+         *
+         * Log.i("[" + i + "]" + item.getUserId() + ", " +
+         * item.getSessionCode());
+         *
+         * }
+         */
+
+        ArrayList<UserToken> tlist = readUserTokenResources();
+        size = tlist.size();
+
+        Log.i("[" + Constants.TOKEN_TABLE + "]Table");
 
         for (int i = 0; i < size; i++) {
 
-            UserSession item = slist.get(i);
+            UserToken item = tlist.get(i);
+
+            Log.i("[" + i + "]" + item.getUserId() + "/"
+                    + item.getAccessToken() + "/" + item.getRefreshToken() + "/"
+                    + item.getIssuedTime());
+
+        }
+    }
+
+    private Document createDocument(UserToken userToken) {
+
+        String userId = userToken.getUserId();
+        String accessToken = userToken.getAccessToken();
+        String refreshToken = userToken.getRefreshToken();
+
+        DateFormat f = new SimpleDateFormat("yyyyMMddkkmm");
+        Date currentDate = new Date();
+
+        String issuedTime = f.format(currentDate);
+
+        Document doc = new Document(Constants.KEY_USER_ID, userId)
+                .append(Constants.KEY_ACCESS_TOKEN, accessToken)
+                .append(Constants.KEY_REFRESH_TOKEN, refreshToken)
+                .append(Constants.KEY_ISSUED_TIME, issuedTime);
+
+        return doc;
+    }
+
+    private Document createDocument(UserDevice userDevice) {
+
+        Document doc = new Document(Constants.KEY_USER_ID,
+                userDevice.getUserId()).append(Constants.KEY_DEVICE_ID,
+                        userDevice.getDeviceId());
+
+        return doc;
+    }
+
+    private UserToken convertTokenDocToResource(Document doc) {
+
+        UserToken userToken = new UserToken();
+
+        String userId = doc.getString(Constants.KEY_USER_ID);
+        String accessToken = doc.getString(Constants.KEY_ACCESS_TOKEN);
+        String refreshToken = doc.getString(Constants.KEY_REFRESH_TOKEN);
+        String issuedTime = doc.getString(Constants.KEY_ISSUED_TIME);
 
-            Logger.i("[" + i + "]" + item.getUserId() + ", "
-                    + item.getSessionCode());
+        // Log.d("issuedTime: " + issuedTime);
+        userToken.setUserToken(userId, accessToken, refreshToken);
+        userToken.setIssuedTime(issuedTime);
 
+        return userToken;
+    }
+
+    private UserDevice convertDeviceDocToResource(Document doc) {
+
+        UserDevice userDevice = new UserDevice();
+
+        userDevice.setUserId(doc.getString(Constants.KEY_USER_ID));
+        userDevice.setDeviceId(doc.getString(Constants.KEY_DEVICE_ID));
+
+        return userDevice;
+    }
+
+    private ArrayList<UserToken> readUserTokenResources() {
+
+        ArrayList<UserToken> userTokenList = new ArrayList<>();
+
+        MongoCollection<Document> collection = db
+                .getCollection(Constants.TOKEN_TABLE);
+        MongoCursor<Document> cursor = collection.find().iterator();
+
+        while (cursor.hasNext()) {
+
+            Document doc = cursor.next();
+            userTokenList.add(convertTokenDocToResource(doc));
+        }
+
+        cursor.close();
+
+        return userTokenList;
+    }
+
+    private ArrayList<UserDevice> readDeviceResources() {
+
+        ArrayList<UserDevice> userDeviceList = new ArrayList<>();
+
+        MongoCollection<Document> collection = db
+                .getCollection(Constants.DEVICE_TABLE);
+        MongoCursor<Document> cursor = collection.find().iterator();
+
+        while (cursor.hasNext()) {
+
+            Document doc = cursor.next();
+            userDeviceList.add(convertDeviceDocToResource(doc));
         }
+
+        cursor.close();
+
+        return userDeviceList;
     }
 
 }