import java.util.Scanner;
import org.iotivity.cloud.accountserver.resources.account.AccountResource;
-import org.iotivity.cloud.accountserver.resources.account.device.DeviceResource;
import org.iotivity.cloud.accountserver.resources.account.session.SessionResource;
import org.iotivity.cloud.accountserver.resources.account.tokenrefresh.TokenRefreshResource;
+import org.iotivity.cloud.accountserver.resources.acl.group.GroupResource;
import org.iotivity.cloud.base.ServerSystem;
import org.iotivity.cloud.base.server.CoapServer;
import org.iotivity.cloud.util.Log;
public static void main(String[] args) throws Exception {
Log.Init();
-
+
System.out.println("-----Account SERVER-----");
if (args.length != 2) {
- Log.e("coap server port and TLS mode required\n"
- + "ex) 5685 0\n");
+ Log.e("coap server port and TLS mode required\n" + "ex) 5685 0\n");
return;
}
serverSystem.addResource(new TokenRefreshResource());
- // Temporally added
- serverSystem.addResource(new DeviceResource());
+ serverSystem.addResource(new GroupResource());
serverSystem.addServer(new CoapServer(
new InetSocketAddress(Integer.parseInt(args[0]))));
+++ /dev/null
-/*
- * //******************************************************************
- * //
- * // 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;
-
-import java.util.ArrayList;
-
-import org.iotivity.cloud.accountserver.db.AccountDBManager;
-import org.iotivity.cloud.accountserver.oauth.OAuthServerFactory;
-import org.iotivity.cloud.accountserver.token.Token;
-import org.iotivity.cloud.accountserver.token.TokenManager;
-import org.iotivity.cloud.util.Log;
-
-/**
- *
- * This class provides a set of APIs to handle requests about account
- * information of authorized user.
- *
- */
-public class AccountServerManager {
-
- private OAuthServerFactory factory = null;
-
- /**
- * API for requesting user account
- *
- * @param userId
- * user identifier
- * @param deviceId
- * device identifier
- * @return Boolean - true if registered, otherwise false
- */
- public Boolean registerUserAccount(String userId, String deviceId) {
-
- Boolean ret = false;
-
- // store info to OAuthDBManager
- ret = AccountDBManager.getInstance().registerUserDevice(userId,
- deviceId);
-
- return ret;
- }
-
- /**
- * API for requesting user account and getting session code for registered
- * user.
- *
- * @param userId
- * user identifier
- * @return String - session code for registered user
- */
- public Token registerUserAccount(String userId) {
-
- // String sessionCode = null;
- // sessionCode = generateSessionCode();
-
- TokenManager tokenManager = new TokenManager();
- Token token = tokenManager.generateToken();
-
- // store info to OAuthDBManager
- AccountDBManager.getInstance().registerUserToken(userId,
- token.getAccessToken(), token.getRefreshToken());
-
- // return sessionCode;
- return token;
- }
-
- /**
- * API for requesting user identifier corresponding with authorization
- * information.
- *
- * @param authCode
- * authorization code
- * @param authServer
- * authorization server
- * @return String - user identifier
- */
- public String requestUserId(String authCode, String authServer,
- String authServerUrl, String apiServerUrl) {
-
- String userId = null;
-
- userId = getUserId(authCode, authServer, authServerUrl, apiServerUrl);
-
- return userId;
- }
-
- /**
- * API for requesting user identifier corresponding with session code.
- *
- * @param sessionCode
- * session code
- * @return String - user identifier
- */
- public String requestUserId(String accessToken) {
-
- String userId = null;
-
- // get userId from MongDB
- userId = AccountDBManager.getInstance()
- .getUserIdByAccessToken(accessToken);
-
- return userId;
- }
-
- /**
- * API for getting devices corresponding with user identifier.
- *
- * @param userId
- * user identifier
- * @return ArrayList<String> - list of devices
- */
- public ArrayList<String> requestAccountDevices(String userId) {
-
- Log.d("userId= " + userId);
-
- ArrayList<String> deviceList = AccountDBManager.getInstance()
- .getDevices(userId);
-
- return deviceList;
- }
-
- public Boolean loadAuthServer(String authServer) {
- factory = new OAuthServerFactory();
-
- return factory.create(authServer);
- }
-
- private String getUserId(String authCode, String authServer,
- String authServerUrl, String apiServerUrl) {
-
- String userId = null;
-
- String accessToken = factory.requestAccessToken(authCode,
- authServerUrl);
-
- if (accessToken == null) {
- return null;
- } else {
- userId = factory.requestGetUserInfo(accessToken, apiServerUrl);
- }
-
- return userId;
- }
-
-}
public class Constants extends OCFConstants {
- // MongoDB
+ // Database name
- public static final String DB_NAME = "ACCOUNTSERVER_DB";
+ public static final String DB_NAME = "ACCOUNTSERVER_DB";
- public static final String DEVICE_TABLE = "USER_DEVICE";
+ // Database table
- public static final String TOKEN_TABLE = "USER_TOKEN";
+ public static final String USER_TABLE = "USER_TABLE";
- public static final String KEY_USER_ID = "userId";
+ public static final String TOKEN_TABLE = "TOKEN_TABLE";
- public static final String KEY_DEVICE_ID = "deviceId";
+ public static final String GROUP_TABLE = "GROUP_TABLE";
- public static final String KEY_ACCESS_TOKEN = "accesstoken";
+ public static final String DEVICE_TABLE = "DEVICE_TABLE";
- public static final String KEY_REFRESH_TOKEN = "refreshtoken";
+ public static final String ACL_TABLE = "ACL_TABLE";
- public static final String KEY_ISSUED_TIME = "issuedTime";
+ public static final String ACLTEMPLATE_TABLE = "ACLTEMPLATE_TABLE";
- // request payload key
+ // Database table key
- public static final String REQ_USER_ID = "uid";
+ public static final String KEYFIELD_UUID = "uuid";
- public static final String REQ_DEVICE_ID = "di";
+ public static final String KEYFIELD_ACCESSTOKEN = "accesstoken";
- public static final String REQ_AUTH_CODE = "authcode";
+ public static final String KEYFIELD_GID = "gid";
- public static final String REQ_AUTH_PROVIDER = "authprovider";
+ public static final String KEYFIELD_DID = "did";
- public static final String REQ_ACCESS_TOKEN = "accesstoken";
+ public static final String KEYFIELD_ACLID = "aclid";
- public static final String REQ_LOGIN = "login";
+ public static final String KEYFIELD_GTYPE = "gtype";
- public static final String REQ_REFRESH_TOKEN = "refreshtoken";
+ public static final String KEYFIELD_GIDLIST = "gidlist";
- public static final String REQ_AUTH_OPTIONS = "options";
+ public static final String KEYFIELD_MIDLIST = "midlist";
- public static final String REQ_AUTH_SERVER_URL = "auth_server_url";
+ public static final String KEYFIELD_GACL = "gacl";
- public static final String REQ_API_SERVER_URL = "api_server_url";
+ public static final String KEYFIELD_USERID = "userid";
- // response payload key
+ public static final String KEYFIELD_PROVIDER = "provider";
- public static final String RESP_ACCESS_TOKEN = "accesstoken";
+ public static final String KEYFIELD_ISSUED_TIME = "issuedtime";
- public static final String RESP_REFRESH_TOKEN = "refreshtoken";
+ public static final String KEYFIELD_EXPIRED_TIME = "expiredtime";
- public static final String RESP_TOKEN_TYPE = "tokentype";
+ // Request payload key
- public static final String RESP_EXPIRES_IN = "expiresin";
+ public static final String REQ_DEVICE_ID = "di";
- public static final String RESP_DEVICES = "devices";
+ public static final String REQ_DEVICE_ID_LIST = "dilist";
- public static final String RESP_USER_ID = "uid";
+ public static final String REQ_UUID_ID = "uid";
- // auth servers
+ public static final String REQ_AUTH_CODE = "authcode";
+
+ public static final String REQ_AUTH_PROVIDER = "authprovider";
+
+ public static final String REQ_ACCESS_TOKEN = "accesstoken";
+
+ public static final String REQ_LOGIN = "login";
+
+ public static final String REQ_REFRESH_TOKEN = "refreshtoken";
+
+ public static final String REQ_GRANT_TYPE = "granttype";
+
+ public static final String REQ_AUTH_OPTIONS = "options";
+
+ public static final String REQ_SEARCH_CRITERIA = "search";
+
+ public static final String REQ_GROUP_ID = "gid";
+
+ public static final String REQ_GROUP_MASTER_ID = "gmid";
+
+ public static final String REQ_GROUP_TYPE = "gtype";
+
+ public static final String REQ_MEMBER = "mid";
+
+ public static final String REQ_MEMBER_LIST = "midlist";
+
+ public static final String REQ_GTYPE_PRIVATE = "Private";
+
+ public static final String REQ_GTYPE_PUBLIC = "Public";
- public static final String GITHUB = "Github";
+ // Response payload key
- public static final String SAMSUNG = "Samsung";
+ public static final String RESP_ACCESS_TOKEN = "accesstoken";
- public static final String KEY_ACCESS_TOKEN_GH = "access_token";
+ public static final String RESP_REFRESH_TOKEN = "refreshtoken";
+
+ public static final String RESP_TOKEN_TYPE = "tokentype";
+
+ public static final String RESP_EXPIRES_IN = "expiresin";
+
+ public static final String RESP_REDIRECT_URI = "redirecturi";
+
+ public static final String RESP_CERTIFICATE = "certificate";
+
+ public static final String RESP_SERVER_ID = "sid";
+
+ public static final String RESP_DEVICES = "devices";
+
+ public static final String RESP_UUID = "uid";
+
+ public static final String RESP_USER_INFO = "uinfo";
+
+ public static final String RESP_USER_LIST = "ulist";
+
+ // static token type
+
+ public static final String TOKEN_TYPE_BEARER = "bearer";
+
+ public static final int TOKEN_INFINITE = -1;
+
+ // auth servers
- // etc
+ public static final String GITHUB = "Github";
- public static final String ERROR_MESSAGE = "error_message";
+ public static final String SAMSUNG = "Samsung";
}
package org.iotivity.cloud.accountserver.db;
import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+import org.bson.Document;
import org.iotivity.cloud.accountserver.Constants;
+import org.iotivity.cloud.base.exception.ServerException.InternalServerErrorException;
/**
*
*/
public class AccountDBManager {
- private static AccountDBManager accoutDBManager = new AccountDBManager();
- private MongoDB mongoDB;
+ private static AccountDBManager accoutDBManager = new AccountDBManager();
+
+ private MongoDB mongoDB;
+
+ private HashMap<String, ArrayList<String>> keyField = new HashMap<String, ArrayList<String>>();
private AccountDBManager() {
- try {
+ createDatabase();
+ createTables();
+ createIndexes();
+ }
- mongoDB = new MongoDB(Constants.DB_NAME);
+ private void createDatabase() {
- mongoDB.createTable(Constants.DEVICE_TABLE);
- // mongoDB.createTable(Constants.SESSION_TABLE);
- mongoDB.createTable(Constants.TOKEN_TABLE);
+ try {
+ mongoDB = new MongoDB(Constants.DB_NAME);
} catch (Exception e) {
e.printStackTrace();
+ throw new InternalServerErrorException(
+ "Database or Table create failed!");
}
}
- public static AccountDBManager getInstance() {
+ private void createTables() {
- return accoutDBManager;
+ mongoDB.createTable(Constants.USER_TABLE);
+ mongoDB.createTable(Constants.TOKEN_TABLE);
+ mongoDB.createTable(Constants.GROUP_TABLE);
+ mongoDB.createTable(Constants.DEVICE_TABLE);
+ mongoDB.createTable(Constants.ACL_TABLE);
+ mongoDB.createTable(Constants.ACLTEMPLATE_TABLE);
}
- public Boolean registerUserToken(String userId, String accessToken,
- String refreshToken) {
+ private void createIndexes() {
- UserToken userToken = new UserToken();
+ ArrayList<String> keys = new ArrayList<>();
+ keys.add(Constants.KEYFIELD_UUID);
- userToken.setUserToken(userId, accessToken, refreshToken);
- mongoDB.createResource(userToken);
- mongoDB.printResources();
+ mongoDB.createIndex(Constants.USER_TABLE, keys);
+ keyField.put(Constants.USER_TABLE, keys);
- return true;
- }
+ keys = new ArrayList<>();
+ keys.add(Constants.KEYFIELD_UUID);
+ keys.add(Constants.KEYFIELD_DID);
+
+ mongoDB.createIndex(Constants.TOKEN_TABLE, keys);
+ keyField.put(Constants.TOKEN_TABLE, keys);
+
+ keys = new ArrayList<>();
+ keys.add(Constants.KEYFIELD_GID);
+
+ mongoDB.createIndex(Constants.GROUP_TABLE, keys);
+ keyField.put(Constants.GROUP_TABLE, keys);
- public Boolean updateUserToken(String userId, String oldRefreshToken,
- String newAccessToken, String newRefreshToken) {
+ keys = new ArrayList<>();
+ keys.add(Constants.KEYFIELD_UUID);
+ keys.add(Constants.KEYFIELD_DID);
- Boolean updateUserToken = false;
+ mongoDB.createIndex(Constants.DEVICE_TABLE, keys);
+ keyField.put(Constants.DEVICE_TABLE, keys);
- UserToken oldUserToken = new UserToken();
- oldUserToken.setUserToken(userId, null, oldRefreshToken);
+ keys = new ArrayList<>();
+ keys.add(Constants.KEYFIELD_ACLID);
- UserToken newUserToken = new UserToken();
- newUserToken.setUserToken(userId, newAccessToken, newRefreshToken);
+ mongoDB.createIndex(Constants.ACL_TABLE, keys);
+ keyField.put(Constants.ACL_TABLE, keys);
- updateUserToken = mongoDB.updateResource(oldUserToken, newUserToken);
- mongoDB.printResources();
+ keys = new ArrayList<>();
+ keys.add(Constants.KEYFIELD_GTYPE);
- return updateUserToken;
+ mongoDB.createIndex(Constants.ACLTEMPLATE_TABLE, keys);
+ keyField.put(Constants.ACLTEMPLATE_TABLE, keys);
+
+ }
+
+ public static AccountDBManager getInstance() {
+
+ return accoutDBManager;
}
/**
- * API for storing device information of authorized user
+ * API for inserting a record into DB table. the record will not be inserted
+ * if duplicated one.
*
- * @param userId
- * user identifier
- * @param deviceId
- * device identifier
- * @return Boolean - true if stored, otherwise false
+ * @param tableName
+ * table name to be inserted
+ * @param record
+ * record to be inserted
*/
- public Boolean registerUserDevice(String userId, String deviceId) {
+ public void insertRecord(String tableName, HashMap<String, Object> insert) {
- UserDevice userDevice = new UserDevice();
+ if (!_insertRecord(tableName, insert))
+ throw new InternalServerErrorException(
+ "Database record insert failed");
+ }
- userDevice.setUserId(userId);
- userDevice.setDeviceId(deviceId);
+ /**
+ * API for inserting a record into DB table. the record will be replaced if
+ * duplicated one.
+ *
+ * @param tableName
+ * table name to be inserted
+ * @param replace
+ * record to be inserted
+ */
+ public void insertAndReplaceRecord(String tableName,
+ HashMap<String, Object> replace) {
- mongoDB.createResource(userDevice);
- mongoDB.printResources();
+ if (!_insertAndReplaceRecord(tableName, replace))
+ throw new InternalServerErrorException(
+ "Database record insert failed");
+ }
- return true;
+ /**
+ * API for selecting records from DB table.
+ *
+ * @param tableName
+ * table name to be inserted
+ * @param condition
+ * condition record to be selected
+ * @return selected records
+ */
+ public ArrayList<HashMap<String, Object>> selectRecord(String tableName,
+ HashMap<String, Object> condition) {
+
+ return _selectRecord(tableName, condition);
}
/**
- * API for getting user identifier information corresponding with session
- * code
+ * API for deleting records from DB table.
*
- * @param userId
- * identifier of authorized user
- * @param sessionCode
- * session code
- * @return Boolean - true if stored, otherwise false
+ * @param tableName
+ * table name to be inserted
+ * @param condition
+ * condition record to be deleted
*/
- public String getUserIdByAccessToken(String token) {
+ public void deleteRecord(String tableName,
+ HashMap<String, Object> condition) {
- String userId = null;
+ if (!_deleteRecord(tableName, condition))
+ throw new InternalServerErrorException(
+ "Database record delete failed");
+ }
+
+ /**
+ * API for updating a record into DB table.
+ *
+ * @param tableName
+ * table name to be inserted
+ * @param replace
+ * record to be updated
+ */
+ public void updateRecord(String tableName,
+ HashMap<String, Object> replace) {
- userId = mongoDB.getUserIdByAccessToken(token);
+ if (!_updateRecord(tableName, replace))
+ throw new InternalServerErrorException(
+ "Database record update failed");
- return userId;
}
- public String getUserIdByRefreshToken(String token) {
+ private Boolean _insertRecord(String tableName,
+ HashMap<String, Object> record) {
+
+ Document doc = createDocument(record);
- String userId = null;
+ return mongoDB.insertRecord(tableName, doc);
+ }
+
+ private Boolean _insertAndReplaceRecord(String tableName,
+ HashMap<String, Object> record) {
- userId = mongoDB.getUserIdByRefreshToken(token);
+ Document doc = createDocument(record);
+ Document filter = getKeyFilter(tableName, record);
- return userId;
+ return mongoDB.insertAndReplaceRecord(tableName, filter, doc);
}
- /**
- * API for getting devices corresponding with user identifier
- *
- * @param userId
- * user identifier
- * @return ArrayList<String> - list of devices
- */
- public ArrayList<String> getDevices(String userId) {
+ private Boolean _deleteRecord(String tableName,
+ HashMap<String, Object> condition) {
+
+ Document doc = createDocument(condition);
- ArrayList<String> deviceList = new ArrayList<>();
+ return mongoDB.deleteRecord(tableName, doc);
+ }
+
+ private Boolean _updateRecord(String tableName,
+ HashMap<String, Object> record) {
- deviceList = mongoDB.getDevices(userId);
+ Document replace = createDocument(record);
+ Document filter = getKeyFilter(tableName, record);
- return deviceList;
+ return mongoDB.updateRecord(tableName, filter, replace);
}
- public Boolean hasAccessToken(String token) {
+ private ArrayList<HashMap<String, Object>> _selectRecord(String tableName,
+ HashMap<String, Object> record) {
- Boolean hasAccessToken = false;
- hasAccessToken = mongoDB.hasAccessToken(token);
+ Document doc = createDocument(record);
- return hasAccessToken;
+ return mongoDB.selectRecord(tableName, doc);
}
- public Boolean hasRefreshToken(String token) {
+ private Document getKeyFilter(String tableName,
+ HashMap<String, Object> record) {
+
+ Document filterDoc = new Document();
- Boolean hasRefreshToken = false;
- hasRefreshToken = mongoDB.hasRefreshToken(token);
+ ArrayList<String> keys = keyField.get(tableName);
- return hasRefreshToken;
+ for (String key : keys) {
+
+ String value = (String) record.get(key);
+ filterDoc.append(key, value);
+ }
+
+ return filterDoc;
}
- public String getIssuedTime(String accessToken) {
+ private Document createDocument(HashMap<String, Object> record) {
- String issuedTime = mongoDB.getIssuedTime(accessToken);
- return issuedTime;
+ Document doc = new Document();
+ Set<Entry<String, Object>> resEntrySet = record.entrySet();
+ Iterator<Entry<String, Object>> entryIter = resEntrySet.iterator();
+ while (entryIter.hasNext()) {
+ Map.Entry<String, Object> entry = (Map.Entry<String, Object>) entryIter
+ .next();
+ doc.append(entry.getKey().toString(), entry.getValue());
+ }
+
+ return doc;
}
+
}
--- /dev/null
+/*
+ * //******************************************************************
+ * //
+ * // 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;
+
+public class GroupTable {
+
+ private String gid;
+ private Object midlist;
+ private Object dilist;
+ private String gmid;
+ private String gacl;
+ private String gtype;
+
+ public GroupTable() {
+ }
+
+ public GroupTable(String gid, Object midlist, Object dilist, String gmid,
+ String gacl, String gtype) {
+ this.gid = gid;
+ this.midlist = midlist;
+ this.dilist = dilist;
+ this.gmid = gmid;
+ this.gacl = gacl;
+ this.gtype = gtype;
+ }
+
+ public String getGid() {
+ return gid;
+ }
+
+ public void setGid(Object gid) {
+ this.gid = gid.toString();
+ }
+
+ public Object getMidlist() {
+ return midlist;
+ }
+
+ public void setMidlist(Object midlist) {
+ this.midlist = midlist;
+ }
+
+ public Object getDilist() {
+ return dilist;
+ }
+
+ public void setDilist(Object dilist) {
+ this.dilist = dilist;
+ }
+
+ public String getGmid() {
+ return gmid;
+ }
+
+ public void setGmid(Object gmid) {
+ this.gmid = gmid.toString();
+ }
+
+ public String getGacl() {
+ return gacl;
+ }
+
+ public void setGacl(Object gacl) {
+ this.gacl = gacl.toString();
+ }
+
+ public String getGtype() {
+ return gtype;
+ }
+
+ public void setGtype(Object gtype) {
+ this.gtype = gtype.toString();
+ }
+}
\ No newline at end of file
*/
package org.iotivity.cloud.accountserver.db;
-import java.text.DateFormat;
-import java.text.SimpleDateFormat;
import java.util.ArrayList;
-import java.util.Date;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
import org.bson.Document;
-import org.iotivity.cloud.accountserver.Constants;
import org.iotivity.cloud.util.Log;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
-import com.mongodb.client.model.Filters;
+import com.mongodb.client.model.IndexOptions;
+import com.mongodb.client.result.DeleteResult;
/**
*
}
/**
- * API creating collection
+ * API for creating collection
*
* @param tableName
* collection name
}
/**
- * API deleting collection
+ * API for creating index
*
* @param tableName
* collection name
+ * @param keys
+ * key fields of collection
*/
- public void deleteTable(String tableName) {
-
- db.getCollection(tableName).drop();
- }
+ public void createIndex(String tablename, ArrayList<String> keys) {
- /**
- * API getting database object
- *
- */
- public MongoDatabase getMongoDatabase() {
+ Document doc = new Document();
- return db;
- }
+ for (String key : keys) {
- public void createResource(UserToken userToken) {
- Document doc = createDocument(userToken);
- MongoCollection<Document> collection = db
- .getCollection(Constants.TOKEN_TABLE);
-
- 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);
+ doc.append(key, 1);
}
- return;
+ IndexOptions options = new IndexOptions();
+ options.unique(true);
+
+ db.getCollection(tablename).createIndex(doc, options);
}
/**
- * API for inserting device information of user
+ * API for deleting collection
*
- * @param UserDevice
- * device information of user
+ * @param tableName
+ * collection name
*/
- public void createResource(UserDevice userDevice) {
-
- Document doc = createDocument(userDevice);
- MongoCollection<Document> collection = db
- .getCollection(Constants.DEVICE_TABLE);
-
- if (collection.findOneAndReplace(
- 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);
- }
+ public void deleteTable(String tableName) {
- return;
+ db.getCollection(tableName).drop();
}
/**
- * API for getting user identifier corresponding with session code from
- * database
+ * API for getting database object
*
- * @param sessionCode
- * session code
- * @return String - user identifier
*/
- public String getUserIdByAccessToken(String token) {
-
- String userId = null;
-
- MongoCollection<Document> collection = db
- .getCollection(Constants.TOKEN_TABLE);
-
- MongoCursor<Document> cursor = collection
- .find(Filters.eq(Constants.KEY_ACCESS_TOKEN, token)).iterator();
-
- try {
-
- while (cursor.hasNext()) {
-
- Document doc = cursor.next();
- UserToken userToken = convertTokenDocToResource(doc);
-
- userId = userToken.getUserId();
- break;
- }
-
- } finally {
-
- cursor.close();
- }
+ public MongoDatabase getMongoDatabase() {
- return userId;
+ return db;
}
- public String getUserIdByRefreshToken(String token) {
-
- String userId = null;
+ public Boolean insertRecord(String tableName, Document doc) {
- MongoCollection<Document> collection = db
- .getCollection(Constants.TOKEN_TABLE);
+ if (tableName == null || doc == null)
+ return false;
- MongoCursor<Document> cursor = collection
- .find(Filters.eq(Constants.KEY_REFRESH_TOKEN, token))
- .iterator();
+ MongoCollection<Document> collection = db.getCollection(tableName);
try {
- while (cursor.hasNext()) {
+ if (collection.find(doc).first() == null) {
+
+ collection.insertOne(doc);
- Document doc = cursor.next();
- UserToken userToken = convertTokenDocToResource(doc);
+ } else {
- userId = userToken.getUserId();
- break;
+ Log.w("DB insert failed due to duplecated one.");
+ return false;
}
- } finally {
+ } catch (Exception e) {
- cursor.close();
+ e.printStackTrace();
+ return false;
}
- return userId;
- }
+ showRecord(tableName);
- /**
- * API for getting devices corresponding with user identifier from database
- *
- * @param userId
- * user identifier
- */
- public ArrayList<String> getDevices(String userId) {
+ return true;
+ }
- ArrayList<String> deviceList = new ArrayList<>();
+ public Boolean insertAndReplaceRecord(String tableName, Document filter,
+ Document doc) {
- MongoCollection<Document> collection = db
- .getCollection(Constants.DEVICE_TABLE);
+ if (tableName == null || filter == null || doc == null)
+ return false;
- MongoCursor<Document> cursor = collection
- .find(Filters.eq(Constants.KEY_USER_ID, userId)).iterator();
+ MongoCollection<Document> collection = db.getCollection(tableName);
try {
- while (cursor.hasNext()) {
-
- Document doc = cursor.next();
- UserDevice userDeivce = convertDeviceDocToResource(doc);
+ if (collection.findOneAndReplace(filter, doc) == null) {
- deviceList.add(userDeivce.getDeviceId());
+ collection.insertOne(doc);
}
- } finally {
+ } catch (Exception e) {
- cursor.close();
+ e.printStackTrace();
+ return false;
}
- return deviceList;
- }
-
- public Boolean hasAccessToken(String token) {
-
- Boolean hasAccessToken = false;
-
- MongoCollection<Document> collection = db
- .getCollection(Constants.TOKEN_TABLE);
-
- MongoCursor<Document> cursor = collection
- .find(Filters.eq(Constants.KEY_ACCESS_TOKEN, token)).iterator();
-
- if (cursor.hasNext())
- hasAccessToken = true;
+ showRecord(tableName);
- cursor.close();
-
- return hasAccessToken;
+ return true;
}
- public Boolean hasRefreshToken(String token) {
+ public Boolean updateRecord(String tableName, Document filter,
+ Document record) {
- Boolean hasRefreshToken = false;
+ if (tableName == null || filter == null || record == null)
+ return false;
- MongoCollection<Document> collection = db
- .getCollection(Constants.TOKEN_TABLE);
+ MongoCollection<Document> collection = db.getCollection(tableName);
- MongoCursor<Document> cursor = collection
- .find(Filters.eq(Constants.KEY_REFRESH_TOKEN, token))
- .iterator();
+ if (collection.findOneAndReplace(filter, record) == null) {
- if (cursor.hasNext())
- hasRefreshToken = true;
+ Log.w("DB update failed due to no matched record!");
+ return false;
+ }
- cursor.close();
+ showRecord(tableName);
- return hasRefreshToken;
+ return true;
}
- public Boolean updateResource(UserToken oldUserToken,
- UserToken newUserToken) {
+ public Boolean deleteRecord(String tableName, Document record) {
- Boolean updateResource = false;
- String userId = oldUserToken.getUserId();
- String oldRefreshToken = oldUserToken.getRefreshToken();
+ if (tableName == null || record == null)
+ return false;
- Document doc = createDocument(newUserToken);
+ MongoCollection<Document> collection = db.getCollection(tableName);
- MongoCollection<Document> collection = db
- .getCollection(Constants.TOKEN_TABLE);
+ try {
+
+ DeleteResult result = collection.deleteMany(record);
- // update
- if (collection.findOneAndReplace(
- Filters.and(Filters.eq(Constants.KEY_USER_ID, userId), Filters
- .eq(Constants.KEY_REFRESH_TOKEN, oldRefreshToken)),
- doc) != null) {
+ if (result.getDeletedCount() == 0) {
+ Log.w("DB delete failed due to no mached record!");
+ return false;
+ }
- // collection.insertOne(doc);
- updateResource = true;
+ } catch (Exception e) {
- } else {
- Log.e("UpdateResource failed!");
+ e.printStackTrace();
+ return false;
}
- return updateResource;
+ showRecord(tableName);
+
+ return true;
}
- public String getIssuedTime(String accessToken) {
+ public ArrayList<HashMap<String, Object>> selectRecord(String tableName,
+ Document doc) {
- MongoCollection<Document> collection = db
- .getCollection(Constants.TOKEN_TABLE);
+ if (tableName == null || doc == null)
+ return null;
- MongoCursor<Document> cursor = collection
- .find(Filters.eq(Constants.KEY_ACCESS_TOKEN, accessToken))
- .iterator();
+ MongoCollection<Document> collection = db.getCollection(tableName);
+ MongoCursor<Document> cursor = collection.find(doc).iterator();
- String issuedTime = null;
+ ArrayList<HashMap<String, Object>> recordList = new ArrayList<HashMap<String, Object>>();
try {
while (cursor.hasNext()) {
-
- Document doc = cursor.next();
- UserToken userToken = convertTokenDocToResource(doc);
-
- issuedTime = userToken.getIssuedTime();
- break;
+ Document selectedDoc = cursor.next();
+ recordList.add(convertDocumentToHashMap(selectedDoc));
}
} finally {
cursor.close();
}
- return issuedTime;
-
+ return recordList;
}
- public void printResources() {
-
- ArrayList<UserDevice> dlist = readDeviceResources();
- int size = dlist.size();
-
- Log.i("[" + Constants.DEVICE_TABLE + "]Table");
- for (int i = 0; i < size; i++) {
-
- UserDevice item = dlist.get(i);
+ private HashMap<String, Object> convertDocumentToHashMap(Document doc) {
+ HashMap<String, Object> resourceMap = new HashMap<String, Object>();
- Log.i("[" + i + "]" + item.getUserId() + ", "
- + item.getDeviceId());
- }
-
- /*
- * 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());
- *
- * }
- */
+ Set<Entry<String, Object>> entrySet = doc.entrySet();
+ Iterator<Entry<String, Object>> entryIter = entrySet.iterator();
- ArrayList<UserToken> tlist = readUserTokenResources();
- size = tlist.size();
+ while (entryIter.hasNext()) {
- Log.i("[" + Constants.TOKEN_TABLE + "]Table");
+ Map.Entry<String, Object> entry = (Map.Entry<String, Object>) entryIter
+ .next();
- for (int i = 0; i < size; i++) {
+ String entryKey = entry.getKey();
- UserToken item = tlist.get(i);
-
- Log.i("[" + i + "]" + item.getUserId() + "/"
- + item.getAccessToken() + "/" + item.getRefreshToken() + "/"
- + item.getIssuedTime());
+ // remove a mongoDB index
+ if (entry.getValue() != null && !entryKey.equals("_id")) {
+ resourceMap.put(entry.getKey(), entry.getValue());
+ }
}
- }
-
- 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;
+ return resourceMap;
}
- private UserToken convertTokenDocToResource(Document doc) {
+ private void showRecord(String tableName) {
- 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);
-
- // 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);
+ MongoCollection<Document> collection = db.getCollection(tableName);
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();
+ Log.i("<" + tableName + ">");
+ HashMap<String, Object> records = null;
+ int index = 0;
while (cursor.hasNext()) {
Document doc = cursor.next();
- userDeviceList.add(convertDeviceDocToResource(doc));
+ records = convertDocumentToHashMap(doc);
+
+ Log.i("[" + index + "] " + records.toString());
+ index++;
}
cursor.close();
-
- return userDeviceList;
}
-
}
--- /dev/null
+/*
+ * //******************************************************************
+ * //
+ * // 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 org.iotivity.cloud.accountserver.Constants;
+
+/**
+ *
+ * This class provides a set of APIs storing session information of authorized
+ * user.
+ *
+ */
+
+public class TokenTable {
+
+ private String uuid = null;
+ private String did = null;
+ private String accesstoken = null;
+ private String refreshtoken = null;
+ private String provider = null;
+ private long expiredtime = Constants.TOKEN_INFINITE;
+ private String issuedtime = null;
+
+ public String getUuid() {
+ return uuid;
+ }
+
+ public void setUuid(Object uuid) {
+ this.uuid = uuid.toString();
+ }
+
+ public String getDid() {
+ return did;
+ }
+
+ public void setDid(String did) {
+ this.did = did;
+ }
+
+ public String getAccesstoken() {
+ return accesstoken;
+ }
+
+ public void setAccesstoken(Object accesstoken) {
+ if (accesstoken != null)
+ this.accesstoken = accesstoken.toString();
+ }
+
+ public String getRefreshtoken() {
+ return refreshtoken;
+ }
+
+ public void setRefreshtoken(Object refreshtoken) {
+ if (refreshtoken != null)
+ this.refreshtoken = refreshtoken.toString();
+ }
+
+ public String getProvider() {
+ return provider;
+ }
+
+ public void setProvider(Object provider) {
+ if (provider != null)
+ this.provider = provider.toString();
+ }
+
+ public long getExpiredtime() {
+ return expiredtime;
+ }
+
+ public void setExpiredtime(Object expiredtime) {
+ if (expiredtime != null)
+ this.expiredtime = Long.valueOf(expiredtime.toString());
+ }
+
+ public String getIssuedtime() {
+ return issuedtime;
+ }
+
+ public void setIssuedtime(Object issuedtime) {
+ if (issuedtime != null)
+ this.issuedtime = issuedtime.toString();
+ }
+}
\ No newline at end of file
+++ /dev/null
-/*
- * //******************************************************************
- * //
- * // 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;
-
-/**
- *
- * This class provides a set of APIs storing device information of authorized
- * user.
- *
- */
-public class UserDevice {
-
- private String userId = null;
- private String deviceId = null;
-
- public void setUserId(String id) {
- this.userId = id;
- }
-
- public void setDeviceId(String id) {
- this.deviceId = id;
- }
-
- public String getUserId() {
- return this.userId;
- }
-
- public String getDeviceId() {
- return this.deviceId;
- }
-}
\ No newline at end of file
--- /dev/null
+package org.iotivity.cloud.accountserver.db;
+
+public class UserTable {
+ private String uuid = null;
+ private String userid = null;
+ private String provider = null;
+ private String email = null;
+ private String phone = null;
+
+ public String getUuid() {
+ return uuid;
+ }
+
+ public void setUuid(Object uuid) {
+ if (uuid != null)
+ this.uuid = uuid.toString();
+ }
+
+ public String getUserid() {
+ return userid;
+ }
+
+ public void setUserid(Object userid) {
+ if (userid != null)
+ this.userid = userid.toString();
+ }
+
+ public String getProvider() {
+ return provider;
+ }
+
+ public void setProvider(Object provider) {
+ if (provider != null)
+ this.provider = provider.toString();
+ }
+
+ public String getEmail() {
+ return email;
+ }
+
+ public void setEmail(Object email) {
+ if (email != null)
+ this.email = email.toString();
+ }
+
+ public String getPhone() {
+ return phone;
+ }
+
+ public void setPhone(Object phone) {
+ if (phone != null)
+ this.phone = phone.toString();
+ }
+
+}
+++ /dev/null
-/*
- * //******************************************************************
- * //
- * // 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;
-
-/**
- *
- * This class provides a set of APIs storing session information of authorized
- * user.
- *
- */
-public class UserToken {
-
- private String userId = null;
- private String accessToken = null;
- private String refreshToken = null;
- private String issuedTime = null;
-
- public void setUserToken(String id, String accessToken,
- String refreshToken) {
- this.userId = id;
- this.accessToken = accessToken;
- this.refreshToken = refreshToken;
- }
-
- public void setUserId(String id) {
- this.userId = id;
- }
-
- public void setToken(String accessToken, String refreshToken) {
- this.accessToken = accessToken;
- this.refreshToken = refreshToken;
- }
-
- public void setIssuedTime(String time) {
- this.issuedTime = time;
- }
-
- public String getUserId() {
- return this.userId;
- }
-
- public String getAccessToken() {
- return this.accessToken;
- }
-
- public String getRefreshToken() {
- return this.refreshToken;
- }
-
- public String getIssuedTime() {
- return this.issuedTime;
- }
-}
\ No newline at end of file
package org.iotivity.cloud.accountserver.oauth;
import java.util.HashMap;
+
import org.apache.oltu.oauth2.client.OAuthClient;
import org.apache.oltu.oauth2.client.URLConnectionClient;
import org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.types.GrantType;
-import org.iotivity.cloud.accountserver.Constants;
+import org.iotivity.cloud.accountserver.db.TokenTable;
+import org.iotivity.cloud.accountserver.db.UserTable;
+import org.iotivity.cloud.base.exception.ServerException.InternalServerErrorException;
import org.iotivity.cloud.util.JSONUtil;
-import org.iotivity.cloud.util.Log;
+import org.iotivity.cloud.util.Log;;
/**
*
* provider.
*
*/
-public class Github implements OAuthServer {
+public class Github implements OAuthProvider {
// do not use 'client_id' and 'secret' variables.
// should use values that are obtained from github.
final static private String resource_url = "https://api.github.com/user";
@Override
- public HashMap<String, String> requestAccessToken(String authCode,
- String authServerUrl) {
+ public TokenTable requestAccessTokenInfo(String authCode, Object options) {
- HashMap<String, String> authServerInfo = new HashMap<String, String>();
+ TokenTable tokenInfo = new TokenTable();
try {
GitHubTokenResponse oAuthResponse = oAuthClient.accessToken(request,
GitHubTokenResponse.class);
- authServerInfo.put(Constants.KEY_ACCESS_TOKEN_GH,
- oAuthResponse.getAccessToken());
+ tokenInfo.setAccesstoken(oAuthResponse.getAccessToken());
+ tokenInfo.setRefreshtoken(oAuthResponse.getRefreshToken());
+
+ // in Github, tokens don't have to expire.
+ tokenInfo.setExpiredtime(-1);
} catch (OAuthSystemException | OAuthProblemException e) {
- authServerInfo.put(Constants.ERROR_MESSAGE, e.getMessage());
+ e.printStackTrace();
+ throw new InternalServerErrorException(
+ "OAuth provider(Github) error");
}
- return authServerInfo;
+ return tokenInfo;
}
@Override
- public HashMap<String, String> requestGetUserInfo(String accessToken,
- String apiServerUrl) {
+ public TokenTable requestRefreshTokenInfo(String refreshToken) {
+
+ TokenTable tokenInfo = new TokenTable();
- HashMap<String, String> authServerInfo = new HashMap<String, String>();
+ return tokenInfo;
+ }
+
+ @Override
+ public UserTable requestGetUserInfo(String accessToken, Object options) {
- String userInfo = null;
+ String response = null;
+ UserTable userInfo = new UserTable();
if (accessToken == null) {
Log.w("accessToken is null!");
OAuthResourceResponse resourceResponse = oAuthClient.resource(
request, OAuth.HttpMethod.GET, OAuthResourceResponse.class);
- userInfo = resourceResponse.getBody();
- Log.d("userInfo: " + userInfo);
+ response = resourceResponse.getBody();
+ Log.d("response: " + response);
} catch (OAuthSystemException | OAuthProblemException e) {
- authServerInfo.put(Constants.ERROR_MESSAGE, e.getMessage());
+ e.printStackTrace();
+ throw new InternalServerErrorException(
+ "OAuth provider(Github) error");
}
String userIdKey = "login";
- JSONUtil<HashMap<String, String>> util = new JSONUtil<HashMap<String, String>>();
- HashMap<String, String> parsedData = util.parseJSON(userInfo,
+ JSONUtil<HashMap<String, String>> util = new JSONUtil<>();
+ HashMap<String, String> parsedData = util.parseJSON(response,
HashMap.class);
String userId = parsedData.get(userIdKey);
- authServerInfo.put(Constants.KEY_USER_ID, userId);
+ userInfo.setUserid(userId);
- return authServerInfo;
+ return userInfo;
}
}
*/
package org.iotivity.cloud.accountserver.oauth;
-import java.util.HashMap;
+import org.iotivity.cloud.accountserver.db.TokenTable;
+import org.iotivity.cloud.accountserver.db.UserTable;
/**
*
* This class provides abstraction of APIs relating authorization for OAuth 2.0
*
*/
-public abstract interface OAuthServer {
+public abstract interface OAuthProvider {
/**
* API for requesting access token
* authorization server url
* @return access token and error message if error occur
*/
- public abstract HashMap<String, String> requestAccessToken(String authCode,
- String authServerUrl);
+ public abstract TokenTable requestAccessTokenInfo(String authCode,
+ Object options);
+
+ public abstract TokenTable requestRefreshTokenInfo(String refreshToken);
/**
* API for getting user's information
* api server url
* @return access token and error message if error occur
*/
- public abstract HashMap<String, String> requestGetUserInfo(
- String accessToken, String apiServerUrl);
+ public abstract UserTable requestGetUserInfo(String accessToken,
+ Object options);
}
--- /dev/null
+/*
+ * //******************************************************************
+ * //
+ * // 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.oauth;
+
+import java.io.File;
+import java.io.IOException;
+import java.lang.reflect.Method;
+import java.net.URL;
+import java.net.URLClassLoader;
+
+import org.iotivity.cloud.accountserver.db.TokenTable;
+import org.iotivity.cloud.accountserver.db.UserTable;
+import org.iotivity.cloud.base.exception.ServerException.InternalServerErrorException;
+import org.iotivity.cloud.util.Log;
+
+/**
+ *
+ * This class provides factory method for OAuth2.0 Servers.
+ *
+ */
+public class OAuthProviderFactory {
+
+ private Class<?> authProviderClass = null;
+ private Object authProviderObj = null;
+
+ public TokenTable requestAccessTokenInfo(String authCode, Object options) {
+
+ TokenTable tokenInfo = null;
+
+ try {
+ Method method = authProviderClass.getMethod(
+ "requestAccessTokenInfo",
+ new Class[] { String.class, Object.class });
+ tokenInfo = (TokenTable) method.invoke(authProviderObj, authCode,
+ options);
+
+ } catch (Exception e) {
+ e.printStackTrace();
+ throw new InternalServerErrorException(
+ "method loading error from 3rd party library");
+ }
+ return tokenInfo;
+ }
+
+ public TokenTable requestRefreshTokenInfo(String refreshToken) {
+
+ TokenTable tokenInfo = null;
+
+ try {
+ Method method = authProviderClass.getMethod(
+ "requestRefreshTokenInfo", new Class[] { String.class });
+ tokenInfo = (TokenTable) method.invoke(authProviderObj,
+ refreshToken);
+
+ } catch (Exception e) {
+ e.printStackTrace();
+ throw new InternalServerErrorException(
+ "method loading error from 3rd party library");
+ }
+ return tokenInfo;
+ }
+
+ public UserTable requestGetUserInfo(String accessToken, Object options) {
+
+ UserTable userInfo = null;
+
+ try {
+ Method method = authProviderClass.getMethod("requestGetUserInfo",
+ new Class[] { String.class, Object.class });
+ userInfo = (UserTable) method.invoke(authProviderObj, accessToken,
+ options);
+
+ } catch (Exception e) {
+ e.printStackTrace();
+ throw new InternalServerErrorException(
+ "method loading error from 3rd party library");
+ }
+ return userInfo;
+ }
+
+ /**
+ * API for creating OAuth server object
+ *
+ * @param authServer
+ * authorization server
+ * @return OAuthServer - object to handle authorization
+ * @throws Exception
+ */
+ public boolean load(String authProvider) {
+
+ String fileName = authProvider + ".jar";
+ File jarFile = new File(fileName);
+ URLClassLoader classLoader = null;
+
+ try {
+ URL urls = new URL("jar:" + jarFile.toURI() + "!/");
+
+ Log.d("urls: " + urls.toString());
+
+ classLoader = new URLClassLoader(new URL[] { urls });
+ Class<?> authProviderClass = classLoader
+ .loadClass(this.getClass().getPackage().getName() + "."
+ + authProvider);
+
+ this.authProviderClass = authProviderClass;
+ Object object = authProviderClass.newInstance();
+ this.authProviderObj = object;
+
+ } catch (Exception e) {
+ e.printStackTrace();
+ return false;
+
+ } finally {
+ try {
+ classLoader.close();
+ } catch (IOException e) {
+ e.printStackTrace();
+ throw new InternalServerErrorException(
+ "3rd party library loading error");
+ }
+ }
+
+ return true;
+ }
+}
+++ /dev/null
-/*
- * //******************************************************************
- * //
- * // 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.oauth;
-
-import java.io.File;
-import java.io.IOException;
-import java.lang.reflect.Method;
-import java.net.URL;
-import java.net.URLClassLoader;
-import java.util.HashMap;
-
-import org.iotivity.cloud.accountserver.Constants;
-import org.iotivity.cloud.util.Log;
-
-/**
- *
- * This class provides factory method for OAuth2.0 Servers.
- *
- */
-public class OAuthServerFactory {
-
- private Class<?> authServerClass = null;
- private Object authServerObj = null;
-
- @SuppressWarnings("unchecked")
- public String requestAccessToken(String authCode, String authServerUrl) {
- String accessToken = null;
- HashMap<String, String> authServerInfo = null;
-
- try {
- Method method = authServerClass.getMethod("requestAccessToken",
- new Class[] { String.class, String.class });
- authServerInfo = (HashMap<String, String>) method
- .invoke(authServerObj, authCode, authServerUrl);
- String errorMessage = authServerInfo.get(Constants.ERROR_MESSAGE);
- if (errorMessage != null) {
- Log.d("Exception Error Message from Auth Server : "
- + errorMessage);
- } else {
- accessToken = authServerInfo.get(Constants.KEY_ACCESS_TOKEN_GH);
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- return accessToken;
- }
-
- @SuppressWarnings("unchecked")
- public String requestGetUserInfo(String accessToken, String apiServerUrl) {
- String userId = null;
- HashMap<String, String> authServerInfo = null;
-
- try {
- Method method = authServerClass.getMethod("requestGetUserInfo",
- new Class[] { String.class, String.class });
- authServerInfo = (HashMap<String, String>) method
- .invoke(authServerObj, accessToken, apiServerUrl);
- String errorMessage = authServerInfo.get(Constants.ERROR_MESSAGE);
- if (errorMessage != null) {
- Log.d("Exception Error Message from Auth Server : "
- + errorMessage);
- } else {
- userId = authServerInfo.get(Constants.KEY_USER_ID);
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- return userId;
- }
-
- /**
- * API for creating OAuth server object
- *
- * @param authServer
- * authorization server
- * @return OAuthServer - object to handle authorization
- * @throws Exception
- */
- public boolean create(String authServer) {
-
- // TODO : 3rd-party provider check logic required
- String authServerName = checkAuthServerName(authServer);
- String fileName = authServerName + ".jar";
- File jarFile = new File(fileName);
- URLClassLoader classLoader = null;
-
- try {
- URL urls = new URL("jar:" + jarFile.toURI() + "!/");
-
- Log.d("urls: " + urls.toString());
-
- classLoader = new URLClassLoader(new URL[] { urls });
- Class<?> gitHubClass = classLoader
- .loadClass(this.getClass().getPackage().getName() + "."
- + authServerName);
-
- authServerClass = gitHubClass;
- Object object = gitHubClass.newInstance();
- authServerObj = object;
-
- } catch (Exception e) {
- e.printStackTrace();
- return false;
-
- } finally {
- try {
- classLoader.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
-
- return true;
- }
-
- private String checkAuthServerName(String authServer) {
-
- String authServerName = null;
-
- if (authServer.equalsIgnoreCase(Constants.GITHUB)) {
- authServerName = Constants.GITHUB;
- } else if (authServer.equalsIgnoreCase(Constants.SAMSUNG)) {
- authServerName = Constants.SAMSUNG;
- }
-
- return authServerName;
- }
-}
--- /dev/null
+/*
+ * //******************************************************************
+ * //
+ * // 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.resources.account;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.text.DateFormat;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.UUID;
+
+import org.iotivity.cloud.accountserver.Constants;
+import org.iotivity.cloud.accountserver.db.AccountDBManager;
+import org.iotivity.cloud.accountserver.db.TokenTable;
+import org.iotivity.cloud.accountserver.db.UserTable;
+import org.iotivity.cloud.accountserver.oauth.OAuthProviderFactory;
+import org.iotivity.cloud.accountserver.resources.acl.group.GroupResource;
+import org.iotivity.cloud.accountserver.util.TypeCastingManager;
+import org.iotivity.cloud.base.exception.ServerException.BadRequestException;
+import org.iotivity.cloud.base.exception.ServerException.InternalServerErrorException;
+import org.iotivity.cloud.base.exception.ServerException.NotFoundException;
+import org.iotivity.cloud.base.exception.ServerException.UnAuthorizedException;
+import org.iotivity.cloud.util.Log;
+
+/**
+ *
+ * This class provides a set of APIs to handle requests about account
+ * information of authorized user.
+ *
+ */
+public class AccountManager {
+
+ private OAuthProviderFactory mFactory = null;
+ private TypeCastingManager<UserTable> mUserTableCastingManager = new TypeCastingManager<>();
+ private TypeCastingManager<TokenTable> mTokenTableCastingManager = new TypeCastingManager<>();
+
+ public HashMap<String, Object> signUp(String did, String authCode,
+ String authProvider, Object options) {
+
+ boolean res = false;
+ authProvider = checkAuthProviderName(authProvider);
+ res = loadAuthProviderLibrary(authProvider);
+
+ if (!res) {
+ throw new InternalServerErrorException(
+ authProvider + " library is not loaded");
+ }
+ String userUuid = null;
+ // set token data
+ TokenTable tokenInfo = requestAccessToken(authCode, options);
+ tokenInfo.setDid(did);
+ tokenInfo.setProvider(authProvider);
+ Date currentTime = new Date();
+ DateFormat transFormat = new SimpleDateFormat("yyyyMMddkkmm");
+ tokenInfo.setIssuedtime(transFormat.format(currentTime));
+
+ // set user data
+ UserTable userInfo = requestUserInfo(tokenInfo.getAccesstoken(),
+ options);
+ userInfo.setProvider(authProvider);
+
+ // check uuid
+ userUuid = findUuid(userInfo.getUserid(), authProvider);
+
+ storeUserTokenInfo(userUuid, userInfo, tokenInfo);
+ // make response
+ HashMap<String, Object> response = makeSignUpResponse(tokenInfo);
+
+ return response;
+ }
+
+ private void storeUserTokenInfo(String userUuid, UserTable userInfo,
+ TokenTable tokenInfo) {
+ // store db
+ if (userUuid == null) {
+ userUuid = generateUuid();
+ userInfo.setUuid(userUuid);
+
+ AccountDBManager.getInstance().insertRecord(Constants.USER_TABLE,
+ castUserTableToMap(userInfo));
+
+ // make my private group
+ GroupResource.getInstance().createGroup(userInfo.getUuid(),
+ Constants.REQ_GTYPE_PRIVATE);
+ }
+ tokenInfo.setUuid(userUuid);
+ AccountDBManager.getInstance().insertAndReplaceRecord(
+ Constants.TOKEN_TABLE, castTokenTableToMap(tokenInfo));
+ }
+
+ private String checkAuthProviderName(String authProvider) {
+
+ String authProviderName = null;
+
+ if (authProvider.equalsIgnoreCase(Constants.GITHUB)) {
+ authProviderName = Constants.GITHUB;
+ } else if (authProvider.equalsIgnoreCase(Constants.SAMSUNG)) {
+ authProviderName = Constants.SAMSUNG;
+ }
+
+ return authProviderName;
+ }
+
+ private String findUuid(String userId, String authProvider) {
+ String uuid = null;
+
+ HashMap<String, Object> condition = new HashMap<>();
+ condition.put(Constants.KEYFIELD_USERID, userId);
+
+ ArrayList<HashMap<String, Object>> recordList = AccountDBManager
+ .getInstance().selectRecord(Constants.USER_TABLE, condition);
+
+ for (HashMap<String, Object> record : recordList) {
+ String foundProvider = record.get(Constants.KEYFIELD_PROVIDER)
+ .toString();
+ if (foundProvider != null
+ && foundProvider.equalsIgnoreCase(authProvider)) {
+ return record.get(Constants.KEYFIELD_UUID).toString();
+ }
+ }
+ return uuid;
+ }
+
+ private HashMap<String, Object> castUserTableToMap(UserTable userInfo) {
+
+ return mUserTableCastingManager.convertObjectToMap(userInfo);
+ }
+
+ private HashMap<String, Object> castTokenTableToMap(TokenTable tokenInfo) {
+
+ return mTokenTableCastingManager.convertObjectToMap(tokenInfo);
+ }
+
+ private TokenTable castMapToTokenTable(HashMap<String, Object> record) {
+ TokenTable tokenInfo = new TokenTable();
+ return mTokenTableCastingManager.convertMaptoObject(record, tokenInfo);
+ }
+
+ private HashMap<String, Object> makeSignUpResponse(TokenTable tokenInfo) {
+
+ HashMap<String, Object> response = new HashMap<>();
+
+ response.put(Constants.RESP_ACCESS_TOKEN, tokenInfo.getAccesstoken());
+ response.put(Constants.RESP_REFRESH_TOKEN, tokenInfo.getRefreshtoken());
+ response.put(Constants.RESP_TOKEN_TYPE, Constants.TOKEN_TYPE_BEARER);
+ response.put(Constants.RESP_EXPIRES_IN, tokenInfo.getExpiredtime());
+ response.put(Constants.RESP_UUID, tokenInfo.getUuid());
+
+ // It will be modified.
+ response.put(Constants.RESP_REDIRECT_URI, getRegionCIUrl());
+ response.put(Constants.RESP_CERTIFICATE, getRootCert());
+ response.put(Constants.RESP_SERVER_ID, Constants.CLOUD_UUID);
+
+ return response;
+ }
+
+ private String getRegionCIUrl() {
+
+ // TODO: add region management
+ return "coap+tcp://127.0.0.1:5683";
+ }
+
+ private byte[] getRootCert() {
+
+ byte[] byteRootCert = null;
+
+ Path path = Paths.get(Constants.ROOT_CERT_FILE);
+
+ try {
+
+ byteRootCert = Files.readAllBytes(path);
+
+ } catch (IOException e) {
+
+ e.printStackTrace();
+ throw new InternalServerErrorException(
+ "root cert file read failed!");
+ }
+
+ return byteRootCert;
+ }
+
+ private Boolean loadAuthProviderLibrary(String authProvider) {
+ mFactory = new OAuthProviderFactory();
+
+ return mFactory.load(authProvider);
+ }
+
+ private TokenTable requestAccessToken(String authCode, Object options) {
+ TokenTable tokenInfo = mFactory.requestAccessTokenInfo(authCode,
+ options);
+ Log.d("access token : " + tokenInfo.getAccesstoken());
+ Log.d("refresh token : " + tokenInfo.getRefreshtoken());
+ Log.d("expired time" + tokenInfo.getExpiredtime());
+
+ return tokenInfo;
+ }
+
+ private UserTable requestUserInfo(String accessToken, Object options) {
+ UserTable userInfo = mFactory.requestGetUserInfo(accessToken, options);
+ Log.d("user id : " + userInfo.getUserid());
+
+ return userInfo;
+ }
+
+ private String generateUuid() {
+ UUID uuid = UUID.randomUUID();
+ String userUuid = uuid.toString();
+ Log.d("generated uuid : " + userUuid);
+ return userUuid;
+ }
+
+ public HashMap<String, Object> signInOut(String uuid, String did,
+ String accessToken) {
+
+ // find record about uuid and did
+ HashMap<String, Object> condition = new HashMap<>();
+ condition.put(Constants.KEYFIELD_UUID, uuid);
+
+ ArrayList<HashMap<String, Object>> recordList = findRecord(
+ AccountDBManager.getInstance()
+ .selectRecord(Constants.TOKEN_TABLE, condition),
+ Constants.KEYFIELD_DID, did);
+
+ if (recordList.isEmpty()) {
+ throw new UnAuthorizedException("access token doesn't exist");
+ }
+
+ HashMap<String, Object> record = recordList.get(0);
+
+ TokenTable tokenInfo = castMapToTokenTable(record);
+
+ if (verifyToken(tokenInfo, accessToken)) {
+ long remainedSeconds = getRemainedSeconds(
+ tokenInfo.getExpiredtime(), tokenInfo.getIssuedtime());
+
+ return makeSignInResponse(remainedSeconds);
+ } else {
+ throw new UnAuthorizedException("AccessToken is unauthorized");
+ }
+ }
+
+ private ArrayList<HashMap<String, Object>> findRecord(
+ ArrayList<HashMap<String, Object>> recordList, String fieldName,
+ String value) {
+ ArrayList<HashMap<String, Object>> foundRecord = new ArrayList<>();
+
+ for (HashMap<String, Object> record : recordList) {
+ Object obj = record.get(fieldName);
+ if (obj != null && obj.equals(value)) {
+ foundRecord.add(record);
+ }
+ }
+ return foundRecord;
+ }
+
+ private HashMap<String, Object> makeSignInResponse(long remainedSeconds) {
+ HashMap<String, Object> response = new HashMap<>();
+ response.put(Constants.RESP_EXPIRES_IN, remainedSeconds);
+
+ return response;
+ }
+
+ private long getRemainedSeconds(long expiredTime, String issuedTime) {
+ if (expiredTime == Constants.TOKEN_INFINITE) {
+ return Constants.TOKEN_INFINITE;
+ } else {
+ return expiredTime - getElaspedSeconds(issuedTime);
+ }
+ }
+
+ private boolean verifyToken(TokenTable tokenInfo, String accessToken) {
+
+ if (checkTokenInDB(tokenInfo, accessToken)) {
+ if (tokenInfo.getExpiredtime() == Constants.TOKEN_INFINITE) {
+ return true;
+ }
+ if (checkExpiredTime(tokenInfo)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private boolean checkTokenInDB(TokenTable tokenInfo, String token) {
+
+ if (tokenInfo.getAccesstoken() == null) {
+ Log.w("token doesn't exist");
+ return false;
+ } else if (!tokenInfo.getAccesstoken().equals(token)) {
+ Log.w("token is not correct");
+ return false;
+ }
+ return true;
+ }
+
+ private boolean checkExpiredTime(TokenTable tokenInfo) {
+
+ String issuedTime = tokenInfo.getIssuedtime();
+ long expiredTime = tokenInfo.getExpiredtime();
+
+ long remainTime = getElaspedSeconds(issuedTime);
+
+ if (remainTime > expiredTime) {
+ Log.w("access token is expired");
+ return false;
+ }
+ return true;
+ }
+
+ private long getElaspedSeconds(String issuedTime) {
+
+ DateFormat format = new SimpleDateFormat("yyyyMMddkkmm");
+ Date currentTime = new Date();
+ Date issuedTimeDate = null;
+
+ try {
+ issuedTimeDate = format.parse(issuedTime);
+ } catch (ParseException e) {
+ e.printStackTrace();
+ }
+
+ long difference = currentTime.getTime() - issuedTimeDate.getTime();
+ long elaspedSeconds = difference / 1000;
+ Log.d("accessToken elasped time: " + elaspedSeconds + "s");
+
+ return elaspedSeconds;
+ }
+
+ public HashMap<String, Object> refreshToken(String uuid, String did,
+ String grantType, String refreshToken) {
+
+ // find record about uuid and did
+ HashMap<String, Object> condition = new HashMap<>();
+ condition.put(Constants.KEYFIELD_UUID, uuid);
+
+ ArrayList<HashMap<String, Object>> recordList = findRecord(
+ AccountDBManager.getInstance()
+ .selectRecord(Constants.TOKEN_TABLE, condition),
+ Constants.KEYFIELD_DID, did);
+
+ if (recordList.isEmpty()) {
+ throw new NotFoundException("refresh token doesn't exist");
+ }
+
+ HashMap<String, Object> record = recordList.get(0);
+
+ TokenTable oldTokenInfo = castMapToTokenTable(record);
+
+ if (!checkTokenInDB(oldTokenInfo, refreshToken)) {
+ throw new NotFoundException("refresh token is not correct");
+ }
+ // call 3rd party refresh token method
+ TokenTable newTokenInfo = requestRefreshToken(refreshToken);
+
+ // record change
+ oldTokenInfo.setAccesstoken(newTokenInfo.getAccesstoken());
+ oldTokenInfo.setRefreshtoken(newTokenInfo.getRefreshtoken());
+
+ // insert record
+ AccountDBManager.getInstance().insertAndReplaceRecord(
+ Constants.TOKEN_TABLE, castTokenTableToMap(oldTokenInfo));
+
+ // make response
+ HashMap<String, Object> response = makeRefreshTokenResponse(
+ oldTokenInfo);
+
+ return response;
+ }
+
+ private HashMap<String, Object> makeRefreshTokenResponse(
+ TokenTable tokenInfo) {
+ HashMap<String, Object> response = new HashMap<>();
+ response.put(Constants.RESP_ACCESS_TOKEN, tokenInfo.getAccesstoken());
+ response.put(Constants.RESP_REFRESH_TOKEN, tokenInfo.getRefreshtoken());
+ response.put(Constants.RESP_TOKEN_TYPE, Constants.TOKEN_TYPE_BEARER);
+ response.put(Constants.RESP_EXPIRES_IN, tokenInfo.getExpiredtime());
+
+ return response;
+ }
+
+ private TokenTable requestRefreshToken(String refreshToken) {
+
+ TokenTable tokenInfo = mFactory.requestRefreshTokenInfo(refreshToken);
+
+ Log.d("access token : " + tokenInfo.getAccesstoken());
+ Log.d("refresh token : " + tokenInfo.getRefreshtoken());
+ Log.d("expired time : " + tokenInfo.getExpiredtime());
+
+ return tokenInfo;
+ }
+
+ public HashMap<String, Object> searchUserAboutUuid(String uuid) {
+ // search user info about uuid
+ HashMap<String, Object> condition = new HashMap<>();
+ condition.put(Constants.KEYFIELD_UUID, uuid);
+
+ ArrayList<HashMap<String, Object>> recordList = AccountDBManager
+ .getInstance().selectRecord(Constants.USER_TABLE, condition);
+ HashMap<String, Object> response = makeSearchUserResponse(recordList);
+
+ return response;
+ }
+
+ private HashMap<String, Object> makeSearchUserResponse(
+ ArrayList<HashMap<String, Object>> recordList) {
+ HashMap<String, Object> response = new HashMap<>();
+ ArrayList<HashMap<String, Object>> ulist = new ArrayList<>();
+
+ for (HashMap<String, Object> record : recordList) {
+ HashMap<String, Object> uInfo = new HashMap<>();
+ String uid = record.get(Constants.KEYFIELD_UUID).toString();
+ uInfo.put(Constants.RESP_UUID, uid);
+ record.remove(Constants.KEYFIELD_UUID);
+ uInfo.put(Constants.RESP_USER_INFO, record);
+ ulist.add(uInfo);
+ }
+
+ response.put(Constants.RESP_USER_LIST, ulist);
+ Log.d("User List " + response.toString());
+
+ return response;
+ }
+
+ // TODO: It will be changed
+ public HashMap<String, Object> searchUserAboutCriteria(String criteria) {
+ // parse criteria
+ String[] searchType = getSearchType(criteria);
+
+ // search user info about criteria
+ HashMap<String, Object> condition = new HashMap<>();
+ condition.put(searchType[0], searchType[1]);
+
+ ArrayList<HashMap<String, Object>> recordList = AccountDBManager
+ .getInstance().selectRecord(Constants.USER_TABLE, condition);
+ HashMap<String, Object> response = makeSearchUserResponse(recordList);
+ return response;
+ }
+
+ // TODO: It will be changed
+ private String[] getSearchType(String criteria) {
+ String[] searchType = criteria.split(":");
+ String searchKey = searchType[0];
+ String searchValue = searchType[1];
+
+ if (searchKey == null || searchValue == null) {
+ throw new BadRequestException("search key or value is null");
+ }
+
+ return searchType;
+ }
+
+ public void deleteDevice(String uid, String di) {
+
+ HashSet<String> diSet = new HashSet<String>();
+ diSet.add(di);
+
+ // the group that gid is uid is my group.
+ GroupResource.getInstance().removeGroupDevice(uid, diSet);
+ }
+}
import java.util.Arrays;
import java.util.HashMap;
+import java.util.List;
-import org.iotivity.cloud.accountserver.AccountServerManager;
import org.iotivity.cloud.accountserver.Constants;
-import org.iotivity.cloud.accountserver.token.Token;
-import org.iotivity.cloud.accountserver.token.TokenPolicy;
import org.iotivity.cloud.base.device.Device;
import org.iotivity.cloud.base.exception.ServerException;
import org.iotivity.cloud.base.exception.ServerException.BadRequestException;
-import org.iotivity.cloud.base.exception.ServerException.InternalServerErrorException;
-import org.iotivity.cloud.base.exception.ServerException.PreconditionFailedException;
import org.iotivity.cloud.base.protocols.IRequest;
import org.iotivity.cloud.base.protocols.IResponse;
import org.iotivity.cloud.base.protocols.MessageBuilder;
private Cbor<HashMap<String, Object>> mCbor = new Cbor<>();
- private AccountServerManager mAsManager = new AccountServerManager();
+ private AccountManager mAsManager = new AccountManager();
public AccountResource() {
super(Arrays.asList(Constants.PREFIX_WELL_KNOWN, Constants.PREFIX_OCF,
Constants.ACCOUNT_URI));
- // addQueryHandler(Arrays.asList("if=" + Constants.INTERFACE_DEFAULT),
- // this::onDefaultInterfaceReceived);
}
@Override
switch (request.getMethod()) {
case POST:
- // Used for user sign-up
response = handlePostSignUp(request);
break;
+ case GET:
+ response = handleGetSearch(request);
+ break;
+
+ case DELETE:
+ response = handleDeleteDevice(request);
+ break;
+
default:
throw new BadRequestException(
request.getMethod() + " request type is not support");
HashMap<String, Object> payloadData = mCbor
.parsePayloadFromCbor(request.getPayload(), HashMap.class);
- exceptionPayloadCheck(payloadData);
-
- String deviceId = payloadData.get(Constants.REQ_DEVICE_ID).toString();
- String authCode = payloadData.get(Constants.REQ_AUTH_CODE).toString();
- String authProvider = payloadData.get(Constants.REQ_AUTH_PROVIDER)
- .toString();
-
- Log.d("authCode: " + authCode);
-
- @SuppressWarnings("unchecked")
- HashMap<String, String> options = (HashMap<String, String>) payloadData
- .get(Constants.REQ_AUTH_OPTIONS);
-
- String authServerUrl = null;
- String apiServerUrl = null;
-
- if (options != null) {
- authServerUrl = (String) options.get(Constants.REQ_AUTH_SERVER_URL);
- apiServerUrl = (String) options.get(Constants.REQ_API_SERVER_URL);
+ if (payloadData == null) {
+ throw new BadRequestException("CBOR parsing failed");
}
- boolean res = false;
+ HashMap<String, Object> responsePayload = null;
- res = mAsManager.loadAuthServer(authProvider);
+ if (checkPayloadException(Arrays.asList(Constants.REQ_DEVICE_ID,
+ Constants.REQ_AUTH_CODE, Constants.REQ_AUTH_PROVIDER),
+ payloadData)) {
- if (!res) {
- throw new InternalServerErrorException(
- authProvider + " library is not loaded");
- }
+ String did = payloadData.get(Constants.REQ_DEVICE_ID).toString();
+ String authCode = payloadData.get(Constants.REQ_AUTH_CODE)
+ .toString();
+ String authProvider = payloadData.get(Constants.REQ_AUTH_PROVIDER)
+ .toString();
- String userId = mAsManager.requestUserId(authCode, authProvider,
- authServerUrl, apiServerUrl);
-
- if (userId == null) {
- throw new BadRequestException("authCode is invalid");
- }
+ Log.d("authCode: " + authCode);
- Token token = new Token();
- token = mAsManager.registerUserAccount(userId);
+ Object options = payloadData.get(Constants.REQ_AUTH_OPTIONS);
- String accessToken = token.getAccessToken();
- String refreshToken = token.getRefreshToken();
-
- if (accessToken == null || refreshToken == null) {
- throw new InternalServerErrorException("MongoDB is not operating");
+ responsePayload = mAsManager.signUp(did, authCode, authProvider,
+ options);
}
- HashMap<String, Object> responsePayload = null;
-
- responsePayload = new HashMap<String, Object>();
+ return MessageBuilder.createResponse(request, ResponseStatus.CHANGED,
+ ContentFormat.APPLICATION_CBOR,
+ mCbor.encodingPayloadToCbor(responsePayload));
+ }
- responsePayload.put(Constants.RESP_ACCESS_TOKEN, accessToken);
- responsePayload.put(Constants.RESP_REFRESH_TOKEN, refreshToken);
- responsePayload.put(Constants.RESP_TOKEN_TYPE,
- TokenPolicy.BEARER_TOKEN);
- responsePayload.put(Constants.RESP_EXPIRES_IN, TokenPolicy.EXPIRES_IN);
- responsePayload.put(Constants.RESP_USER_ID, userId);
+ private IResponse handleGetSearch(IRequest request) {
+ HashMap<String, Object> responsePayload = null;
- res = mAsManager.registerUserAccount(userId, deviceId);
+ HashMap<String, List<String>> queryData = request.getUriQueryMap();
- if (!res) {
- throw new InternalServerErrorException("MongoDB is not operating");
+ if (queryData == null) {
+ throw new BadRequestException("query is null");
+ }
+ List<String> suid = queryData.get(Constants.REQ_UUID_ID);
+ List<String> criteria = queryData.get(Constants.REQ_SEARCH_CRITERIA);
+
+ if (suid != null) {
+ responsePayload = mAsManager.searchUserAboutUuid(suid.get(0));
+ } else if (criteria != null) {
+ responsePayload = mAsManager
+ .searchUserAboutCriteria(criteria.get(0));
+
+ } else {
+ throw new BadRequestException(
+ "uid and search query param are null");
}
+
return MessageBuilder.createResponse(request, ResponseStatus.CHANGED,
ContentFormat.APPLICATION_CBOR,
mCbor.encodingPayloadToCbor(responsePayload));
}
- private void exceptionPayloadCheck(HashMap<String, Object> payloadData)
- throws ServerException {
- if (payloadData == null) {
- throw new BadRequestException("payload is null");
- }
-
- // check if mandatory properties exist
- if (!payloadData.containsKey(Constants.REQ_DEVICE_ID)) {
- throw new PreconditionFailedException("di property is not include");
- }
-
- if (!payloadData.containsKey(Constants.REQ_AUTH_CODE)) {
- throw new PreconditionFailedException(
- "authcode property is not include");
- }
+ private IResponse handleDeleteDevice(IRequest request) {
- if (!payloadData.containsKey(Constants.REQ_AUTH_PROVIDER)) {
- throw new PreconditionFailedException(
- "authprovider property is not include");
- }
+ HashMap<String, List<String>> queryMap = request.getUriQueryMap();
- // check if mandatory properties have null values
- if (payloadData.get(Constants.REQ_DEVICE_ID) == null) {
- throw new PreconditionFailedException("di param is null");
- }
+ if (checkQueryException(
+ Arrays.asList(Constants.REQ_UUID_ID, Constants.REQ_DEVICE_ID),
+ queryMap)) {
- if (payloadData.get(Constants.REQ_AUTH_CODE) == null) {
- throw new PreconditionFailedException("authcode param is null");
+ String uid = queryMap.get(Constants.REQ_UUID_ID).get(0);
+ String did = queryMap.get(Constants.REQ_DEVICE_ID).get(0);
+ mAsManager.deleteDevice(uid, did);
}
- if (payloadData.get(Constants.REQ_AUTH_PROVIDER) == null) {
- throw new PreconditionFailedException("authprovider param is null");
- }
+ return MessageBuilder.createResponse(request, ResponseStatus.DELETED);
}
}
+++ /dev/null
-/*
- * //******************************************************************
- * //
- * // 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.resources.account.device;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-
-import org.iotivity.cloud.accountserver.AccountServerManager;
-import org.iotivity.cloud.accountserver.Constants;
-import org.iotivity.cloud.accountserver.token.TokenManager;
-import org.iotivity.cloud.base.device.Device;
-import org.iotivity.cloud.base.exception.ServerException;
-import org.iotivity.cloud.base.exception.ServerException.BadRequestException;
-import org.iotivity.cloud.base.exception.ServerException.UnAuthorizedException;
-import org.iotivity.cloud.base.protocols.IRequest;
-import org.iotivity.cloud.base.protocols.IResponse;
-import org.iotivity.cloud.base.protocols.MessageBuilder;
-import org.iotivity.cloud.base.protocols.enums.ContentFormat;
-import org.iotivity.cloud.base.protocols.enums.ResponseStatus;
-import org.iotivity.cloud.base.resource.Resource;
-import org.iotivity.cloud.util.Cbor;
-
-public class DeviceResource extends Resource {
-
- private Cbor<HashMap<String, Object>> mCbor = new Cbor<>();
-
- TokenManager mTokenManager = new TokenManager();
-
- private AccountServerManager mAsManager = new AccountServerManager();
-
- public DeviceResource() {
- super(Arrays.asList(Constants.PREFIX_WELL_KNOWN, Constants.PREFIX_OCF,
- Constants.ACCOUNT_URI, Constants.DEVICE_URI));
- }
-
- @Override
- public void onDefaultRequestReceived(Device srcDevice, IRequest request)
- throws ServerException {
-
- IResponse response = null;
-
- switch (request.getMethod()) {
- case GET:
- // Used for getting devices.
- response = handleGetDevice(request);
- break;
-
- default:
- throw new BadRequestException(
- request.getMethod() + " request type is not support");
- }
- srcDevice.sendResponse(response);
- }
-
- private IResponse handleGetDevice(IRequest request) throws ServerException {
-
- String accessToken = request.getUriQueryMap().get("accesstoken").get(0);
-
- if (accessToken == null) {
- throw new BadRequestException("AccessToken is empty");
- }
-
- Boolean res = false;
-
- res = mTokenManager.verifyAccessToken(accessToken);
-
- if (!res) {
- throw new UnAuthorizedException("AccessToken is unauthorized");
- }
-
- String userId = mAsManager.requestUserId(accessToken);
-
- if (userId == null) {
- throw new BadRequestException("userid is invalid");
- }
-
- ArrayList<String> deviceList = mAsManager.requestAccountDevices(userId);
-
- if (request.getUriQueryMap().get("di") != null) {
- if (deviceList.containsAll(request.getUriQueryMap().get("di"))) {
- return MessageBuilder.createResponse(request,
- ResponseStatus.VALID);
- } else {
- throw new UnAuthorizedException("di is invalid");
- }
- } else {
- HashMap<String, Object> responsePayload = new HashMap<String, Object>();
- responsePayload.put(Constants.RESP_DEVICES, deviceList);
-
- return MessageBuilder.createResponse(request,
- ResponseStatus.CONTENT, ContentFormat.APPLICATION_CBOR,
- mCbor.encodingPayloadToCbor(responsePayload));
- }
- }
-}
import java.util.HashMap;
import org.iotivity.cloud.accountserver.Constants;
-import org.iotivity.cloud.accountserver.token.TokenManager;
+import org.iotivity.cloud.accountserver.resources.account.AccountManager;
import org.iotivity.cloud.base.device.Device;
import org.iotivity.cloud.base.exception.ServerException;
import org.iotivity.cloud.base.exception.ServerException.BadRequestException;
-import org.iotivity.cloud.base.exception.ServerException.PreconditionFailedException;
-import org.iotivity.cloud.base.exception.ServerException.UnAuthorizedException;
import org.iotivity.cloud.base.protocols.IRequest;
import org.iotivity.cloud.base.protocols.IResponse;
import org.iotivity.cloud.base.protocols.MessageBuilder;
public class SessionResource extends Resource {
- private Cbor<HashMap<String, Object>> mCbor = new Cbor<>();
+ private Cbor<HashMap<String, Object>> mCbor = new Cbor<>();
- TokenManager mTokenManager = new TokenManager();
+ private AccountManager mAsManager = new AccountManager();
public SessionResource() {
super(Arrays.asList(Constants.PREFIX_WELL_KNOWN, Constants.PREFIX_OCF,
Constants.ACCOUNT_URI, Constants.SESSION_URI));
-
- // addQueryHandler(Arrays.asList("if=" + Constants.INTERFACE_DEFAULT),
- // this::onDefaultInterfaceReceived);
}
@Override
.parsePayloadFromCbor(request.getPayload(), HashMap.class);
if (payloadData == null) {
- throw new BadRequestException("payload is null");
- }
-
- if (payloadData.get(Constants.REQ_USER_ID) == null) {
- throw new PreconditionFailedException("UserId missing");
- }
-
- if (payloadData.get(Constants.REQ_DEVICE_ID) == null) {
- throw new PreconditionFailedException("DeviceId missing");
- }
-
- String accessToken = payloadData.get(Constants.REQ_ACCESS_TOKEN)
- .toString();
- boolean signinRequest = (boolean) payloadData.get(Constants.REQ_LOGIN);
-
- Boolean res = false;
-
- res = mTokenManager.verifyAccessToken(accessToken);
-
- if (!res) {
- throw new UnAuthorizedException("AccessToken is unauthorized");
- }
-
- if (!signinRequest) {
- return MessageBuilder.createResponse(request, ResponseStatus.VALID);
+ throw new BadRequestException("CBOR parsing failed");
}
HashMap<String, Object> responsePayload = null;
- responsePayload = new HashMap<String, Object>();
-
- responsePayload.put(Constants.RESP_EXPIRES_IN,
- mTokenManager.getRemainExpiredTime(accessToken));
+ if (checkPayloadException(
+ Arrays.asList(Constants.REQ_UUID_ID, Constants.REQ_DEVICE_ID,
+ Constants.REQ_ACCESS_TOKEN, Constants.REQ_LOGIN),
+ payloadData)) {
+
+ String uuid = payloadData.get(Constants.REQ_UUID_ID).toString();
+ String deviceId = payloadData.get(Constants.REQ_DEVICE_ID)
+ .toString();
+ String accessToken = payloadData.get(Constants.REQ_ACCESS_TOKEN)
+ .toString();
+ boolean signinRequest = (boolean) payloadData
+ .get(Constants.REQ_LOGIN);
+
+ if (signinRequest) {
+ responsePayload = mAsManager.signInOut(uuid, deviceId,
+ accessToken);
+ } else {
+ mAsManager.signInOut(uuid, deviceId, accessToken);
+ return MessageBuilder.createResponse(request,
+ ResponseStatus.CHANGED);
+ }
+ }
return MessageBuilder.createResponse(request, ResponseStatus.CHANGED,
ContentFormat.APPLICATION_CBOR,
import java.util.HashMap;
import org.iotivity.cloud.accountserver.Constants;
-import org.iotivity.cloud.accountserver.token.Token;
-import org.iotivity.cloud.accountserver.token.TokenManager;
-import org.iotivity.cloud.accountserver.token.TokenPolicy;
+import org.iotivity.cloud.accountserver.resources.account.AccountManager;
import org.iotivity.cloud.base.device.Device;
import org.iotivity.cloud.base.exception.ServerException;
import org.iotivity.cloud.base.exception.ServerException.BadRequestException;
-import org.iotivity.cloud.base.exception.ServerException.InternalServerErrorException;
-import org.iotivity.cloud.base.exception.ServerException.PreconditionFailedException;
-import org.iotivity.cloud.base.exception.ServerException.UnAuthorizedException;
import org.iotivity.cloud.base.protocols.IRequest;
import org.iotivity.cloud.base.protocols.IResponse;
import org.iotivity.cloud.base.protocols.MessageBuilder;
import org.iotivity.cloud.base.protocols.enums.ResponseStatus;
import org.iotivity.cloud.base.resource.Resource;
import org.iotivity.cloud.util.Cbor;
+import org.iotivity.cloud.util.Log;
public class TokenRefreshResource extends Resource {
- private Cbor<HashMap<String, Object>> mCbor = new Cbor<>();
+ private Cbor<HashMap<String, Object>> mCbor = new Cbor<>();
- TokenManager mTokenManager = new TokenManager();
+ private AccountManager mAsManager = new AccountManager();
public TokenRefreshResource() {
super(Arrays.asList(Constants.PREFIX_WELL_KNOWN, Constants.PREFIX_OCF,
Constants.ACCOUNT_URI, Constants.TOKEN_REFRESH_URI));
-
- // addQueryHandler(Arrays.asList("if=" + Constants.INTERFACE_DEFAULT),
- // this::onDefaultInterfaceReceived);
}
@Override
switch (request.getMethod()) {
case POST:
- // Used for token refresh
response = handlePostRefreshToken(request);
break;
private IResponse handlePostRefreshToken(IRequest request)
throws ServerException {
- HashMap<String, Object> payloadData = mCbor
- .parsePayloadFromCbor(request.getPayload(), HashMap.class);
-
- if (payloadData == null) {
+ if (request.getPayload() == null) {
throw new BadRequestException("payload is null");
}
- if (payloadData.get(Constants.REQ_USER_ID) == null) {
- throw new PreconditionFailedException("UserId missing");
- }
-
- if (payloadData.get(Constants.REQ_DEVICE_ID) == null) {
- throw new PreconditionFailedException("DeviceId missing");
- }
-
- String refreshToken = payloadData.get(Constants.REQ_REFRESH_TOKEN)
- .toString();
-
- Boolean res = false;
-
- res = mTokenManager.verifyRefreshToken(refreshToken);
-
- if (!res) {
- throw new UnAuthorizedException("RefreshToken is unauthorized");
- }
+ HashMap<String, Object> payloadData = mCbor
+ .parsePayloadFromCbor(request.getPayload(), HashMap.class);
- Token refreshedToken = mTokenManager.refreshToken(refreshToken);
+ // temp code
+ Log.v(payloadData.toString());
- if (refreshedToken.getAccessToken() == null
- || refreshedToken.getRefreshToken() == null) {
- throw new InternalServerErrorException("MongoDB is not operating");
+ if (payloadData == null) {
+ throw new BadRequestException("CBOR parsing failed");
}
HashMap<String, Object> responsePayload = null;
- responsePayload = new HashMap<String, Object>();
-
- responsePayload.put(Constants.RESP_ACCESS_TOKEN,
- refreshedToken.getAccessToken());
- responsePayload.put(Constants.RESP_REFRESH_TOKEN,
- refreshedToken.getRefreshToken());
- responsePayload.put(Constants.RESP_TOKEN_TYPE,
- TokenPolicy.BEARER_TOKEN);
- responsePayload.put(Constants.RESP_EXPIRES_IN, TokenPolicy.EXPIRES_IN);
+ if (checkPayloadException(
+ Arrays.asList(Constants.REQ_UUID_ID, Constants.REQ_DEVICE_ID,
+ Constants.REQ_REFRESH_TOKEN, Constants.REQ_GRANT_TYPE),
+ payloadData)) {
+
+ String uuid = payloadData.get(Constants.REQ_UUID_ID).toString();
+ String deviceId = payloadData.get(Constants.REQ_DEVICE_ID)
+ .toString();
+ String refreshToken = payloadData.get(Constants.REQ_REFRESH_TOKEN)
+ .toString();
+ String grantType = payloadData.get(Constants.REQ_GRANT_TYPE)
+ .toString();
+
+ responsePayload = mAsManager.refreshToken(uuid, deviceId, grantType,
+ refreshToken);
+ }
return MessageBuilder.createResponse(request, ResponseStatus.CHANGED,
ContentFormat.APPLICATION_CBOR,
--- /dev/null
+/*
+ * //******************************************************************
+ * //
+ * // 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.resources.acl.group;
+
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+
+import org.iotivity.cloud.accountserver.Constants;
+import org.iotivity.cloud.accountserver.db.AccountDBManager;
+import org.iotivity.cloud.accountserver.db.GroupTable;
+import org.iotivity.cloud.accountserver.util.TypeCastingManager;
+import org.iotivity.cloud.base.device.Device;
+import org.iotivity.cloud.base.exception.ServerException.UnAuthorizedException;
+import org.iotivity.cloud.base.protocols.IRequest;
+import org.iotivity.cloud.base.protocols.MessageBuilder;
+import org.iotivity.cloud.base.protocols.enums.ContentFormat;
+import org.iotivity.cloud.base.protocols.enums.ResponseStatus;
+import org.iotivity.cloud.util.Cbor;
+
+public class Group {
+
+ private Cbor<HashMap<String, Object>> mCbor = new Cbor<>();
+ private String mGid = null;
+ private TypeCastingManager<GroupTable> mTypeGroup = new TypeCastingManager<>();
+
+ public Group(String gid) {
+ mGid = gid;
+ }
+
+ private class GroupSubscriber {
+ GroupSubscriber(Device subscriber, IRequest request) {
+ mSubscriber = subscriber;
+ mRequest = request;
+ }
+
+ public Device mSubscriber;
+ public IRequest mRequest;
+ }
+
+ private HashMap<String, GroupSubscriber> mSubscribers = new HashMap<>();
+
+ public void addMember(HashSet<String> uuid) {
+
+ GroupTable groupTable = getGroupTable();
+
+ groupTable.setMidlist(groupTable.getMidlist() == null ? uuid
+ : addGroupListSet(groupTable.getMidlist(), uuid));
+
+ AccountDBManager.getInstance().updateRecord(Constants.GROUP_TABLE,
+ mTypeGroup.convertObjectToMap(groupTable));
+
+ notifyToSubscriber(getResponsePayload(true));
+ }
+
+ public void addDevice(HashSet<String> di) {
+
+ GroupTable groupTable = getGroupTable();
+
+ groupTable.setDilist(groupTable.getDilist() == null ? di
+ : addGroupListSet(groupTable.getDilist(), di));
+
+ AccountDBManager.getInstance().updateRecord(Constants.GROUP_TABLE,
+ mTypeGroup.convertObjectToMap(groupTable));
+
+ notifyToSubscriber(getResponsePayload(true));
+ }
+
+ public void removeMember(HashSet<String> uuid) {
+
+ GroupTable groupTable = getGroupTable();
+
+ if (uuid.contains(groupTable.getGmid())) {
+ GroupResource.getInstance().deleteGroup(groupTable.getGmid(), mGid);
+ notifyToSubscriber(getResponsePayload(false));
+ } else {
+ groupTable.setMidlist(
+ removeGroupListSet(groupTable.getMidlist(), uuid));
+ AccountDBManager.getInstance().updateRecord(Constants.GROUP_TABLE,
+ mTypeGroup.convertObjectToMap(groupTable));
+ notifyToSubscriber(getResponsePayload(true));
+
+ Iterator<String> mid = uuid.iterator();
+ while (mid.hasNext()) {
+ removeSubscriber(mid.next());
+ }
+
+ }
+
+ }
+
+ public void removeDevice(HashSet<String> di) {
+
+ GroupTable groupTable = getGroupTable();
+
+ groupTable.setDilist(removeGroupListSet(groupTable.getDilist(), di));
+
+ AccountDBManager.getInstance().updateRecord(Constants.GROUP_TABLE,
+ mTypeGroup.convertObjectToMap(groupTable));
+
+ notifyToSubscriber(getResponsePayload(true));
+ }
+
+ public HashMap<String, Object> getInfo(String mid) {
+
+ GroupTable groupTable = getGroupTable();
+
+ HashSet<String> midListSet = new HashSet<String>(
+ (Collection<? extends String>) groupTable.getMidlist());
+
+ if (!midListSet.contains(mid)) {
+
+ throw new UnAuthorizedException(
+ mid + " is not Group member in gid=" + mGid);
+ }
+
+ return getResponsePayload(true);
+ }
+
+ public HashMap<String, Object> addSubscriber(String mid, Device subscriber,
+ IRequest request) {
+
+ GroupTable groupTable = getGroupTable();
+
+ HashSet<String> midListSet = new HashSet<String>(
+ (Collection<? extends String>) groupTable.getMidlist());
+
+ if (!midListSet.contains(mid)) {
+
+ throw new UnAuthorizedException(
+ mid + " is not Group member in gid=" + mGid);
+ }
+
+ GroupSubscriber newSubscriber = new GroupSubscriber(subscriber,
+ request);
+
+ mSubscribers.put(mid, newSubscriber);
+
+ return getInfo(
+ request.getUriQueryMap().get(Constants.REQ_MEMBER).get(0));
+ }
+
+ public HashMap<String, Object> removeSubscriber(String mid) {
+
+ HashMap<String, Object> responsePayload = null;
+ if (mSubscribers.containsKey(mid)) {
+ mSubscribers.remove(mid);
+ }
+
+ return responsePayload;
+ }
+
+ private void notifyToSubscriber(
+ HashMap<String, Object> notifiyBtyePayloadData) {
+ synchronized (mSubscribers) {
+
+ Iterator<String> iterator = mSubscribers.keySet().iterator();
+
+ while (iterator.hasNext()) {
+
+ String key = iterator.next();
+
+ GroupSubscriber groupSubscriber = mSubscribers.get(key);
+
+ groupSubscriber.mSubscriber.sendResponse(
+ MessageBuilder.createResponse(groupSubscriber.mRequest,
+ ResponseStatus.CONTENT,
+ ContentFormat.APPLICATION_CBOR,
+ mCbor.encodingPayloadToCbor(
+ notifiyBtyePayloadData)));
+ }
+ }
+ }
+
+ private GroupTable getGroupTable() {
+
+ GroupTable getGroupTable = new GroupTable();
+
+ getGroupTable = mTypeGroup
+ .convertMaptoObject(
+ AccountDBManager.getInstance().selectRecord(
+ Constants.GROUP_TABLE, getContdition()).get(0),
+ getGroupTable);
+
+ return getGroupTable;
+ }
+
+ private HashMap<String, Object> getResponsePayload(boolean isAliveGroup) {
+
+ GroupTable groupTable = isAliveGroup ? getGroupTable() : null;
+
+ HashMap<String, Object> responsePayload = new HashMap<>();
+
+ responsePayload.put(Constants.REQ_GROUP_ID,
+ isAliveGroup ? groupTable.getGid() : null);
+ responsePayload.put(Constants.REQ_GROUP_MASTER_ID,
+ isAliveGroup ? groupTable.getGmid() : null);
+ responsePayload.put(Constants.REQ_MEMBER_LIST,
+ isAliveGroup ? groupTable.getMidlist() : null);
+ responsePayload.put(Constants.REQ_DEVICE_ID_LIST,
+ isAliveGroup ? groupTable.getDilist() : null);
+ responsePayload.put(Constants.REQ_GROUP_TYPE,
+ isAliveGroup ? groupTable.getGtype() : null);
+
+ return responsePayload;
+ }
+
+ private HashSet<String> addGroupListSet(Object object,
+ HashSet<String> addList) {
+
+ HashSet<String> groupSet = new HashSet<String>(
+ (Collection<? extends String>) object);
+
+ groupSet.addAll(addList);
+
+ return groupSet;
+ }
+
+ private HashSet<String> removeGroupListSet(Object object,
+ HashSet<String> removeList) {
+
+ HashSet<String> groupSet = new HashSet<String>(
+ (Collection<? extends String>) object);
+
+ groupSet.removeAll(removeList);
+
+ return groupSet;
+ }
+
+ private HashMap<String, Object> getContdition() {
+
+ HashMap<String, Object> condition = new HashMap<>();
+ condition.put(Constants.REQ_GROUP_ID, mGid);
+ return condition;
+ }
+
+}
--- /dev/null
+/*
+ * //******************************************************************
+ * //
+ * // 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.resources.acl.group;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.UUID;
+
+import org.iotivity.cloud.accountserver.Constants;
+import org.iotivity.cloud.accountserver.db.AccountDBManager;
+import org.iotivity.cloud.accountserver.db.GroupTable;
+import org.iotivity.cloud.accountserver.util.TypeCastingManager;
+import org.iotivity.cloud.base.device.Device;
+import org.iotivity.cloud.base.exception.ServerException.BadRequestException;
+import org.iotivity.cloud.base.protocols.IRequest;
+
+public class GroupManager {
+ public HashMap<String, Group> mGroups = new HashMap<>();
+ private TypeCastingManager<GroupTable> mTypeGroup = new TypeCastingManager<GroupTable>();
+
+ public HashMap<String, Object> createGroup(String uuid, String gtype) {
+
+ HashMap<String, Object> responsePayload = new HashMap<>();
+ String gid = null;
+
+ switch (gtype) {
+ case Constants.REQ_GTYPE_PRIVATE:
+ gid = uuid;
+ break;
+ case Constants.REQ_GTYPE_PUBLIC:
+ gid = UUID.randomUUID().toString();
+ break;
+ default:
+ throw new BadRequestException(
+ gtype + " group type is not support");
+ }
+
+ GroupTable newGroupTable = new GroupTable(gid,
+ new HashSet<String>(Arrays.asList(uuid)), null, uuid, null,
+ gtype);
+
+ AccountDBManager.getInstance().insertRecord(Constants.GROUP_TABLE,
+ mTypeGroup.convertObjectToMap(newGroupTable));
+
+ mGroups.put(gid, new Group(gid));
+
+ responsePayload.put(Constants.REQ_GROUP_ID, gid);
+
+ return responsePayload;
+ }
+
+ public void deleteGroup(String gmid, String gid) {
+
+ HashMap<String, Object> condition = new HashMap<>();
+ condition.put(Constants.REQ_GROUP_ID, gid);
+ ArrayList<HashMap<String, Object>> result = AccountDBManager
+ .getInstance().selectRecord(Constants.GROUP_TABLE, condition);
+
+ if (!gmid.equals(result.get(0).get(Constants.REQ_GROUP_MASTER_ID))) {
+
+ throw new BadRequestException(
+ gmid + " is not owner for " + gid + "group");
+ }
+ AccountDBManager.getInstance().deleteRecord(Constants.GROUP_TABLE,
+ condition);
+
+ mGroups.remove(gid);
+ }
+
+ public HashMap<String, Object> getGroupList(String uuid) {
+
+ HashMap<String, Object> responsePayload = new HashMap<>();
+ ArrayList<String> gidList = new ArrayList<String>();
+
+ HashMap<String, Object> condition = new HashMap<>();
+ condition.put(Constants.KEYFIELD_MIDLIST, uuid);
+
+ ArrayList<HashMap<String, Object>> result = AccountDBManager
+ .getInstance().selectRecord(Constants.GROUP_TABLE, condition);
+
+ for (HashMap<String, Object> element : result) {
+
+ GroupTable getGroupTable = new GroupTable();
+
+ getGroupTable = mTypeGroup.convertMaptoObject(element,
+ getGroupTable);
+
+ HashSet<String> midListSet = new HashSet<String>(
+ (Collection<? extends String>) getGroupTable.getMidlist());
+
+ if (midListSet.contains(uuid) && getGroupTable.getGtype()
+ .equals(Constants.REQ_GTYPE_PUBLIC)) {
+
+ gidList.add(getGroupTable.getGid());
+ }
+ }
+ responsePayload.put(Constants.KEYFIELD_GIDLIST, gidList);
+
+ return responsePayload;
+ }
+
+ public void addGroupMember(String gid, HashSet<String> midlist) {
+
+ getGroup(gid).addMember(midlist);
+ }
+
+ public void addGroupDevice(String gid, HashSet<String> dilist) {
+
+ getGroup(gid).addDevice(dilist);
+ }
+
+ public void removeGroupMember(String gid, HashSet<String> midlist) {
+
+ getGroup(gid).removeMember(midlist);
+ }
+
+ public void removeGroupDevice(String gid, HashSet<String> dilist) {
+
+ getGroup(gid).removeDevice(dilist);
+ }
+
+ public HashMap<String, Object> getGroupInfo(String gid, String mid) {
+
+ return getGroup(gid).getInfo(mid);
+ }
+
+ public HashMap<String, Object> addGroupSubscriber(String gid, String mid,
+ Device srcDevice, IRequest request) {
+
+ return getGroup(gid).addSubscriber(mid, srcDevice, request);
+ }
+
+ public HashMap<String, Object> removeGroupSubscriber(String gid,
+ String mid) {
+
+ return getGroup(gid).removeSubscriber(mid);
+ }
+
+ private Group getGroup(String gid) {
+
+ return mGroups.get(gid);
+ }
+}
--- /dev/null
+/*
+ * //******************************************************************
+ * //
+ * // 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.resources.acl.group;
+
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+
+import org.iotivity.cloud.accountserver.Constants;
+import org.iotivity.cloud.base.device.Device;
+import org.iotivity.cloud.base.exception.ServerException;
+import org.iotivity.cloud.base.exception.ServerException.BadRequestException;
+import org.iotivity.cloud.base.exception.ServerException.PreconditionFailedException;
+import org.iotivity.cloud.base.protocols.IRequest;
+import org.iotivity.cloud.base.protocols.IResponse;
+import org.iotivity.cloud.base.protocols.MessageBuilder;
+import org.iotivity.cloud.base.protocols.enums.ContentFormat;
+import org.iotivity.cloud.base.protocols.enums.ResponseStatus;
+import org.iotivity.cloud.base.resource.Resource;
+import org.iotivity.cloud.util.Cbor;
+
+public class GroupResource extends Resource {
+
+ private Cbor<HashMap<String, Object>> mCbor = new Cbor<>();
+
+ private static GroupManager mGrManager = new GroupManager();
+
+ public GroupResource() {
+ super(Arrays.asList(Constants.PREFIX_WELL_KNOWN, Constants.PREFIX_OCF,
+ Constants.ACL_URI, Constants.GROUP_URI));
+ }
+
+ public static GroupManager getInstance() {
+ return mGrManager;
+ }
+
+ @Override
+ public void onDefaultRequestReceived(Device srcDevice, IRequest request)
+ throws ServerException {
+
+ IResponse response = null;
+
+ if (request.getUriPathSegments().size() > getUriPathSegments().size()
+ + 1) {
+ throw new BadRequestException("uriPath is invalid");
+ }
+
+ switch (request.getMethod()) {
+ case POST:
+ response = handlePostRequest(request);
+ break;
+ case GET:
+ response = handleGetRequest(srcDevice, request);
+ break;
+ case DELETE:
+ response = handleDeleteRequest(request);
+ break;
+ default:
+ throw new BadRequestException(
+ request.getMethod() + " request type is not support");
+ }
+ srcDevice.sendResponse(response);
+ }
+
+ private IResponse handlePostRequest(IRequest request)
+ throws ServerException {
+ HashMap<String, Object> payloadData = mCbor
+ .parsePayloadFromCbor(request.getPayload(), HashMap.class);
+
+ if (getUriPathSegments().containsAll(request.getUriPathSegments())) {
+ String uuid = payloadData.get(Constants.REQ_GROUP_MASTER_ID)
+ .toString();
+ String gtype = (String) payloadData.get(Constants.REQ_GROUP_TYPE)
+ .toString();
+ if (uuid == null || gtype == null) {
+ throw new PreconditionFailedException(
+ "value of group property is invalid");
+ }
+ return MessageBuilder.createResponse(request,
+ ResponseStatus.CHANGED, ContentFormat.APPLICATION_CBOR,
+ mCbor.encodingPayloadToCbor(
+ mGrManager.createGroup(uuid, gtype)));
+ } else {
+ String gid = request.getUriPathSegments()
+ .get(getUriPathSegments().size());
+
+ if (payloadData.containsKey(Constants.REQ_MEMBER_LIST)) {
+ List<String> midList = (List<String>) payloadData
+ .get(Constants.REQ_MEMBER_LIST);
+ if (midList == null) {
+ throw new PreconditionFailedException(
+ "midList property is invalid");
+ }
+ mGrManager.addGroupMember(gid, new HashSet<String>(midList));
+ }
+
+ if (payloadData.containsKey(Constants.REQ_DEVICE_ID_LIST)) {
+ List<String> diList = (List<String>) payloadData
+ .get(Constants.REQ_DEVICE_ID_LIST);
+ if (diList == null) {
+ throw new PreconditionFailedException(
+ "diList property is invalid");
+ }
+ mGrManager.addGroupDevice(gid, new HashSet<String>(diList));
+ }
+ }
+ return MessageBuilder.createResponse(request, ResponseStatus.CHANGED);
+
+ }
+
+ private IResponse handleGetRequest(Device srcDevice, IRequest request)
+ throws ServerException {
+ HashMap<String, Object> responsePayload = null;
+ String mid = null;
+
+ if (!request.getUriQueryMap().containsKey(Constants.REQ_MEMBER)) {
+ throw new PreconditionFailedException("mid property is invalid");
+ }
+
+ mid = request.getUriQueryMap().get(Constants.REQ_MEMBER).get(0);
+
+ if (getUriPathSegments().containsAll(request.getUriPathSegments())) {
+ responsePayload = mGrManager.getGroupList(mid);
+ } else {
+ String gid = request.getUriPathSegments()
+ .get(getUriPathSegments().size());
+ switch (request.getObserve()) {
+ case NOTHING:
+ responsePayload = mGrManager.getGroupInfo(gid, mid);
+ break;
+ case SUBSCRIBE:
+ responsePayload = mGrManager.addGroupSubscriber(gid, mid,
+ srcDevice, request);
+ break;
+ case UNSUBSCRIBE:
+ responsePayload = mGrManager.removeGroupSubscriber(gid,
+ mid);
+ break;
+ default:
+ throw new BadRequestException(request.getObserve()
+ + " observe type is not support");
+ }
+ }
+ return MessageBuilder.createResponse(request, ResponseStatus.CONTENT,
+ ContentFormat.APPLICATION_CBOR,
+ mCbor.encodingPayloadToCbor(responsePayload));
+ }
+
+ private IResponse handleDeleteRequest(IRequest request)
+ throws ServerException {
+ if (getUriPathSegments().containsAll(request.getUriPathSegments())) {
+
+ String gmid = request.getUriQueryMap()
+ .get(Constants.REQ_GROUP_MASTER_ID).get(0);
+ String gid = request.getUriQueryMap().get(Constants.REQ_GROUP_ID)
+ .get(0);
+
+ if (gmid == null || gid == null) {
+ throw new PreconditionFailedException(
+ "gmid and gid property is invalid");
+ }
+ mGrManager.deleteGroup(gmid, gid);
+ } else {
+ String gid = request.getUriPathSegments()
+ .get(getUriPathSegments().size());
+
+ if (request.getUriQueryMap()
+ .containsKey(Constants.REQ_MEMBER_LIST)) {
+ List<String> midList = request.getUriQueryMap()
+ .get(Constants.REQ_MEMBER_LIST);
+ if (midList == null) {
+ throw new PreconditionFailedException(
+ "midList property is invalid");
+ }
+ mGrManager.removeGroupMember(gid, new HashSet<String>(midList));
+ }
+ if (request.getUriQueryMap()
+ .containsKey(Constants.REQ_DEVICE_ID_LIST)) {
+ List<String> diList = request.getUriQueryMap()
+ .get(Constants.REQ_DEVICE_ID_LIST);
+ if (diList == null) {
+ throw new PreconditionFailedException(
+ "diList property is invalid");
+ }
+ mGrManager.removeGroupDevice(gid, new HashSet<String>(diList));
+ }
+ }
+ return MessageBuilder.createResponse(request, ResponseStatus.DELETED);
+ }
+}
+++ /dev/null
-/*
- * //******************************************************************
- * //
- * // 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.token;
-
-public class Token {
-
- private String accessToken;
- private String refreshToken;
-
- public void setToken(String accessToken, String refreshToken) {
-
- this.accessToken = accessToken;
- this.refreshToken = refreshToken;
- }
-
- public String getAccessToken() {
-
- return accessToken;
- }
-
- public String getRefreshToken() {
-
- return refreshToken;
- }
-}
+++ /dev/null
-/*
- * //******************************************************************
- * //
- * // 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.token;
-
-import org.apache.oltu.oauth2.as.issuer.MD5Generator;
-import org.apache.oltu.oauth2.as.issuer.OAuthIssuer;
-import org.apache.oltu.oauth2.as.issuer.OAuthIssuerImpl;
-import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
-import org.iotivity.cloud.util.Log;
-
-public class TokenGenerator {
-
- String generateAccessToken() {
-
- OAuthIssuer oauthIssuerImpl = new OAuthIssuerImpl(new MD5Generator());
-
- String accessToken = null;
-
- try {
-
- accessToken = oauthIssuerImpl.accessToken();
- Log.d("accessToken : " + accessToken);
-
- } catch (OAuthSystemException e) {
-
- e.printStackTrace();
- }
-
- return accessToken;
- }
-
- String generateRefreshToken() {
-
- OAuthIssuer oauthIssuerImpl = new OAuthIssuerImpl(new MD5Generator());
-
- String refreshToken = null;
-
- try {
-
- refreshToken = oauthIssuerImpl.refreshToken();
- Log.d("refreshToken : " + refreshToken);
-
- } catch (OAuthSystemException e) {
-
- e.printStackTrace();
- }
-
- return refreshToken;
- }
-}
+++ /dev/null
-/*
- * //******************************************************************
- * //
- * // 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.token;
-
-import org.iotivity.cloud.accountserver.db.AccountDBManager;
-import org.iotivity.cloud.util.Log;
-
-public class TokenManager {
-
- private TokenGenerator tokenGenerator;
- private TokenValidator tokenValidator;
-
- public TokenManager() {
- tokenGenerator = new TokenGenerator();
- tokenValidator = new TokenValidator();
- }
-
- public Token generateToken() {
-
- String accessToken = tokenGenerator.generateAccessToken();
- String refreshToken = tokenGenerator.generateRefreshToken();
-
- Token token = new Token();
- token.setToken(accessToken, refreshToken);
-
- return token;
- }
-
- public Boolean verifyAccessToken(String token) {
-
- return tokenValidator.verifyAccessToken(token);
- }
-
- public Boolean verifyRefreshToken(String token) {
-
- return tokenValidator.verifyRefreshToken(token);
- }
-
- public long getRemainExpiredTime(String token) {
-
- return tokenValidator.getRemainedSeconds(token);
- }
-
- public Token refreshToken(String token) {
-
- String userId = null;
-
- Token refreshedToken = new Token();
-
- Boolean verifyRefreshToken = false;
- verifyRefreshToken = tokenValidator.verifyRefreshToken(token);
-
- if (!verifyRefreshToken) {
- Log.w("RefreshToken is not existed!");
- return null;
- }
-
- refreshedToken = generateToken();
-
- userId = AccountDBManager.getInstance().getUserIdByRefreshToken(token);
-
- AccountDBManager.getInstance().updateUserToken(userId, token,
- refreshedToken.getAccessToken(),
- refreshedToken.getRefreshToken());
-
- return refreshedToken;
- }
-
-}
+++ /dev/null
-/*
- * //******************************************************************
- * //
- * // 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.token;
-
-public class TokenPolicy {
-
- /* token type */
- public final static String BEARER_TOKEN = "bearer";
-
- /* expired time for accessToken */
- public final static int EXPIRES_IN = 3600; // 1hour
-
-}
+++ /dev/null
-/*
- * //******************************************************************
- * //
- * // 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.token;
-
-import java.text.DateFormat;
-import java.text.ParseException;
-import java.text.SimpleDateFormat;
-import java.util.Date;
-
-import org.iotivity.cloud.accountserver.db.AccountDBManager;
-import org.iotivity.cloud.util.Log;
-
-public class TokenValidator {
-
- Boolean verifyAccessToken(String token) {
-
- Boolean valid = false;
-
- // check token existed
- valid = AccountDBManager.getInstance().hasAccessToken(token);
- if (!valid) {
- Log.w("accessToken is not existed..");
- return false;
- }
-
- // check token expired
- if (getElaspedSeconds(token) > TokenPolicy.EXPIRES_IN) {
-
- Log.w("accessToken is expired..");
- return false;
- }
-
- return true;
- }
-
- public long getElaspedSeconds(String token) {
-
- String time = AccountDBManager.getInstance().getIssuedTime(token);
-
- DateFormat format = new SimpleDateFormat("yyyyMMddkkmm");
- Date currentTime = new Date();
- Date issuedTime = null;
-
- try {
- issuedTime = format.parse(time);
- } catch (ParseException e) {
- e.printStackTrace();
- }
-
- long difference = currentTime.getTime() - issuedTime.getTime();
- long elaspedSeconds = difference / 1000;
- // Log.d("currentTime : " + currentTime.getTime());
- // Log.d("issuedTime : " + issuedTime.getTime());
- // Log.d("difference : " + difference);
- Log.d("accessToken elasped time: " + elaspedSeconds + "s");
-
- return elaspedSeconds;
- }
-
- public long getRemainedSeconds(String token) {
- return TokenPolicy.EXPIRES_IN - getElaspedSeconds(token);
- }
-
- Boolean verifyRefreshToken(String token) {
-
- Boolean valid = false;
- // check token existed
- valid = AccountDBManager.getInstance().hasRefreshToken(token);
- if (!valid)
- Log.w("refreshToken is not existed..");
-
- return valid;
- }
-
-}
--- /dev/null
+package org.iotivity.cloud.accountserver.util;
+
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.util.HashMap;
+import java.util.Iterator;
+
+import org.iotivity.cloud.base.exception.ServerException.InternalServerErrorException;
+
+public class TypeCastingManager<T> {
+ public TypeCastingManager() {
+
+ }
+
+ public HashMap<String, Object> convertObjectToMap(T objClass) {
+
+ try {
+ Field[] fieldList = objClass.getClass().getDeclaredFields();
+ HashMap<String, Object> map = new HashMap<>();
+
+ for (Field field : fieldList) {
+ field.setAccessible(true);
+ Object value = field.get(objClass);
+ if (value != null) {
+ String fieldName = field.getName();
+ map.put(fieldName, value);
+ }
+ }
+ return map;
+ } catch (Exception e) {
+ throw new InternalServerErrorException(
+ "Object to Map casting error");
+ }
+ }
+
+ public T convertMaptoObject(HashMap<String, Object> map, T objClass) {
+
+ String keyAttribute = null;
+ String methodName = null;
+ Iterator<String> iter = map.keySet().iterator();
+ String prefixName = "set";
+ while (iter.hasNext()) {
+ keyAttribute = iter.next().toString();
+ methodName = makeMethodName(keyAttribute, prefixName);
+
+ Method[] methodList = objClass.getClass().getDeclaredMethods();
+
+ for (Method method : methodList) {
+ if (methodName.equals(method.getName())) {
+ try {
+ method.invoke(objClass, map.get(keyAttribute));
+ } catch (Exception e) {
+ e.printStackTrace();
+ throw new InternalServerErrorException(
+ "Map to Object casting error");
+ }
+ }
+ }
+ }
+ return objClass;
+ }
+
+ private String makeMethodName(String keyAttribute, String prefixName) {
+
+ String methodName = null;
+
+ methodName = prefixName + keyAttribute.substring(0, 1).toUpperCase()
+ + keyAttribute.substring(1);
+
+ return methodName;
+ }
+}
--- /dev/null
+-----BEGIN CERTIFICATE-----
+MIIDBjCCAe4CCQC15rNSV0fgHzANBgkqhkiG9w0BAQsFADBFMQswCQYDVQQGEwJB
+VTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50ZXJuZXQgV2lkZ2l0
+cyBQdHkgTHRkMB4XDTE2MDYyODA1MzUwM1oXDTIxMDYyNzA1MzUwM1owRTELMAkG
+A1UEBhMCQVUxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoMGEludGVybmV0
+IFdpZGdpdHMgUHR5IEx0ZDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB
+AMs0PAj60hmrVtvaP52m8Uu5cgsoYOM9OpI2IxrzGVhbtugXry5B6nXay7Btio2S
+AAV9vb0jLan/WEggLoZSY6Em0l9iUPSNi23FyPG0bcWZTZplex+1DV8hKIM3/icH
+K6NrQz0OsilWGR9jyIExDDFWw1KFY7KCGa6clBpkjMNsHis+iyntGH+syfSD2lz9
+SJ7rTP/JWwd11Jim4Wsk0szTN4VfGDasto9G5Kd+g5Zvx8H8hUa969vLvwEyI8su
++QJu5jmO/oTH1E4vDxVaesb5J08p4Uv1ktes5RMl6LbnofLiqBzaWVJYTC7+Cyj7
+AqiEAtudl5gNtCh/+qsPdBUCAwEAATANBgkqhkiG9w0BAQsFAAOCAQEAS1SVOvp/
+1zo4QyaLT7Gmxa5+l2E3m2GZovVpqttHBjrDDerGSldZQBt4lUEh3ItaTup/2AxE
+tPRxpo1BVLTmu6LOU0/FVXIQGIYyj6rJwsuKUIV4vEwxat51TLjU57JmKb/ZLF5N
+Z9K4dM5zNGeX1IIxn7bpy7cBqf95M2JQoDjxBBd7crIKgkEoX4cAjavIqcDuoiBB
+KSQp7lf8Z490E3GHyLbgFncSAZwhQs013at5JXsrtwOrTPgA5AldCj9aboqYySFg
+Xg+ANx6f7PNkb6GEErGhfFt1ji+Lsrm1GNQSpA7Qp+ev8B13NmFvTLBb78/oK22k
++tOYqL5c2KjHbw==
+-----END CERTIFICATE-----
--- /dev/null
+-----BEGIN PRIVATE KEY-----
+MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDLNDwI+tIZq1bb
+2j+dpvFLuXILKGDjPTqSNiMa8xlYW7boF68uQep12suwbYqNkgAFfb29Iy2p/1hI
+IC6GUmOhJtJfYlD0jYttxcjxtG3FmU2aZXsftQ1fISiDN/4nByuja0M9DrIpVhkf
+Y8iBMQwxVsNShWOyghmunJQaZIzDbB4rPosp7Rh/rMn0g9pc/Uie60z/yVsHddSY
+puFrJNLM0zeFXxg2rLaPRuSnfoOWb8fB/IVGvevby78BMiPLLvkCbuY5jv6Ex9RO
+Lw8VWnrG+SdPKeFL9ZLXrOUTJei256Hy4qgc2llSWEwu/gso+wKohALbnZeYDbQo
+f/qrD3QVAgMBAAECggEAQIOh99viLoImfoCJJ/1jqH4FBiPYtuyultMXTCwYRORB
+auhyFsaYsLg5aRcuIQpUdWnZfp4XllxaY/PLsZugw/42VlA5kZsKxFxCEvMM0up8
+J+PGNmfeCfDWEusJBs0Q/r5ER7NNvy/1o/CjLNksnNGGC8ILyBXkH3rYzpRT2Ir/
+HAGf4+hW6Co3eQZQe5sfVp7FyD13SkpRZqX9yBXQOSDGaujRfB58xzWcBCcrqJ5M
+RqVykvm6X/uuq2Jmsq7/SV+9xIqlBBiuwq2lkhGL0gtTQPl4C8zbQGoxRf+f9Cqh
+a77RbrMelxBHcmS6C878et3ESw5H0FlDeghrDNXvgQKBgQDqWzJ/H9/LFy6Gt3S+
+vBEygEm24tgVKB1MjGhZ7clZ7DRa2eWq1xfeii1SsBp9WrGLCH4JZUu/s1eQ87Td
+xFYpQydxshR4ey69CaYYMMakDyID0RglSd5wjFDTZ5w9kChEWt8hyVIi0wQQTiGZ
+L7et3XUxzSYgOJWgZfhaMZob9QKBgQDd+IRHUtMb3izXmqR3gA1Ogo8s4XB/WGfB
+NeY1hcDZgp8Wy7HFzL0myn5IxoTKgJHY6BQnZjW7rrjGxp6506SuheUfm0toC2wy
+bfTAtieeOappXFL0jU5mn/2FIvURHQuN5JaP8PlNtkDyrR9fAeAGlNIfCeH3qqe0
+1ZbbjZADoQKBgQCt4UZBHfQcqjGCEMHU9pLH5nlK8VojsGS0tASEnLHlPyTFN6B4
+tihmnBzumey9jznlj0J8VCT0serJiJhsZk0LRmEQsXEQx0yxQ2Rx1Fa9yOCS9mO0
+3u7kkKczg09gOgI2XTnqxoVjgy8jreSt1MKyhHp8ndqo03Lo1F+FBAJ0tQKBgQCM
+MVnackVDZJ+NzO3zS70byPoErp4O0Bc3wIMVatTSi91O2Hf/JcCRr3LzI+7atzlm
+da3E9JkbYM7zPJ8jXri0QXzk6YBGxnAfqbLbxDBhjqpCwTzjmBvcVVAZtmpx1JZn
+l+hAIUJUArgijZUyvExx26yaTfOaKP6jCAOvx0keAQKBgQCD+M63CCkJNdpzKdJM
+ZJTOlgpyZ0s1rp1SvGHed+HKgw/3CvEXAdCAIX+60QzmjYJZpGvqnXhz3+5tDIsc
+DlD4PPUWlHmMdeZ5AmuoGpCvLuZxCtZqGDBor1x3+JOWckY5PhSwe+6NFEoq+BXm
+QDcixZP13I5e2Kgx+fReu7LqQg==
+-----END PRIVATE KEY-----
--- /dev/null
+-----BEGIN CERTIFICATE-----
+MIIC/jCCAeYCAQEwDQYJKoZIhvcNAQELBQAwRTELMAkGA1UEBhMCQVUxEzARBgNV
+BAgMClNvbWUtU3RhdGUxITAfBgNVBAoMGEludGVybmV0IFdpZGdpdHMgUHR5IEx0
+ZDAeFw0xNjA2MjgwNTMzNThaFw0yNjA2MjYwNTMzNThaMEUxCzAJBgNVBAYTAkFV
+MRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBXaWRnaXRz
+IFB0eSBMdGQwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC1HHkfMG9c
+BJ7ZeCIBKe7pSjpptvi+hzpdV72W7szpWDlTQdUaRxKL9aoNxbyuF5OL8xAQ9s28
+IqIxdPW7X3JAmkLigzMCo2xtXHz/OyvomU6fhibneQw5De+iUoD68zdG+/k1NcAW
+xx+VEAMw4fvZvYSVEQ1aKFnjtrQ8o6Zfe5+MRTvBq+G0+jwZWJEoKbpxIPpNWPGx
+AV17tEpe+lg27jEYDYG1QUiL2TG80ZjQQL95OjETYf8EIxoqrKHvHCvDin0zdd+E
+qPN0Y+Rhkl3PYoxWm7d8z0p1mD7lcwOMvy1KgEgtJ7SHy0D2SIW/KaDox/kRPC1P
+ksFeAS2B0Z9zAgMBAAEwDQYJKoZIhvcNAQELBQADggEBAAtHjimMywXn893Ifu1v
+tNnL9ITMpQhsHAlg1QBVEyjGZLIjUgMhsWljVwTC1PdBrO7V0ElYbeV+LKYGwDk6
+fjBJogCLgZiUw18F8TjHC/qDsoWEsm1iB4KcTZkk0nm/2vidHK0TMLzCohR71/vN
+KS2rtiQDYGKe9EzjNSO3GlCWkVTYtJNhALa/BfDza5keRkwmldJYhlx4rQH5yVRn
+t5k87vjX0h7m8MzIwiAb2s/b9XBlM1FuFx3FxcVjBl7KtUAU7twU8v5LenjWDSH1
+D1jnKiZUUspgovhosPRqmxGNXldaX1E+RJmxdtqUVg4co/zjAbTY7C+7ZYIZBo46
+Ll0=
+-----END CERTIFICATE-----
import org.iotivity.cloud.ciserver.DeviceServerSystem.CoapDevicePool;
import org.iotivity.cloud.ciserver.resources.DiResource;
import org.iotivity.cloud.ciserver.resources.KeepAliveResource;
-import org.iotivity.cloud.ciserver.resources.proxy.Account;
-import org.iotivity.cloud.ciserver.resources.proxy.DevicePresence;
-import org.iotivity.cloud.ciserver.resources.proxy.MessageQueue;
-import org.iotivity.cloud.ciserver.resources.proxy.ResourceDirectory;
-import org.iotivity.cloud.ciserver.resources.proxy.ResourceFind;
-import org.iotivity.cloud.ciserver.resources.proxy.ResourcePresence;
+import org.iotivity.cloud.ciserver.resources.proxy.account.Account;
+import org.iotivity.cloud.ciserver.resources.proxy.account.AccountSession;
+import org.iotivity.cloud.ciserver.resources.proxy.account.Acl;
+import org.iotivity.cloud.ciserver.resources.proxy.account.AclGroup;
+import org.iotivity.cloud.ciserver.resources.proxy.mq.MessageQueue;
+import org.iotivity.cloud.ciserver.resources.proxy.rd.DevicePresence;
+import org.iotivity.cloud.ciserver.resources.proxy.rd.ResourceDirectory;
+import org.iotivity.cloud.ciserver.resources.proxy.rd.ResourceFind;
+import org.iotivity.cloud.ciserver.resources.proxy.rd.ResourcePresence;
import org.iotivity.cloud.util.Log;
public class CloudInterfaceServer {
System.out.println("-----CI SERVER-------");
if (args.length != 8) {
- Log.e(
- "coap server port and RDServer_Address port AccountServer_Address Port MQBroker_Address Port and TLS mode required\n"
- + "ex) 5683 127.0.0.1 5684 127.0.0.1 5685 127.0.0.1 5686 0\n");
+ Log.e("coap server port and RDServer_Address port AccountServer_Address Port MQBroker_Address Port and TLS mode required\n"
+ + "ex) 5683 127.0.0.1 5684 127.0.0.1 5685 127.0.0.1 5686 0\n");
return;
}
DeviceServerSystem deviceServer = new DeviceServerSystem();
Account acHandler = new Account();
+ AccountSession acSessionHandler = new AccountSession();
ResourceDirectory rdHandler = new ResourceDirectory();
ResourceFind resHandler = new ResourceFind();
ResourcePresence adHandler = new ResourcePresence();
DevicePresence prsHandler = new DevicePresence();
MessageQueue mqHandler = new MessageQueue();
+ Acl aclHandler = new Acl();
+ AclGroup aclGroupHandler = new AclGroup();
CoapDevicePool devicePool = deviceServer.getDevicePool();
deviceServer.addResource(acHandler);
+ deviceServer.addResource(acSessionHandler);
+
deviceServer.addResource(rdHandler);
deviceServer.addResource(resHandler);
deviceServer.addResource(mqHandler);
+ deviceServer.addResource(aclHandler);
+
+ deviceServer.addResource(aclGroupHandler);
+
KeepAliveResource resKeepAlive = new KeepAliveResource(
new int[] { 1, 2, 4, 8 });
public class Constants extends OCFConstants {
- public static final int MIN_TO_LIVE = 10;
+ public static final int MIN_TO_LIVE = 10;
- public static final String DEVICE_ID = "di";
- public static final String PRESENCE_STATE = "state";
+ public static final String USER_ID = "uid";
+ public static final String DEVICE_ID = "di";
+ public static final String PRESENCE_STATE = "state";
- public static final String SEARCH_ACCESS_TOKEN = "accesstoken";
- public static final Object SEARCH_REFRESH_TOKEN = "refreshtoken";
- public static final Object EXPIRES_IN = "expiresin";
+ public static final String REQ_LOGIN = "login";
+
+ public static final String ACCESS_TOKEN = "accesstoken";
+ public static final Object REFRESH_TOKEN = "refreshtoken";
+ public static final Object EXPIRES_IN = "expiresin";
+
+ public static final String REQ_GROUP_MASTER_ID = "gmid";
+ public static final String REQ_MEMBER_ID = "mid";
+ public static final String REQ_MEMBER_LIST = "midlist";
+ public static final String REQ_DEVICE_ID = "di";
+ public static final String REQ_DEVICE_LIST = "dilist";
}
}
} catch (Throwable t) {
+ Log.f(ctx.channel(), t);
ResponseStatus responseStatus = t instanceof ServerException
? ((ServerException) t).getErrorResponse()
- : ResponseStatus.BAD_REQUEST;
+ : ResponseStatus.INTERNAL_SERVER_ERROR;
ctx.channel().writeAndFlush(MessageBuilder
.createResponse((CoapRequest) msg, responseStatus));
- Log.f(ctx.channel(), t);
ctx.channel().close();
}
}
Cbor<HashMap<String, Object>> cbor = new Cbor<>();
IRequestChannel RDServer = ConnectorPool.getConnection("rd");
HashMap<String, Object> payload = new HashMap<String, Object>();
- payload.put(Constants.DEVICE_ID, deviceId);
+ payload.put(Constants.REQ_DEVICE_ID, deviceId);
payload.put(Constants.PRESENCE_STATE, state);
StringBuffer uriPath = new StringBuffer();
uriPath.append("/" + Constants.PREFIX_WELL_KNOWN);
}
CoapDevice device = new CoapDevice(ctx,
- (String) authPayload.get("di"),
- (String) authPayload.get("accesstoken"));
+ (String) authPayload.get(Constants.DEVICE_ID),
+ (String) authPayload.get(Constants.USER_ID),
+ (String) authPayload.get(Constants.ACCESS_TOKEN));
// Create device first and pass to upperlayer
ctx.channel().attr(keyDevice).set(device);
private CoapDevicePool mDevicePool = null;
public DiResource(CoapDevicePool devicePool) {
- super(Arrays.asList(Constants.DEVICE_ID));
+ super(Arrays.asList(Constants.REQ_DEVICE_ID));
mDevicePool = devicePool;
addQueryHandler(
convertedUri = "/di/" + di + "/" + coapResponse.getUriPath();
}
- return MessageBuilder
- .modifyResponse(response, convertedUri, null, null);
+ return MessageBuilder.modifyResponse(response, convertedUri, null,
+ null);
}
class LinkInterfaceHandler implements IResponseEventHandler {
mSrcDevice.sendResponse(MessageBuilder.modifyResponse(
convertReponseUri(response, mTargetDI),
- ContentFormat.APPLICATION_CBOR,
- linkPayload != null ? mCbor
- .encodingPayloadToCbor(linkPayload) : null));
+ ContentFormat.APPLICATION_CBOR, linkPayload != null
+ ? mCbor.encodingPayloadToCbor(linkPayload) : null));
}
}
String deviceId = request.getUriPathSegments().get(1);
- requestChannel.sendRequest(MessageBuilder.modifyRequest(request,
- extractTargetUriPath(request), null, null, null),
+ requestChannel.sendRequest(
+ MessageBuilder.modifyRequest(request,
+ extractTargetUriPath(request), null, null, null),
new LinkInterfaceHandler(deviceId, srcDevice));
}
String deviceId = request.getUriPathSegments().get(1);
- requestChannel.sendRequest(MessageBuilder.modifyRequest(request,
- extractTargetUriPath(request), null, null, null),
+ requestChannel.sendRequest(
+ MessageBuilder.modifyRequest(request,
+ extractTargetUriPath(request), null, null, null),
new DefaultResponseHandler(deviceId, srcDevice));
}
* //
* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
*/
-package org.iotivity.cloud.ciserver.resources.proxy;
+package org.iotivity.cloud.ciserver.resources.proxy.account;
import java.util.Arrays;
import org.iotivity.cloud.base.device.IRequestChannel;
import org.iotivity.cloud.base.exception.ServerException;
import org.iotivity.cloud.base.protocols.IRequest;
+import org.iotivity.cloud.base.protocols.MessageBuilder;
+import org.iotivity.cloud.base.protocols.enums.RequestMethod;
import org.iotivity.cloud.base.resource.Resource;
import org.iotivity.cloud.ciserver.Constants;
-public class ResourceDirectory extends Resource {
- IRequestChannel mRDServer = null;
+public class Account extends Resource {
+ IRequestChannel mAuthServer = null;
- public ResourceDirectory() {
- super(Arrays.asList(Constants.PREFIX_OIC, Constants.RD_URI));
+ public Account() {
+ super(Arrays.asList(Constants.PREFIX_WELL_KNOWN, Constants.PREFIX_OCF,
+ Constants.ACCOUNT_URI));
- mRDServer = ConnectorPool.getConnection("rd");
+ mAuthServer = ConnectorPool.getConnection("account");
}
@Override
public void onDefaultRequestReceived(Device srcDevice, IRequest request)
throws ServerException {
- // Token exchange is done by CoapClient
- mRDServer.sendRequest(request, srcDevice);
+ if (request.getMethod().equals(RequestMethod.DELETE)) {
+ String di = request.getUriQueryMap().get(Constants.REQ_DEVICE_ID)
+ .get(0);
+ StringBuffer uriQuery = new StringBuffer();
+ uriQuery.append(Constants.REQ_DEVICE_ID + "=" + di);
+ uriQuery.append(";");
+ uriQuery.append(Constants.USER_ID + "=" + srcDevice.getUserId());
+
+ request = MessageBuilder.modifyRequest(request, null,
+ uriQuery.toString(), null, null);
+ }
+ mAuthServer.sendRequest(request, srcDevice);
}
}
--- /dev/null
+/*
+ * //******************************************************************
+ * //
+ * // 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.ciserver.resources.proxy.account;
+
+import java.util.Arrays;
+import java.util.HashMap;
+
+import org.iotivity.cloud.base.connector.ConnectorPool;
+import org.iotivity.cloud.base.device.Device;
+import org.iotivity.cloud.base.device.IRequestChannel;
+import org.iotivity.cloud.base.exception.ServerException;
+import org.iotivity.cloud.base.protocols.IRequest;
+import org.iotivity.cloud.base.protocols.MessageBuilder;
+import org.iotivity.cloud.base.protocols.enums.ContentFormat;
+import org.iotivity.cloud.base.resource.Resource;
+import org.iotivity.cloud.ciserver.Constants;
+import org.iotivity.cloud.util.Cbor;
+
+public class AccountSession extends Resource {
+ IRequestChannel mAuthServer = null;
+ private Cbor<HashMap<String, Object>> mCbor = new Cbor<>();
+
+ public AccountSession() {
+ super(Arrays.asList(Constants.PREFIX_WELL_KNOWN, Constants.PREFIX_OCF,
+ Constants.ACCOUNT_URI, Constants.SESSION_URI));
+
+ mAuthServer = ConnectorPool.getConnection("account");
+ }
+
+ @Override
+ public void onDefaultRequestReceived(Device srcDevice, IRequest request)
+ throws ServerException {
+ HashMap<String, Object> payloadData = mCbor
+ .parsePayloadFromCbor(request.getPayload(), HashMap.class);
+ if (payloadData.get(Constants.REQ_LOGIN).toString().equals("false")) {
+ payloadData.put(Constants.USER_ID, srcDevice.getUserId());
+ payloadData.put(Constants.DEVICE_ID, srcDevice.getDeviceId());
+ payloadData.put(Constants.ACCESS_TOKEN, srcDevice.getAccessToken());
+ request = MessageBuilder.modifyRequest(request, null, null,
+ ContentFormat.APPLICATION_CBOR,
+ mCbor.encodingPayloadToCbor(payloadData));
+ }
+ mAuthServer.sendRequest(request, srcDevice);
+ }
+}
\ No newline at end of file
* //
* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
*/
-package org.iotivity.cloud.ciserver.resources.proxy;
+package org.iotivity.cloud.ciserver.resources.proxy.account;
import java.util.Arrays;
import org.iotivity.cloud.base.resource.Resource;
import org.iotivity.cloud.ciserver.Constants;
-public class Account extends Resource {
+public class Acl extends Resource {
IRequestChannel mAuthServer = null;
- public Account() {
+ public Acl() {
super(Arrays.asList(Constants.PREFIX_WELL_KNOWN, Constants.PREFIX_OCF,
- Constants.ACCOUNT_URI));
+ Constants.ACL_URI));
mAuthServer = ConnectorPool.getConnection("account");
}
// Token exchange is done by CoapClient
mAuthServer.sendRequest(request, srcDevice);
}
-}
+}
\ No newline at end of file
--- /dev/null
+/*
+ * //******************************************************************
+ * //
+ * // 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.ciserver.resources.proxy.account;
+
+import java.util.Arrays;
+import java.util.HashMap;
+
+import org.iotivity.cloud.base.connector.ConnectorPool;
+import org.iotivity.cloud.base.device.Device;
+import org.iotivity.cloud.base.device.IRequestChannel;
+import org.iotivity.cloud.base.exception.ServerException;
+import org.iotivity.cloud.base.exception.ServerException.BadRequestException;
+import org.iotivity.cloud.base.protocols.IRequest;
+import org.iotivity.cloud.base.protocols.MessageBuilder;
+import org.iotivity.cloud.base.protocols.enums.ContentFormat;
+import org.iotivity.cloud.base.resource.Resource;
+import org.iotivity.cloud.ciserver.Constants;
+import org.iotivity.cloud.util.Cbor;
+
+public class AclGroup extends Resource {
+
+ private IRequestChannel mAuthServer = null;
+ private Cbor<HashMap<String, Object>> mCbor = new Cbor<>();
+
+ public AclGroup() {
+ super(Arrays.asList(Constants.PREFIX_WELL_KNOWN, Constants.PREFIX_OCF,
+ Constants.ACL_URI, Constants.GROUP_URI));
+
+ mAuthServer = ConnectorPool.getConnection("account");
+ }
+
+ @Override
+ public void onDefaultRequestReceived(Device srcDevice, IRequest request)
+ throws ServerException {
+ switch (request.getMethod()) {
+
+ case POST:
+ HashMap<String, Object> payloadData = mCbor
+ .parsePayloadFromCbor(request.getPayload(),
+ HashMap.class);
+ if (getUriPathSegments()
+ .containsAll(request.getUriPathSegments())) {
+ payloadData.put(Constants.REQ_GROUP_MASTER_ID,
+ srcDevice.getUserId());
+ } else {
+ if (!payloadData.containsKey(Constants.REQ_DEVICE_LIST)
+ && !payloadData
+ .containsKey(Constants.REQ_MEMBER_LIST)) {
+ payloadData.put(Constants.REQ_MEMBER_LIST,
+ Arrays.asList(srcDevice.getUserId()));
+ }
+ }
+ request = MessageBuilder.modifyRequest(request, null, null,
+ ContentFormat.APPLICATION_CBOR,
+ mCbor.encodingPayloadToCbor(payloadData));
+ break;
+ case GET:
+ StringBuffer uriGetQuery = new StringBuffer();
+ uriGetQuery.append(
+ Constants.REQ_MEMBER_ID + "=" + srcDevice.getUserId());
+ request = MessageBuilder.modifyRequest(request, null,
+ uriGetQuery.toString(), null, null);
+ break;
+ case DELETE:
+ String uriDeleteQuery;
+ StringBuffer additionalQuery = new StringBuffer();
+ if (getUriPathSegments()
+ .containsAll(request.getUriPathSegments())) {
+ additionalQuery.append(Constants.REQ_GROUP_MASTER_ID + "="
+ + srcDevice.getUserId());
+ uriDeleteQuery = request.getUriQuery() + ";"
+ + additionalQuery.toString();
+ request = MessageBuilder.modifyRequest(request, null,
+ uriDeleteQuery, null, null);
+ } else {
+ if (request.getUriQuery() == null) {
+ additionalQuery.append(Constants.REQ_MEMBER_LIST + "="
+ + srcDevice.getUserId());
+ request = MessageBuilder.modifyRequest(request, null,
+ additionalQuery.toString(), null, null);
+ }
+ }
+ break;
+ default:
+ throw new BadRequestException(
+ request.getMethod() + " request type is not support");
+ }
+ mAuthServer.sendRequest(request, srcDevice);
+ }
+}
\ No newline at end of file
* //
* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
*/
-package org.iotivity.cloud.ciserver.resources.proxy;
+package org.iotivity.cloud.ciserver.resources.proxy.mq;
import java.util.Arrays;
* //
* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
*/
-package org.iotivity.cloud.ciserver.resources.proxy;
+package org.iotivity.cloud.ciserver.resources.proxy.rd;
-import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
+import java.util.List;
import org.iotivity.cloud.base.connector.ConnectorPool;
-import org.iotivity.cloud.base.device.CoapDevice;
import org.iotivity.cloud.base.device.Device;
import org.iotivity.cloud.base.device.IRequestChannel;
import org.iotivity.cloud.base.device.IResponseEventHandler;
import org.iotivity.cloud.base.exception.ClientException;
import org.iotivity.cloud.base.exception.ClientException.BadResponseException;
import org.iotivity.cloud.base.exception.ServerException;
+import org.iotivity.cloud.base.exception.ServerException.UnAuthorizedException;
import org.iotivity.cloud.base.protocols.IRequest;
import org.iotivity.cloud.base.protocols.IResponse;
import org.iotivity.cloud.base.protocols.MessageBuilder;
import org.iotivity.cloud.util.Cbor;
public class DevicePresence extends Resource {
- IRequestChannel mASServer = null;
+ IRequestChannel mASServer = null;
+ private Cbor<HashMap<String, Object>> mCbor = new Cbor<>();
public DevicePresence() {
super(Arrays.asList(Constants.PREFIX_WELL_KNOWN, Constants.PREFIX_OCF,
@Override
public void onResponseReceived(IResponse response)
throws ClientException {
-
switch (response.getStatus()) {
- case VALID:
- mRDServer.sendRequest(mRequest, mSrcDevice);
- break;
-
case CONTENT:
StringBuilder additionalQuery = new StringBuilder();
- Cbor<HashMap<String, ArrayList<String>>> responsePayload = new Cbor<>();
-
- ArrayList<String> deviceList = responsePayload
+ HashMap<String, Object> payloadData = mCbor
.parsePayloadFromCbor(response.getPayload(),
- HashMap.class)
- .get("devices");
-
- int index = deviceList.size();
- for (String deviceId : deviceList) {
- if (!deviceId.equals(mSrcDevice.getDeviceId())) {
- additionalQuery.append("di=");
- additionalQuery.append(deviceId);
- if (--index > 0) {
- additionalQuery.append("&");
+ HashMap.class);
+ List<String> deviceList = (List<String>) payloadData
+ .get(Constants.REQ_DEVICE_LIST);
+ if (deviceList != null) {
+ int index = deviceList.size();
+ if (mRequest.getUriQuery() == null) {
+ for (String device : deviceList) {
+ if (!device.equals(mSrcDevice.getDeviceId())) {
+ additionalQuery
+ .append(Constants.REQ_DEVICE_ID
+ + "=" + device);
+ if (--index > 0) {
+ additionalQuery.append(";");
+ }
+ }
+ }
+ String uriQuery = (mRequest.getUriQuery() == null
+ ? "" : mRequest.getUriQuery()) + ";"
+ + additionalQuery.toString();
+ mRequest = MessageBuilder.modifyRequest(mRequest,
+ null, uriQuery, null, null);
+ } else {
+ List<String> originDeviceList = mRequest
+ .getUriQueryMap()
+ .get(Constants.REQ_DEVICE_ID);
+ if (originDeviceList == null) {
+ throw new UnAuthorizedException(
+ "device is not include in group");
+ }
+ for (String device : originDeviceList) {
+ if (!deviceList.contains(device)) {
+ throw new UnAuthorizedException(device
+ + " device is not include in group");
+ }
}
}
- }
-
- String uriQuery = (mRequest.getUriQuery() == null ? ""
- : mRequest.getUriQuery() + "&")
- + additionalQuery.toString();
- IRequest requestToAS = MessageBuilder.modifyRequest(
- mRequest, null, uriQuery, null, null);
-
- mRDServer.sendRequest(requestToAS, mSrcDevice);
+ mRDServer.sendRequest(mRequest, mSrcDevice);
+ } else
+ throw new UnAuthorizedException(
+ "There is not device in group");
break;
-
default:
throw new BadResponseException(
response.getStatus().toString()
@Override
public void onDefaultRequestReceived(Device srcDevice, IRequest request)
throws ServerException {
- // Token exchange is done by CoapClient
- CoapDevice coapDevice = (CoapDevice) srcDevice;
StringBuffer uriQuery = new StringBuffer();
- uriQuery.append(Constants.SEARCH_ACCESS_TOKEN + "=");
- uriQuery.append(coapDevice.getAccessToken());
-
- if (request.getUriQueryMap() != null) {
- if (request.getUriQueryMap().get("di") != null) {
- String di = request.getUriQueryMap().get("di").get(0);
- if (di != null) {
- uriQuery.append("&");
- uriQuery.append("di" + "=");
- uriQuery.append(di);
- }
- }
- }
+ uriQuery.append(Constants.REQ_MEMBER_ID + "=" + srcDevice.getUserId());
StringBuffer uriPath = new StringBuffer();
uriPath.append(Constants.PREFIX_WELL_KNOWN + "/");
uriPath.append(Constants.PREFIX_OCF + "/");
- uriPath.append(Constants.ACCOUNT_URI + "/");
- uriPath.append(Constants.DEVICE_URI);
+ uriPath.append(Constants.ACL_URI + "/");
+ uriPath.append(Constants.GROUP_URI + "/");
+ uriPath.append(srcDevice.getUserId());
IRequest requestToAS = MessageBuilder.createRequest(RequestMethod.GET,
uriPath.toString(), uriQuery.toString());
mASServer.sendRequest(requestToAS,
new AccountReceiveHandler(request, srcDevice));
}
-}
+}
\ No newline at end of file
* //
* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
*/
-package org.iotivity.cloud.ciserver.resources.proxy;
+package org.iotivity.cloud.ciserver.resources.proxy.rd;
-import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import org.iotivity.cloud.base.connector.ConnectorPool;
-import org.iotivity.cloud.base.device.CoapDevice;
import org.iotivity.cloud.base.device.Device;
import org.iotivity.cloud.base.device.IRequestChannel;
import org.iotivity.cloud.base.device.IResponseEventHandler;
import org.iotivity.cloud.base.protocols.IRequest;
import org.iotivity.cloud.base.protocols.IResponse;
import org.iotivity.cloud.base.protocols.MessageBuilder;
+import org.iotivity.cloud.base.protocols.enums.ContentFormat;
import org.iotivity.cloud.base.protocols.enums.RequestMethod;
import org.iotivity.cloud.base.resource.Resource;
import org.iotivity.cloud.ciserver.Constants;
import org.iotivity.cloud.util.Cbor;
-public class ResourcePresence extends Resource {
- IRequestChannel mASServer = null;
+public class ResourceDirectory extends Resource {
+ private Cbor<HashMap<String, Object>> mCbor = new Cbor<>();
+ IRequestChannel mASServer = null;
- public ResourcePresence() {
- super(Arrays.asList(Constants.PREFIX_OIC, Constants.RES_PRESENCE_URI));
+ public ResourceDirectory() {
+ super(Arrays.asList(Constants.PREFIX_OIC, Constants.RD_URI));
mASServer = ConnectorPool.getConnection("account");
}
throws ClientException {
switch (response.getStatus()) {
- case VALID:
- mRDServer.sendRequest(mRequest, mSrcDevice);
- break;
+ case CHANGED:
- case CONTENT:
- StringBuilder additionalQuery = new StringBuilder();
-
- Cbor<HashMap<String, ArrayList<String>>> responsePayload = new Cbor<>();
-
- ArrayList<String> deviceList = responsePayload
- .parsePayloadFromCbor(response.getPayload(),
- HashMap.class)
- .get("devices");
-
- int index = deviceList.size();
- for (String deviceId : deviceList) {
- if (!deviceId.equals(mSrcDevice.getDeviceId())) {
- additionalQuery.append("di=");
- additionalQuery.append(deviceId);
- if (--index > 0) {
- additionalQuery.append("&");
- }
- }
- }
-
- String uriQuery = (mRequest.getUriQuery() == null ? ""
- : mRequest.getUriQuery() + "&")
- + additionalQuery.toString();
- IRequest requestToAS = MessageBuilder.modifyRequest(
- mRequest, null, uriQuery, null, null);
-
- mRDServer.sendRequest(requestToAS, mSrcDevice);
+ mRDServer.sendRequest(mRequest, mSrcDevice);
break;
default:
@Override
public void onDefaultRequestReceived(Device srcDevice, IRequest request)
throws ServerException {
- // Token exchange is done by CoapClient
- CoapDevice coapDevice = (CoapDevice) srcDevice;
- StringBuffer uriQuery = new StringBuffer();
- uriQuery.append(Constants.SEARCH_ACCESS_TOKEN + "=");
- uriQuery.append(coapDevice.getAccessToken());
-
- if (request.getUriQueryMap() != null) {
- String di = request.getUriQueryMap().get("di").get(0);
- if (di != null) {
- uriQuery.append("&");
- uriQuery.append("di" + "=");
- uriQuery.append(di);
- }
- }
StringBuffer uriPath = new StringBuffer();
uriPath.append(Constants.PREFIX_WELL_KNOWN + "/");
uriPath.append(Constants.PREFIX_OCF + "/");
- uriPath.append(Constants.ACCOUNT_URI + "/");
- uriPath.append(Constants.DEVICE_URI);
+ uriPath.append(Constants.ACL_URI + "/");
+ uriPath.append(Constants.GROUP_URI + "/");
+ uriPath.append(srcDevice.getUserId());
+
+ HashMap<String, Object> payloadData = mCbor
+ .parsePayloadFromCbor(request.getPayload(), HashMap.class);
+
+ String di = payloadData.get(Constants.REQ_DEVICE_ID).toString();
+
+ HashMap<String, Object> requestPayload = new HashMap<>();
- IRequest requestToAS = MessageBuilder.createRequest(RequestMethod.GET,
- uriPath.toString(), uriQuery.toString());
+ requestPayload.put(Constants.REQ_DEVICE_LIST, Arrays.asList(di));
+ IRequest requestToAS = MessageBuilder.createRequest(RequestMethod.POST,
+ uriPath.toString(), null, ContentFormat.APPLICATION_CBOR,
+ mCbor.encodingPayloadToCbor(requestPayload));
mASServer.sendRequest(requestToAS,
new AccountReceiveHandler(request, srcDevice));
* //
* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
*/
-package org.iotivity.cloud.ciserver.resources.proxy;
+package org.iotivity.cloud.ciserver.resources.proxy.rd;
-import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
+import java.util.List;
import org.iotivity.cloud.base.connector.ConnectorPool;
-import org.iotivity.cloud.base.device.CoapDevice;
import org.iotivity.cloud.base.device.Device;
import org.iotivity.cloud.base.device.IRequestChannel;
import org.iotivity.cloud.base.device.IResponseEventHandler;
import org.iotivity.cloud.base.exception.ClientException;
+import org.iotivity.cloud.base.exception.ClientException.BadResponseException;
import org.iotivity.cloud.base.exception.ServerException;
+import org.iotivity.cloud.base.exception.ServerException.UnAuthorizedException;
import org.iotivity.cloud.base.protocols.IRequest;
import org.iotivity.cloud.base.protocols.IResponse;
import org.iotivity.cloud.base.protocols.MessageBuilder;
import org.iotivity.cloud.util.Cbor;
public class ResourceFind extends Resource {
- IRequestChannel mASServer = null;
+ IRequestChannel mASServer = null;
+ private Cbor<HashMap<String, Object>> mCbor = new Cbor<>();
public ResourceFind() {
super(Arrays.asList(Constants.PREFIX_OIC, Constants.WELL_KNOWN_URI));
@Override
public void onResponseReceived(IResponse response)
throws ClientException {
-
switch (response.getStatus()) {
- case VALID:
- mRDServer.sendRequest(mRequest, mSrcDevice);
- break;
-
case CONTENT:
StringBuilder additionalQuery = new StringBuilder();
- Cbor<HashMap<String, ArrayList<String>>> responsePayload = new Cbor<>();
-
- ArrayList<String> deviceList = responsePayload
+ HashMap<String, Object> payloadData = mCbor
.parsePayloadFromCbor(response.getPayload(),
- HashMap.class)
- .get("devices");
-
- int index = deviceList.size();
-
- for (String deviceId : deviceList) {
- if (!deviceId.equals(mSrcDevice.getDeviceId())) {
- additionalQuery.append("di=");
- additionalQuery.append(deviceId);
- if (--index > 0) {
- additionalQuery.append("&");
+ HashMap.class);
+ List<String> deviceList = (List<String>) payloadData
+ .get(Constants.REQ_DEVICE_LIST);
+ if (deviceList != null) {
+ int index = deviceList.size();
+ if (mRequest.getUriQuery() == null) {
+ for (String device : deviceList) {
+ if (!device.equals(mSrcDevice.getDeviceId())) {
+ additionalQuery
+ .append(Constants.REQ_DEVICE_ID
+ + "=" + device);
+ if (--index > 0) {
+ additionalQuery.append(";");
+ }
+ }
+ }
+ String uriQuery = (mRequest.getUriQuery() == null
+ ? "" : mRequest.getUriQuery()) + ";"
+ + additionalQuery.toString();
+ mRequest = MessageBuilder.modifyRequest(mRequest,
+ null, uriQuery, null, null);
+ } else {
+ List<String> originDeviceList = mRequest
+ .getUriQueryMap()
+ .get(Constants.REQ_DEVICE_ID);
+ if (originDeviceList == null) {
+ throw new UnAuthorizedException(
+ "device is not include in group");
+ }
+ for (String device : originDeviceList) {
+ if (!deviceList.contains(device)) {
+ throw new UnAuthorizedException(device
+ + " device is not include in group");
+ }
}
}
- }
- String uriQuery = (mRequest.getUriQuery() == null ? ""
- : mRequest.getUriQuery() + "&")
- + additionalQuery.toString();
- IRequest requestToAS = MessageBuilder.modifyRequest(
- mRequest, null, uriQuery, null, null);
-
- mRDServer.sendRequest(requestToAS, mSrcDevice);
+ mRDServer.sendRequest(mRequest, mSrcDevice);
+ } else
+ throw new UnAuthorizedException(
+ "There is not device in group");
break;
-
default:
- mSrcDevice.sendResponse(MessageBuilder
- .createResponse(mRequest, response.getStatus()));
+ throw new BadResponseException(
+ response.getStatus().toString()
+ + " response type is not supported");
}
}
}
@Override
public void onDefaultRequestReceived(Device srcDevice, IRequest request)
throws ServerException {
- // Token exchange is done by CoapClient
- CoapDevice coapDevice = (CoapDevice) srcDevice;
StringBuffer uriQuery = new StringBuffer();
- uriQuery.append(Constants.SEARCH_ACCESS_TOKEN + "=");
- uriQuery.append(coapDevice.getAccessToken());
-
- if (request.getUriQueryMap().get("di") != null) {
- for (String di : request.getUriQueryMap().get("di")) {
- uriQuery.append("&");
- uriQuery.append("di" + "=");
- uriQuery.append(di);
- }
- }
+ uriQuery.append(Constants.REQ_MEMBER_ID + "=" + srcDevice.getUserId());
StringBuffer uriPath = new StringBuffer();
uriPath.append(Constants.PREFIX_WELL_KNOWN + "/");
uriPath.append(Constants.PREFIX_OCF + "/");
- uriPath.append(Constants.ACCOUNT_URI + "/");
- uriPath.append(Constants.DEVICE_URI);
+ uriPath.append(Constants.ACL_URI + "/");
+ uriPath.append(Constants.GROUP_URI + "/");
+ uriPath.append(srcDevice.getUserId());
IRequest requestToAS = MessageBuilder.createRequest(RequestMethod.GET,
uriPath.toString(), uriQuery.toString());
mASServer.sendRequest(requestToAS,
new AccountReceiveHandler(request, srcDevice));
}
-}
+}
\ No newline at end of file
--- /dev/null
+/*
+ * //******************************************************************
+ * //
+ * // 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.ciserver.resources.proxy.rd;
+
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+
+import org.iotivity.cloud.base.connector.ConnectorPool;
+import org.iotivity.cloud.base.device.Device;
+import org.iotivity.cloud.base.device.IRequestChannel;
+import org.iotivity.cloud.base.device.IResponseEventHandler;
+import org.iotivity.cloud.base.exception.ClientException;
+import org.iotivity.cloud.base.exception.ClientException.BadResponseException;
+import org.iotivity.cloud.base.exception.ServerException;
+import org.iotivity.cloud.base.exception.ServerException.UnAuthorizedException;
+import org.iotivity.cloud.base.protocols.IRequest;
+import org.iotivity.cloud.base.protocols.IResponse;
+import org.iotivity.cloud.base.protocols.MessageBuilder;
+import org.iotivity.cloud.base.protocols.enums.RequestMethod;
+import org.iotivity.cloud.base.resource.Resource;
+import org.iotivity.cloud.ciserver.Constants;
+import org.iotivity.cloud.util.Cbor;
+
+public class ResourcePresence extends Resource {
+ IRequestChannel mASServer = null;
+ private Cbor<HashMap<String, Object>> mCbor = new Cbor<>();
+
+ public ResourcePresence() {
+ super(Arrays.asList(Constants.PREFIX_OIC, Constants.RES_PRESENCE_URI));
+
+ mASServer = ConnectorPool.getConnection("account");
+ }
+
+ class AccountReceiveHandler implements IResponseEventHandler {
+
+ IRequestChannel mRDServer = null;
+ private Device mSrcDevice;
+ private IRequest mRequest;
+
+ public AccountReceiveHandler(IRequest request, Device srcDevice) {
+ mRDServer = ConnectorPool.getConnection("rd");
+ mSrcDevice = srcDevice;
+ mRequest = request;
+ }
+
+ @Override
+ public void onResponseReceived(IResponse response)
+ throws ClientException {
+ switch (response.getStatus()) {
+ case CONTENT:
+ StringBuilder additionalQuery = new StringBuilder();
+
+ HashMap<String, Object> payloadData = mCbor
+ .parsePayloadFromCbor(response.getPayload(),
+ HashMap.class);
+ List<String> deviceList = (List<String>) payloadData
+ .get(Constants.REQ_DEVICE_LIST);
+ if (deviceList != null) {
+ int index = deviceList.size();
+ if (mRequest.getUriQuery() == null) {
+ for (String device : deviceList) {
+ if (!device.equals(mSrcDevice.getDeviceId())) {
+ additionalQuery
+ .append(Constants.REQ_DEVICE_ID
+ + "=" + device);
+ if (--index > 0) {
+ additionalQuery.append(";");
+ }
+ }
+ }
+ String uriQuery = (mRequest.getUriQuery() == null
+ ? "" : mRequest.getUriQuery()) + ";"
+ + additionalQuery.toString();
+ mRequest = MessageBuilder.modifyRequest(mRequest,
+ null, uriQuery, null, null);
+ } else {
+ List<String> originDeviceList = mRequest
+ .getUriQueryMap()
+ .get(Constants.REQ_DEVICE_ID);
+ if (originDeviceList == null) {
+ throw new UnAuthorizedException(
+ "device is not include in group");
+ }
+ for (String device : originDeviceList) {
+ if (!deviceList.contains(device)) {
+ throw new UnAuthorizedException(device
+ + " device is not include in group");
+ }
+ }
+ }
+ mRDServer.sendRequest(mRequest, mSrcDevice);
+ } else
+ throw new UnAuthorizedException(
+ "There is not device in group");
+ break;
+ default:
+ throw new BadResponseException(
+ response.getStatus().toString()
+ + " response type is not supported");
+ }
+ }
+ }
+
+ @Override
+ public void onDefaultRequestReceived(Device srcDevice, IRequest request)
+ throws ServerException {
+ StringBuffer uriQuery = new StringBuffer();
+ uriQuery.append(Constants.REQ_MEMBER_ID + "=" + srcDevice.getUserId());
+
+ StringBuffer uriPath = new StringBuffer();
+ uriPath.append(Constants.PREFIX_WELL_KNOWN + "/");
+ uriPath.append(Constants.PREFIX_OCF + "/");
+ uriPath.append(Constants.ACL_URI + "/");
+ uriPath.append(Constants.GROUP_URI + "/");
+ uriPath.append(srcDevice.getUserId());
+
+ IRequest requestToAS = MessageBuilder.createRequest(RequestMethod.GET,
+ uriPath.toString(), uriQuery.toString());
+
+ mASServer.sendRequest(requestToAS,
+ new AccountReceiveHandler(request, srcDevice));
+ }
+}
\ No newline at end of file
private TypeCastingManager<PublishTags> mPublishTagsTypeManager = new TypeCastingManager<>();
private TypeCastingManager<PublishLinks> mPublishLinksTypeManager = new TypeCastingManager<>();
private InsManager mInsManager = new InsManager();
- private String notiDeviceId = null;
- private ArrayList<ResPresencePayload> notiPayloadList = new ArrayList<ResPresencePayload>();
+ private String mNotiDeviceId = null;
+ private ArrayList<ResPresencePayload> mNotiPayloadList = new ArrayList<ResPresencePayload>();
public ResourceDirectoryResource() {
super(Arrays.asList(Constants.PREFIX_OIC, Constants.RD_URI));
srcDevice.sendResponse(response);
- ResPresenceManager.getInstance().notifyToObservers(notiDeviceId,
- notiPayloadList);
+ ResPresenceManager.getInstance().notifyToObservers(mNotiDeviceId,
+ mNotiPayloadList);
}
PublishPayload pubPayload = parsingPublishPayload(
request.getPayload());
- notiDeviceId = pubPayload.getTags().getDi();
+ mNotiDeviceId = pubPayload.getTags().getDi();
PublishPayload copyPubPayload = pubPayload.copy();
ArrayList<HashMap<Object, Object>> storeResList = creatDBStoreResource(
changeResourceUri(copyPubPayload));
- notiPayloadList = DBManager.getInstance()
+ mNotiPayloadList = DBManager.getInstance()
.registerResource(storeResList);
encodedPayload = createPublishResponse(pubPayload);
"di property is not include");
} else {
String di = diList.get(0);
- notiDeviceId = di;
+ mNotiDeviceId = di;
if (insList == null) {
- notiPayloadList = DBManager.getInstance()
+ mNotiPayloadList = DBManager.getInstance()
.deleteResourceAboutDi(di);
} else {
String ins = insList.get(0);
- notiPayloadList = DBManager.getInstance()
+ mNotiPayloadList = DBManager.getInstance()
.deleteResourceAboutDiAandIns(di, ins);
}
}
public static final String TOKEN_REFRESH_URI = "tokenrefresh";
+ /* resource url for acl */
+ public static final String ACL_URI = "acl";
+
+ public static final String GROUP_URI = "group";
+
+ public static final String VERIFY_URI = "verify";
+
+ public static final String ID_URI = "id";
+
/* resource uri to publish, update, delete resource info */
public static final String RD_URI = "rd";
public static final String MQ_BROKER_URI = "ps";
public static final String MQ_BROKER_RT = "oic.wk.ps";
- /* file path for tls communication - Modify filePath to yours */
+ /* certificate file path - Modify this to yours */
public static final String ROOT_CERT_FILE = "./rootca.crt";
public static final String CLOUD_CERT_FILE = "./iotivitycloud.crt";
public static final String CLOUD_KEY_FILE = "./iotivitycloud.key";
+ /* cloud uuid */
+ public static final String CLOUD_UUID = "2a6085d1-815d-4277-baba-4e4e4df91308";
+
}
deviceId.insert(13, '-');
deviceId.insert(18, '-');
deviceId.insert(23, '-');
- Device device = new CoapDevice(ctx, deviceId.toString(), null);
+ Device device = new CoapDevice(ctx, deviceId.toString(), null,
+ null);
ctx.channel().attr(keyDevice).set(device);
device.onConnected();
import io.netty.channel.ChannelHandlerContext;
public class CoapDevice extends Device {
- private CoapClient mCoapClient = null;
- private String mDeviceId;
- private String mAccessToken = null;
- private Date mIssuedTime = null;
- private int mExpiredPolicy = 0;
-
- public CoapDevice(ChannelHandlerContext ctx, String deviceId,
- String accessToken) {
+ private CoapClient mCoapClient = null;
+ private String mUserId = null;
+ private String mDeviceId = null;
+ private String mAccessToken = null;
+ private Date mIssuedTime = null;
+ private int mExpiredPolicy = 0;
+
+ private static final int INFINITE_TIME = -1;
+
+ public CoapDevice(ChannelHandlerContext ctx, String did, String uid,
+ String accesstoken) {
super(ctx);
- mDeviceId = deviceId;
- mAccessToken = accessToken;
+ mDeviceId = did;
+ mUserId = uid;
+ mAccessToken = accesstoken;
}
@Override
return mDeviceId;
}
+ @Override
+ public String getUserId() {
+ return mUserId;
+ }
+
+ @Override
public String getAccessToken() {
return mAccessToken;
}
this.mExpiredPolicy = expiredPolicy;
}
+ public void setUerId(String userId) {
+ this.mUserId = userId;
+ }
+
+ public void setAccessToken(String accessToken) {
+ this.mAccessToken = accessToken;
+ }
+
// This is called by cloud resource model
@Override
public void sendResponse(IResponse response) {
public boolean isExpiredTime() {
+ if (mExpiredPolicy == INFINITE_TIME) {
+ return false;
+ }
+
Date currentTime = new Date();
long difference = currentTime.getTime() - mIssuedTime.getTime();
long remainTime = mExpiredPolicy - difference / 1000;
@Override
public void onDisconnected() {
}
+
}
public abstract void onDisconnected();
public abstract String getDeviceId();
+
+ public abstract String getUserId();
+
+ public abstract String getAccessToken();
}
// TODO Auto-generated method stub
return null;
}
+
+ @Override
+ public String getUserId() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public String getAccessToken() {
+ // TODO Auto-generated method stub
+ return null;
+ }
}
return;
}
- String[] querySegments = query.split("&");
+ String[] querySegments = query.split(";");
for (String querySegment : querySegments) {
uri_query.add(querySegment.getBytes(StandardCharsets.UTF_8));
}
throw new NotFoundException("No handlers registered");
}
- public boolean checkQueryException(String property, IRequest request) {
- return checkQueryException(Arrays.asList(property), request);
+ public boolean checkQueryException(String property,
+ HashMap<String, List<String>> queryData) {
+ return checkQueryException(Arrays.asList(property), queryData);
}
public boolean checkQueryException(List<String> propertyList,
- IRequest request) {
- HashMap<String, List<String>> queryData = request.getUriQueryMap();
+ HashMap<String, List<String>> queryData) {
+
if (queryData == null)
throw new BadRequestException("queryData is null");
return true;
}
- public boolean checkPayloadException(String property, IRequest request) {
- return checkPayloadException(Arrays.asList(property), request);
+ public boolean checkPayloadException(String property,
+ HashMap<String, Object> payloadData) {
+ return checkPayloadException(Arrays.asList(property), payloadData);
}
public boolean checkPayloadException(List<String> propertyList,
- IRequest request) {
- Cbor<HashMap<String, Object>> cbor = new Cbor<>();
- HashMap<String, Object> payloadData = cbor
- .parsePayloadFromCbor(request.getPayload(), HashMap.class);
+ HashMap<String, Object> payloadData) {
+
if (payloadData == null)
throw new BadRequestException("payloadData is null");
throws CertificateException, SSLException, InterruptedException {
try {
- Log.i("[CoapServer]startServer with tlsMode! mode= " + tlsMode);
+ if (tlsMode)
+ Log.i("Server starts with TLS!");
if (tlsMode == true) {