1. When a device is deleted, the device ID in each group is removed.
2. The device ID is added only in the resource publish case
3. footnote added
Change-Id: Ifdff14f0f3132a753b2a05cd4e1691657a8b3560
Signed-off-by: yeonghun.nam <yeonghun.nam@samsung.com>
Reviewed-on: https://gerrit.iotivity.org/gerrit/11137
Reviewed-by: jung seungho <shonest.jung@samsung.com>
Signed-off-by: Jee Hyeok Kim <jihyeok13.kim@samsung.com>
Signed-off-by: yeonghun.nam <yeonghun.nam@samsung.com>
Signed-off-by: Jee Hyeok Kim <jihyeok13.kim@samsung.com>
Reviewed-on: https://gerrit.iotivity.org/gerrit/11979
return db;
}
+ /**
+ * API for inserting a record into DB table. the record will not be inserted
+ * if duplicated one.
+ *
+ * @param tableName
+ * table name to be inserted
+ * @param doc
+ * document to be inserted
+ */
public Boolean insertRecord(String tableName, Document doc) {
if (tableName == null || doc == null)
return true;
}
+ /**
+ * API for inserting a record into DB table. the record will be replaced if
+ * duplicated one.
+ *
+ * @param tableName
+ * table name to be inserted
+ * @param filter
+ * document filter
+ * @param doc
+ * document to be inserted
+ * @return returns true if the record is inserted and replaced successfully,
+ * or returns false
+ */
public Boolean insertAndReplaceRecord(String tableName, Document filter,
Document doc) {
return true;
}
+ /**
+ * API for updating a record into DB table.
+ *
+ * @param tableName
+ * table name to be updated
+ * @param filter
+ * document filter
+ * @param record
+ * record to be updated
+ * @return returns true if the record is updated successfully, or returns
+ * false
+ */
public Boolean updateRecord(String tableName, Document filter,
Document record) {
return true;
}
+ /**
+ * API for deleting records from DB table.
+ *
+ * @param tableName
+ * table name for the record to be deleted
+ * @param record
+ * record filter to be deleted
+ * @return returns true if the record is deleted successfully, or returns
+ * false
+ */
public Boolean deleteRecord(String tableName, Document record) {
if (tableName == null || record == null)
return true;
}
+ /**
+ * API for selecting records from DB table.
+ *
+ * @param tableName
+ * table name for the record to be selected
+ * @param doc
+ * document filter to be selected
+ * @return record list according to the filter document
+ */
public ArrayList<HashMap<String, Object>> selectRecord(String tableName,
Document doc) {
public abstract interface OAuthProvider {
/**
- * API for requesting access token
+ * API to request access token
*
* @param authCode
* authorization code
- * @param authServerUrl
- * authorization server url
- * @return access token and error message if error occur
+ * @param options
+ * option field of region authserver url, apiserver url
+ * @return token information or error message if error occurs
*/
public abstract TokenTable requestAccessTokenInfo(String authCode,
Object options);
+ /**
+ * API to request refresh token
+ *
+ * @param refreshToken
+ * Refresh token used to refresh the access token in cloud before
+ * getting expired
+ * @return token information or error message if error occurs
+ */
public abstract TokenTable requestRefreshTokenInfo(String refreshToken);
/**
- * API for getting user's information
+ * API to get user information
*
* @param accessToken
* access token
- * @param apiServerUrl
- * api server url
- * @return access token and error message if error occur
+ * @param options
+ * option field of region authserver url, apiserver url
+ * @return user information or error message if error occurs
*/
public abstract UserTable requestGetUserInfo(String accessToken,
Object options);
private Class<?> authProviderClass = null;
private Object authProviderObj = null;
+ /**
+ * API to get token table which includes access token, refresh token, and
+ * token expiration time
+ *
+ * @param authCode:
+ * authorization code
+ * @param options:
+ * authserver url and apiserver url option
+ * @return : token table which includes access token, refresh token, and
+ * token expiration time
+ */
public TokenTable requestAccessTokenInfo(String authCode, Object options) {
-
TokenTable tokenInfo = null;
-
try {
Method method = authProviderClass.getMethod(
"requestAccessTokenInfo",
return tokenInfo;
}
+ /**
+ * API to get renewed token table which includes new access token, new
+ * refresh token, and new token expiration time
+ *
+ * @param refreshToken:
+ * Refresh token used to refresh the access token in cloud before
+ * getting expired
+ * @return: token table which includes new access token, new refresh token,
+ * and new token expiration time
+ */
public TokenTable requestRefreshTokenInfo(String refreshToken) {
TokenTable tokenInfo = null;
return tokenInfo;
}
+ /**
+ * API to get user information table
+ *
+ * @param accessToken:
+ * Access token used for communication with cloud after account
+ * creation
+ * @param options:
+ * authserver url and apiserver url option
+ * @return: user information table
+ */
public UserTable requestGetUserInfo(String accessToken, Object options) {
UserTable userInfo = null;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
-import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
private TypeCastingManager<UserTable> mUserTableCastingManager = new TypeCastingManager<>();
private TypeCastingManager<TokenTable> mTokenTableCastingManager = new TypeCastingManager<>();
+ /**
+ * API to return a sign-up response payload
+ *
+ * @param did
+ * Device id registered under user account
+ * @param authCode
+ * Unique identifier of the resource which is obtained from an
+ * auth provider or a single sign-on (SSO) client
+ * @param authProvider
+ * Provider name user for authentication (e.g., "Github")
+ * @param options
+ * Optional field (e.g., region authserver url, apiserver url)
+ *
+ * @return Sign-up response payload
+ */
+
public HashMap<String, Object> signUp(String did, String authCode,
String authProvider, Object options) {
-
boolean res = false;
+
+ // check auth provider name not to be case-sensitive
authProvider = checkAuthProviderName(authProvider);
res = loadAuthProviderLibrary(authProvider);
// check uuid
userUuid = findUuid(userInfo.getUserid(), authProvider);
+ // store token information and user information to the DB
+ // private group creation and store group information to the DB
storeUserTokenInfo(userUuid, userInfo, tokenInfo, did);
// make response
return response;
}
+ /**
+ * API to return a sign-in or sign-out response payload
+ *
+ * @param uuid
+ * User id which is provided by Sign-up process
+ * @param did
+ * Device id registered under user account
+ * @param accessToken
+ * Access token used for communication with cloud
+ * @return Sign-in or sign-out response payload
+ */
+ public HashMap<String, Object> signInOut(String uuid, String did,
+ String accessToken) {
+
+ // find token information corresponding to the 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);
+
+ // token verification to check if the accesstoken is expired
+ if (verifyToken(tokenInfo, accessToken)) {
+ long remainedSeconds = getRemainedSeconds(
+ tokenInfo.getExpiredtime(), tokenInfo.getIssuedtime());
+
+ return makeSignInResponse(remainedSeconds);
+ } else {
+ throw new UnAuthorizedException("AccessToken is unauthorized");
+ }
+ }
+
+ /**
+ * API to return a token refresh response payload
+ *
+ * @param uuid
+ * user id which is provided by Sign-up process
+ * @param did
+ * device id registered under user account
+ * @param grantType
+ * token type to be granted
+ * @param refreshToken
+ * Refresh token used to refresh the access token in cloud before
+ * getting expired
+ * @return Token refresh response payload
+ */
+
+ 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);
+ condition.put(Constants.KEYFIELD_DID, did);
+
+ 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);
+ String provider = oldTokenInfo.getProvider();
+
+ if (!checkRefreshTokenInDB(oldTokenInfo, refreshToken)) {
+ throw new NotFoundException("refresh token is not correct");
+ }
+ // call 3rd party refresh token method
+ TokenTable newTokenInfo = requestRefreshToken(refreshToken, provider);
+
+ // 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 void storeUserTokenInfo(String userUuid, UserTable userInfo,
TokenTable tokenInfo, String did) {
// store db
+ // the user table is created
if (userUuid == null) {
userUuid = generateUuid();
userInfo.setUuid(userUuid);
GroupResource.getInstance().createGroup(userInfo.getUuid(),
Constants.REQ_GTYPE_PRIVATE);
}
- // add my device to private group
- GroupResource.getInstance().getGroup(userUuid)
- .addDevice(new HashSet<String>(Arrays.asList(did)));
tokenInfo.setUuid(userUuid);
AccountDBManager.getInstance().insertAndReplaceRecord(
Constants.TOKEN_TABLE, castTokenTableToMap(tokenInfo));
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) {
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);
- condition.put(Constants.KEYFIELD_DID, did);
-
- 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);
- String provider = oldTokenInfo.getProvider();
-
- if (!checkRefreshTokenInDB(oldTokenInfo, refreshToken)) {
- throw new NotFoundException("refresh token is not correct");
- }
- // call 3rd party refresh token method
- TokenTable newTokenInfo = requestRefreshToken(refreshToken, provider);
-
- // 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<>();
HashSet<String> diSet = new HashSet<String>();
diSet.add(di);
- // the group that gid is uid is my group.
- GroupResource.getInstance().removeGroupDevice(uid, diSet);
+ // token table search criteria
+ HashMap<String, Object> condition = new HashMap<>();
+ condition.put(Constants.KEYFIELD_UUID, uid);
+ condition.put(Constants.KEYFIELD_DID, di);
+
+ // delete Token information from the DB
+ AccountDBManager.getInstance().deleteRecord(Constants.TOKEN_TABLE,
+ condition);
+ // delete device ID from all groups in the DB
+ GroupResource.getInstance().removeGroupDeviceinEveryGroup(uid, di);
+
+ // TODO remove device record from the ACL table
}
+
}
switch (request.getMethod()) {
case POST:
+ // make sign-up response message
response = handlePostSignUp(request);
break;
throw new BadRequestException(
request.getMethod() + " request type is not support");
}
-
+ // send sign-up response to the source device
srcDevice.sendResponse(response);
}
HashMap<String, Object> responsePayload = null;
+ // payload verification if the mandatory properties are
+ // included in the payload
if (checkPayloadException(Arrays.asList(Constants.REQ_DEVICE_ID,
Constants.REQ_AUTH_CODE, Constants.REQ_AUTH_PROVIDER),
payloadData)) {
import org.iotivity.cloud.base.resource.Resource;
import org.iotivity.cloud.util.Cbor;
+/**
+ *
+ * This class provides a set of APIs to handle sign-in/sign-out requests
+ *
+ */
+
public class SessionResource extends Resource {
private Cbor<HashMap<String, Object>> mCbor = new Cbor<>();
throw new BadRequestException(
request.getMethod() + " request type is not support");
}
-
+ // send sign-up response to the source device
srcDevice.sendResponse(response);
}
.toString();
String accessToken = payloadData.get(Constants.REQ_ACCESS_TOKEN)
.toString();
+
+ // identify if the request is sign-in or sign-out
boolean signinRequest = (boolean) payloadData
.get(Constants.REQ_LOGIN);
if (signinRequest) {
+ // sign-in response payload
responsePayload = mAsManager.signInOut(uuid, deviceId,
accessToken);
} else {
+ // sign-out response
mAsManager.signInOut(uuid, deviceId, accessToken);
return MessageBuilder.createResponse(request,
ResponseStatus.CHANGED);
}
}
+ // sign-in response
return MessageBuilder.createResponse(request, ResponseStatus.CHANGED,
ContentFormat.APPLICATION_CBOR,
mCbor.encodingPayloadToCbor(responsePayload));
import org.iotivity.cloud.base.resource.Resource;
import org.iotivity.cloud.util.Cbor;
+/**
+ *
+ * This class provides a set of APIs to handle token refresh requests
+ *
+ */
+
public class TokenRefreshResource extends Resource {
private Cbor<HashMap<String, Object>> mCbor = new Cbor<>();
switch (request.getMethod()) {
case POST:
+ // make token refresh response message
response = handlePostRefreshToken(request);
break;
throw new BadRequestException(
request.getMethod() + " request type is not support");
}
-
+ // send sign-up response to the source device
srcDevice.sendResponse(response);
}
HashMap<String, Object> responsePayload = null;
+ // check if the payload has mandatory properties
if (checkPayloadException(
Arrays.asList(Constants.REQ_UUID_ID, Constants.REQ_DEVICE_ID,
Constants.REQ_REFRESH_TOKEN, Constants.REQ_GRANT_TYPE),
responsePayload = mAsManager.refreshToken(uuid, deviceId, grantType,
refreshToken);
}
-
+ // return token refresh response message
return MessageBuilder.createResponse(request, ResponseStatus.CHANGED,
ContentFormat.APPLICATION_CBOR,
mCbor.encodingPayloadToCbor(responsePayload));
import org.iotivity.cloud.base.protocols.enums.ResponseStatus;
import org.iotivity.cloud.util.Cbor;
+/**
+ *
+ * This class provides a set of APIs to handle group requests
+ *
+ */
+
public class Group {
private Cbor<HashMap<String, Object>> mCbor = new Cbor<>();
private HashMap<String, GroupSubscriber> mSubscribers = new HashMap<>();
+ /**
+ *
+ * API to add the member user id to the group table in the db
+ *
+ * @param uuid
+ * User id list which are provided by Sign-up process
+ */
public void addMember(HashSet<String> uuid) {
GroupTable groupTable = getGroupTable();
notifyToSubscriber(getResponsePayload(true));
}
+ /**
+ * API to add the device id to the group table in the db
+ *
+ * @param di
+ * device id list to be stored
+ */
public void addDevice(HashSet<String> di) {
GroupTable groupTable = getGroupTable();
notifyToSubscriber(getResponsePayload(true));
}
+ /**
+ * API to remove member user id list from the group table in the db
+ *
+ * @param uuid
+ * User id list to be removed from the group table
+ */
public void removeMember(HashSet<String> uuid) {
GroupTable groupTable = getGroupTable();
while (mid.hasNext()) {
removeSubscriber(mid.next());
}
-
}
-
}
+ /**
+ * API to remove device id list from the group table in the db
+ *
+ * @param di
+ * device id list to be removed from the group table
+ */
public void removeDevice(HashSet<String> di) {
GroupTable groupTable = getGroupTable();
notifyToSubscriber(getResponsePayload(true));
}
+ /**
+ * API to return the group information payload
+ *
+ * @param mid
+ * member id to verify if the id exists in the group table
+ * @return group information payload
+ */
public HashMap<String, Object> getInfo(String mid) {
verifyGroupTableMid(mid);
return getResponsePayload(true);
}
+ public boolean checkDeviceExistance(String di) {
+ return verifyGroupTableDi(di);
+ }
+
+ /**
+ * API to add group subscriber
+ *
+ * @param mid
+ * member id to verify if the id exists in the group table
+ * @param subscriber
+ * subscriber device
+ * @param request
+ * request message
+ * @return group information payload
+ */
public HashMap<String, Object> addSubscriber(String mid, Device subscriber,
IRequest request) {
+ // Check if the user has privilege to observe
verifyGroupTableMid(mid);
GroupSubscriber newSubscriber = new GroupSubscriber(subscriber,
request.getUriQueryMap().get(Constants.REQ_MEMBER).get(0));
}
+ /**
+ * API to unsubscribe group information
+ *
+ * @param mid
+ * user Id to unscribe group information
+ * @return group information payload
+ */
public HashMap<String, Object> removeSubscriber(String mid) {
HashMap<String, Object> responsePayload = getResponsePayload(true);
if (groupTable.getMidlist() == null) {
throw new BadRequestException("midList is invalid in Group");
}
- HashSet<String> midListSet = new HashSet<String>(
+ HashSet<String> midListSet = new HashSet<>(
(Collection<? extends String>) groupTable.getMidlist());
if (!midListSet.contains(mid)) {
}
}
+ private boolean verifyGroupTableDi(String di) {
+
+ GroupTable groupTable = getGroupTable();
+
+ if (groupTable.getDilist() == null) {
+ return false;
+ }
+
+ HashSet<String> diListSet = new HashSet<>(
+ (Collection<? extends String>) groupTable.getDilist());
+
+ if (!diListSet.contains(di)) {
+ return false;
+ }
+ return true;
+ }
+
private void notifyToSubscriber(
HashMap<String, Object> notifiyBtyePayloadData) {
synchronized (mSubscribers) {
private HashSet<String> addGroupListSet(Object object,
HashSet<String> addList) {
- HashSet<String> groupSet = new HashSet<String>(
+ HashSet<String> groupSet = new HashSet<>(
(Collection<? extends String>) object);
groupSet.addAll(addList);
private HashSet<String> removeGroupListSet(Object object,
HashSet<String> removeList) {
- HashSet<String> groupSet = new HashSet<String>(
+ HashSet<String> groupSet = new HashSet<>(
(Collection<? extends String>) object);
groupSet.removeAll(removeList);
import org.iotivity.cloud.base.exception.ServerException.InternalServerErrorException;
import org.iotivity.cloud.base.protocols.IRequest;
+/**
+ *
+ * This class provides a set of APIs to manage group
+ *
+ */
+
public class GroupManager {
public HashMap<String, Group> mGroups = new HashMap<>();
private TypeCastingManager<GroupTable> mTypeGroup = new TypeCastingManager<GroupTable>();
+ /**
+ * API to create a public or private group
+ *
+ * @param uuid
+ * User id which provided by Sign-up process
+ * @param gtype
+ * group type (ex: "Private" or "Public)
+ * @return response payload which includes the created group ID
+ */
public HashMap<String, Object> createGroup(String uuid, String gtype) {
HashMap<String, Object> responsePayload = new HashMap<>();
String gid = null;
switch (gtype) {
+ // if the group type is "Private", group id becomes the name of user
+ // id itself
case Constants.REQ_GTYPE_PRIVATE:
gid = uuid;
break;
+ // if the group type is "Public", group id is randomly generated
case Constants.REQ_GTYPE_PUBLIC:
gid = UUID.randomUUID().toString();
break;
new HashSet<String>(Arrays.asList(uuid)), null, uuid, null,
gtype);
+ // record newly generated group information to the group table
AccountDBManager.getInstance().insertRecord(Constants.GROUP_TABLE,
mTypeGroup.convertObjectToMap(newGroupTable));
return responsePayload;
}
+ /**
+ * API to delete a group
+ *
+ * @param gmid
+ * An unique identifier of member who must be a group master.
+ * Group master can be user or resource client.
+ * @param gid
+ * An unique identifier of the group created under user entity
+ * who requested for group creation.
+ */
public void deleteGroup(String gmid, String gid) {
HashMap<String, Object> condition = new HashMap<>();
mGroups.remove(gid);
}
+ /**
+ * API to delete a device ID from all groups
+ *
+ * @param uid
+ * User id which provided by Sign-up process
+ * @param di
+ * device id to be deleted from all groups
+ */
+
+ public void removeGroupDeviceinEveryGroup(String uid, String di) {
+ // check if the device is the resource server (i.e., device ID exists in
+ // the private group table
+ if (GroupResource.getInstance().verifyDeviceInGroup(uid, di)) {
+ // token table search criteria
+ HashMap<String, Object> condition = new HashMap<>();
+ condition.put(Constants.REQ_DEVICE_ID_LIST, di);
+ // read group record which contains device ID in each group
+ ArrayList<HashMap<String, Object>> groupRecord = AccountDBManager
+ .getInstance()
+ .selectRecord(Constants.GROUP_TABLE, condition);
+ // update group record to the DB
+ for (HashMap<String, Object> record : groupRecord) {
+ String gid = (String) record.get(Constants.KEYFIELD_GID);
+ HashSet<String> diSet = new HashSet<>();
+ diSet.add(di);
+ GroupResource.getInstance().removeGroupDevice(gid, diSet);
+ }
+ }
+ }
+
+ /**
+ * API to get group list where the each group has uuid as a member
+ *
+ * @param uuid
+ * User id which is provided by Sign-up process
+ * @return response payload which has the list of groups where each group
+ * has uuid as a member id
+ *
+ */
public HashMap<String, Object> getGroupList(String uuid) {
HashMap<String, Object> responsePayload = new HashMap<>();
throw new BadRequestException("midList is invalid in Group");
}
- HashSet<String> midListSet = new HashSet<String>(
+ HashSet<String> midListSet = new HashSet<>(
(Collection<? extends String>) getGroupTable.getMidlist());
if (midListSet.contains(uuid) && getGroupTable.getGtype()
return responsePayload;
}
+ /**
+ * API to add the member user id list to the group table in the db
+ *
+ * @param gid
+ * group id
+ * @param midlist
+ * User id list to be added to the group
+ */
public void addGroupMember(String gid, HashSet<String> midlist) {
getGroup(gid).addMember(midlist);
}
+ /**
+ * API to add the device id list to the group table in the db
+ *
+ * @param gid
+ * group id
+ * @param dilist
+ * device id list to be added to the group
+ */
public void addGroupDevice(String gid, HashSet<String> dilist) {
getGroup(gid).addDevice(dilist);
}
+ /**
+ * API to remove the member user id list from the group table in the db
+ *
+ * @param gid
+ * group id
+ * @param midlist
+ * member user id list to be removed from the group
+ */
public void removeGroupMember(String gid, HashSet<String> midlist) {
getGroup(gid).removeMember(midlist);
}
+ /**
+ * API to remove the device id list from the group table in the db
+ *
+ * @param gid
+ * group id
+ * @param dilist
+ * device id list to be removed from the group
+ */
public void removeGroupDevice(String gid, HashSet<String> dilist) {
getGroup(gid).removeDevice(dilist);
}
+ /**
+ * API to get the group information from the db
+ *
+ * @param gid
+ * group id
+ * @param mid
+ * An unique Identifier of the member(query requester) who is
+ * expected as a member of a group
+ * @return group information payload
+ */
public HashMap<String, Object> getGroupInfo(String gid, String mid) {
return getGroup(gid).getInfo(mid);
}
+ /**
+ * API to check if the device is in the group
+ *
+ * @param gid
+ * group id
+ * @param di
+ * device id
+ * @return true if the device exists in the group or false if the device is
+ * not in the group
+ */
+ public boolean verifyDeviceInGroup(String gid, String di) {
+ try {
+ return getGroup(gid).checkDeviceExistance(di);
+ } catch (NullPointerException e) {
+ // if getGroup(gid) throws NullPointerException
+ return false;
+ }
+ }
+
+ /**
+ * API to add a group subscriber of a specific group
+ *
+ * @param gid
+ * group id to subscribe
+ * @param mid
+ * An unique Identifier of the member(query requester) who is
+ * expected as a member of a group
+ * @param srcDevice
+ * subscriber device
+ * @param request
+ * request message
+ * @return group information payload
+ */
public HashMap<String, Object> addGroupSubscriber(String gid, String mid,
Device srcDevice, IRequest request) {
return getGroup(gid).addSubscriber(mid, srcDevice, request);
}
+ /**
+ * API to unsubscribe group information
+ *
+ * @param gid
+ * group id to subscribe
+ * @param mid
+ * user Id to unscribe group information
+ * @return group information payload
+ */
public HashMap<String, Object> removeGroupSubscriber(String gid,
String mid) {
return getGroup(gid).removeSubscriber(mid);
}
+ /**
+ * API to get group information for a certain group
+ *
+ * @param gid
+ * group id to get
+ * @return group information
+ */
public Group getGroup(String gid) {
return mGroups.get(gid);
import org.iotivity.cloud.base.protocols.enums.ResponseStatus;
import org.iotivity.cloud.util.Cbor;
+/**
+ *
+ * This class provides a set of APIs to invite a user to a group
+ *
+ */
+
public class InviteManager {
private TypeCastingManager<InviteTable> mTypeInvite = new TypeCastingManager<>();
public void addInvitation(String uid, String gid, String mid) {
+ // create invitation table
InviteTable newInviteTable = new InviteTable(uid, gid, mid);
HashMap<String, Object> condition = new HashMap<>();
response = handleGetRequest(srcDevice, request);
break;
case POST:
+ // handle send-invitation message
response = handlePostRequest(request);
break;
case DELETE:
HashMap<String, Object> payload = mCbor
.parsePayloadFromCbor(request.getPayload(), HashMap.class);
+ // check properties in payload
checkPayloadException(
Arrays.asList(Constants.REQ_UUID_ID, Constants.REQ_INVITE),
payload);
+ // get user uid
String uid = (String) payload.get(Constants.REQ_UUID_ID);
ArrayList<HashMap<String, String>> inviteList = (ArrayList<HashMap<String, String>>) payload
.get(Constants.REQ_INVITE);
import org.iotivity.cloud.accountserver.Constants;
import org.iotivity.cloud.accountserver.db.AccountDBManager;
+import org.iotivity.cloud.accountserver.db.MongoDB;
import org.iotivity.cloud.accountserver.db.TokenTable;
import org.iotivity.cloud.accountserver.db.UserTable;
import org.iotivity.cloud.accountserver.resources.acl.group.GroupResource;
private static final String GROUP_URI = Constants.GROUP_FULL_URI;
private static final String DEVICE_ID = "B371C481-38E6-4D47-8320-7688D8A5B58C";
private String mAuthProvider = "Github";
- private String mAuthCode = "00a93f698b47980b2d77";
+ private String mAuthCode = "b4878d614bbc5f8db463";
private CoapDevice mMockDevice = mock(
CoapDevice.class);
private Cbor<HashMap<String, Object>> mCbor = new Cbor<>();
private TypeCastingManager<TokenTable> mTokenTableCastingManager = new TypeCastingManager<>();
private AccountResource mAccountResource = new AccountResource();
private GroupResource mGroupResource = new GroupResource();
+ private String mGroupId = null;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
+ resetAccountDatabase();
// callback mock
Mockito.doAnswer(new Answer<Object>() {
@Override
throws Throwable {
Object[] args = invocation.getArguments();
CoapResponse resp = (CoapResponse) args[0];
+ if (resp.getPayload() != null) {
+ HashMap<String, Object> payloadData = mCbor
+ .parsePayloadFromCbor(resp.getPayload(),
+ HashMap.class);
+ if (payloadData.containsKey("gid")) {
+ mGroupId = (String) payloadData.get("gid");
+ }
+ }
System.out
.println("\t----payload : " + resp.getPayloadString());
System.out
}).when(mMockDevice).sendResponse(Mockito.anyObject());
}
+ public static void resetAccountDatabase() throws Exception {
+ MongoDB mongoDB = new MongoDB(Constants.DB_NAME);
+ mongoDB.createTable(Constants.USER_TABLE);
+ mongoDB.createTable(Constants.TOKEN_TABLE);
+ mongoDB.createTable(Constants.GROUP_TABLE);
+ }
+
@Test
public void testSignUpOnDefaultRequestReceived() throws Exception {
getTestMethodName();
getTestMethodName();
String uuid = "u0001Search";
// register TokenInfo and UserInfo to the DB
- HashMap<String, Object> tokenInfo = mTokenTableCastingManager
- .convertObjectToMap(makeTokenTable(uuid));
- HashMap<String, Object> userInfo = mUserTableCastingManager
- .convertObjectToMap(makeUserTable(uuid));
- AccountDBManager.getInstance()
- .insertAndReplaceRecord(Constants.TOKEN_TABLE, tokenInfo);
- AccountDBManager.getInstance().insertRecord(Constants.USER_TABLE,
- userInfo);
+ registerTokenUserInfo(uuid, DEVICE_ID);
// request uuid using search criteria
getUserInfoSearch("search=userid:userId");
Cbor<HashMap<String, ArrayList<HashMap<String, Object>>>> cbor = new Cbor<>();
assertTrue(getUserInfo.get("uid").equals(uuid));
}
- private void getUserInfoSearch(String query) {
- System.out.println("-----get User Info Search using query: " + query);
- IRequest request = MessageBuilder.createRequest(RequestMethod.GET,
- REGISTER_URI, query);
- mAccountResource.onDefaultRequestReceived(mMockDevice, request);
+ @Test
+ public void testDeleteDeviceDefaultGroupOnDefaultRequestReceived()
+ throws Exception {
+ getTestMethodName();
+ // register the token table and user table to the DB
+ String uuid = "u0001";
+ registerTokenUserInfo(uuid, DEVICE_ID);
+ createGroup(uuid, "Private");
+ // register three devices to the group
+ shareDevice(DEVICE_ID, uuid);
+ shareDevice(DEVICE_ID + "2", uuid);
+ shareDevice(DEVICE_ID + "3", uuid);
+ // delete one device
+ deleteDevice(DEVICE_ID, uuid);
+ assertTrue(methodCheck(mResponse, ResponseStatus.DELETED));
}
@Test
- public void testDeleteDeviceOnDefaultRequestReceived() throws Exception {
+ public void testDeleteDeviceInEveryGroupOnDefaultRequestReceived()
+ throws Exception {
+ getTestMethodName();
+ // register the token table and user table for three resource servers to
+ // the DB
+ String uuid = "u0001DeleteEveryGroup";
+ registerTokenUserInfo(uuid, DEVICE_ID);
+ registerTokenInfo(uuid, DEVICE_ID + "2");
+ registerTokenInfo(uuid, DEVICE_ID + "3");
+ // register token table for the resource client
+ registerTokenInfo(uuid, DEVICE_ID + "4");
+ createGroup(uuid, "Private");
+ // register three devices to the private group
+ shareDevice(DEVICE_ID, uuid);
+ shareDevice(DEVICE_ID + "2", uuid);
+ shareDevice(DEVICE_ID + "3", uuid);
+ // register resource servers to the public group
+ createGroup(uuid, "Public");
+ shareDevice(DEVICE_ID, mGroupId);
+ shareDevice(DEVICE_ID + "2", mGroupId);
+ shareDevice(DEVICE_ID + "3", mGroupId);
+ // register resource servers to the public group
+ createGroup(uuid, "Public");
+ shareDevice(DEVICE_ID, mGroupId);
+ shareDevice(DEVICE_ID + "2", mGroupId);
+ shareDevice(DEVICE_ID + "3", mGroupId);
+ // device delete for three resource servers
+ deleteDevice(DEVICE_ID, uuid);
+ assertTrue(methodCheck(mResponse, ResponseStatus.DELETED));
+ deleteDevice(DEVICE_ID + "2", uuid);
+ assertTrue(methodCheck(mResponse, ResponseStatus.DELETED));
+ deleteDevice(DEVICE_ID + "3", uuid);
+ assertTrue(methodCheck(mResponse, ResponseStatus.DELETED));
+ // device delete for one resource client
+ deleteDevice(DEVICE_ID + "4", uuid);
+ assertTrue(methodCheck(mResponse, ResponseStatus.DELETED));
+ }
+
+ @Test
+ public void testDeleteClientOnDefaultRequestReceived() throws Exception {
getTestMethodName();
// register the token table and user table to the DB
- String uuid = "u0001";
+ String uuid = "u0001Client";
HashMap<String, Object> tokenInfo = mTokenTableCastingManager
- .convertObjectToMap(makeTokenTable(uuid));
+ .convertObjectToMap(makeTokenTable(uuid, DEVICE_ID));
HashMap<String, Object> userInfo = mUserTableCastingManager
.convertObjectToMap(makeUserTable(uuid));
AccountDBManager.getInstance()
.insertAndReplaceRecord(Constants.TOKEN_TABLE, tokenInfo);
AccountDBManager.getInstance().insertRecord(Constants.USER_TABLE,
userInfo);
- createDefaultGroup(uuid);
- shareDevice(DEVICE_ID);
- deleteDevice(DEVICE_ID);
+ deleteDevice(DEVICE_ID, uuid);
assertTrue(methodCheck(mResponse, ResponseStatus.DELETED));
}
@Test
public void testGetUserInfoUsingUuidOnDefaultRequestReceived()
throws Exception {
- System.out.println(
- "\t--------------Sign Up with Invalid Method (GET) Test------------");
+ getTestMethodName();
// register the token table and user table to the DB
String uuid = "u0001Get";
HashMap<String, Object> tokenInfo = mTokenTableCastingManager
- .convertObjectToMap(makeTokenTable(uuid));
+ .convertObjectToMap(makeTokenTable(uuid, DEVICE_ID));
HashMap<String, Object> userInfo = mUserTableCastingManager
.convertObjectToMap(makeUserTable(uuid));
AccountDBManager.getInstance()
assertTrue(methodCheck(mResponse, ResponseStatus.CONTENT));
}
+ private void registerTokenUserInfo(String uuid, String deviceId) {
+ registerTokenInfo(uuid, deviceId);
+ registerUserInfo(uuid);
+ }
+
+ private void registerTokenInfo(String uuid, String deviceId) {
+ HashMap<String, Object> tokenInfo = mTokenTableCastingManager
+ .convertObjectToMap(makeTokenTable(uuid, deviceId));
+ AccountDBManager.getInstance()
+ .insertAndReplaceRecord(Constants.TOKEN_TABLE, tokenInfo);
+ }
+
+ private void registerUserInfo(String uuid) {
+ HashMap<String, Object> userInfo = mUserTableCastingManager
+ .convertObjectToMap(makeUserTable(uuid));
+ AccountDBManager.getInstance().insertRecord(Constants.USER_TABLE,
+ userInfo);
+ }
+
private void getTestMethodName() {
StackTraceElement[] stacks = new Throwable().getStackTrace();
StackTraceElement currentStack = stacks[1];
return request;
}
- private void createDefaultGroup(String uuid) throws Exception {
- System.out.println("-----Create Default Group");
+ private void createGroup(String uuid, String gtype) throws Exception {
+ System.out.println("-----Create Group");
IRequest request = null;
- request = createDefaultGroupRequest(uuid);
+ request = createDefaultGroupRequest(uuid, gtype);
mGroupResource.onDefaultRequestReceived(mMockDevice, request);
}
- private void deleteDevice(String di) throws Exception {
+ private void deleteDevice(String di, String uid) throws Exception {
System.out.println("-----Delete Device");
IRequest request = null;
- request = deleteDeviceRequest(di);
+ request = deleteDeviceRequest(di, uid);
mAccountResource.onDefaultRequestReceived(mMockDevice, request);
}
mAccountResource.onDefaultRequestReceived(mMockDevice, request);
}
- private void shareDevice(String deviceId) throws Exception {
+ private void shareDevice(String deviceId, String gid) throws Exception {
System.out.println("-----Share Device");
IRequest request = null;
- request = createShareDeviceRequest(deviceId);
+ request = createShareDeviceRequest(deviceId, gid);
mGroupResource.onDefaultRequestReceived(mMockDevice, request);
}
- private IRequest deleteDeviceRequest(String deviceId) {
+ private IRequest deleteDeviceRequest(String deviceId, String uid) {
IRequest request = MessageBuilder.createRequest(RequestMethod.DELETE,
- REGISTER_URI, "di=" + deviceId + ";uid=u0001");
+ REGISTER_URI, "di=" + deviceId + ";uid=" + uid);
return request;
}
- private IRequest createDefaultGroupRequest(String uuid) {
+ private IRequest createDefaultGroupRequest(String uuid, String gtype) {
IRequest request = null;
HashMap<String, String> payloadData = new HashMap<String, String>();
payloadData.put("gmid", uuid);
- payloadData.put("gtype", "Private");
+ payloadData.put("gtype", gtype);
request = MessageBuilder.createRequest(RequestMethod.POST, GROUP_URI,
null, ContentFormat.APPLICATION_CBOR,
mCbor.encodingPayloadToCbor(payloadData));
return request;
}
- private IRequest createShareDeviceRequest(String deviceId) {
+ private IRequest createShareDeviceRequest(String deviceId, String gid) {
IRequest request = null;
HashMap<String, Object> payloadData = new HashMap<String, Object>();
ArrayList<String> diList = new ArrayList<>();
diList.add(deviceId);
payloadData.put("dilist", diList);
request = MessageBuilder.createRequest(RequestMethod.POST,
- GROUP_URI + "/" + "u0001", null, ContentFormat.APPLICATION_CBOR,
+ GROUP_URI + "/" + gid, null, ContentFormat.APPLICATION_CBOR,
mCbor.encodingPayloadToCbor(payloadData));
return request;
}
return request;
}
+ private void getUserInfoSearch(String query) {
+ System.out.println("-----get User Info Search using query: " + query);
+ IRequest request = MessageBuilder.createRequest(RequestMethod.GET,
+ REGISTER_URI, query);
+ mAccountResource.onDefaultRequestReceived(mMockDevice, request);
+ }
+
private IRequest signUpInvalidMethodRequest(String deviceId,
String authProvider, String authCode) {
IRequest request = null;
return false;
}
- private TokenTable makeTokenTable(String uuid) {
+ private TokenTable makeTokenTable(String uuid, String deviceId) {
TokenTable tokenInfo = new TokenTable();
tokenInfo.setUuid(uuid);
- tokenInfo.setDid(DEVICE_ID);
+ tokenInfo.setDid(deviceId);
tokenInfo.setAccesstoken("at0001");
tokenInfo.setRefreshtoken("rt0001");
tokenInfo.setProvider(mAuthProvider);
uriPath.append(Constants.PREFIX_OIC + "/");
uriPath.append(Constants.RD_URI);
mRDServer.sendRequest(
- MessageBuilder.createRequest(RequestMethod.POST,
+ MessageBuilder.createRequest(RequestMethod.DELETE,
uriPath.toString(), mRequest.getUriQuery()),
mSrcDevice);
break;