public static final String REQ_LINKS = "links";
public static final String REQ_HREF = "href";
-
+ public static final String REQ_CRL = "crl";
}
import org.mockito.stubbing.Answer;
public class DevicePresenceTest {
- public static final String DEVICE_PRS_REQ_URI = Constants.DEVICE_PRESENCE_FULL_URI;
- public static final String DEVICE_LIST_KEY = "devices";
- public static final String RES_PRS_URI = Constants.RESOURCE_PRESENCE_FULL_URI;
- private String mDi = "B371C481-38E6-4D47-8320-7688D8A5B58C";
- private CoapDevice mMockDevice = mock(CoapDevice.class);
- private IRequest mReq = null;
- private DeviceServerSystem mDeviceServerSystem = new DeviceServerSystem();
- final CountDownLatch mLatch = new CountDownLatch(1);
+ private static final String DEVICE_PRS_REQ_URI = Constants.DEVICE_PRESENCE_FULL_URI;
+ private String mDi = "B371C481-38E6-4D47-8320-7688D8A5B58C";
+ private CoapDevice mMockDevice = mock(CoapDevice.class);
+ private IRequest mReq = null;
+ private DeviceServerSystem mDeviceServerSystem = new DeviceServerSystem();
+ final CountDownLatch mLatch = new CountDownLatch(1);
@Mock
- private IRequestChannel mRequestChannel;
+ private IRequestChannel mRequestChannel;
@InjectMocks
- private DevicePresence mPrsHandler = new DevicePresence();
+ private DevicePresence mPrsHandler = new DevicePresence();
@Before
public void setUp() throws Exception {
public class ResourcePresenceTest {
public static final String DEVICE_PRS_REQ_URI = Constants.DEVICE_PRESENCE_FULL_URI;
- public static final String DEVICE_LIST_KEY = "devices";
public static final String RES_PRS_URI = Constants.RESOURCE_PRESENCE_FULL_URI;
private String mDi = "B371C481-38E6-4D47-8320-7688D8A5B58C";
private CoapDevice mMockDevice = mock(CoapDevice.class);
*/
package org.iotivity.cloud.rdserver;
-import java.util.Arrays;
-import java.util.List;
-
import org.iotivity.cloud.base.OICConstants;
public class Constants extends OICConstants {
- public static final String RD_DB_NAME = "RD_DB";
- public static final String RD_TABLE = "RD_TABLE";
- public static final String PRESENCE_TABLE = "PRESENCE_TABLE";
-
- public static final String DEVICE_NAME = "n";
- public static final String DEVICE_ID = "di";
- public static final String POLICY = "p";
- public static final String BITMAP = "bm";
- public static final String INS = "ins";
- public static final String DEVICE_TTL = "lt";
- public static final String RESOURCE_TTL = "ttl";
- public static final String HREF = "href";
- public static final String RESOURCE_TYPE = "rt";
- public static final String INTERFACE = "if";
- public static final String REL = "rel";
- public static final String TITLE = "title";
- public static final String ANCHOR = "anchor";
- public static final String MEDIA_TYPE = "type";
- public static final String LINKS = "links";
- public static final String RESOURCE_TYPE_RDPUBLISH = "oic.wk.rdpub";
- public static final List<String> TAGS = Arrays
- .asList(DEVICE_NAME, DEVICE_ID, DEVICE_TTL);
-
- public static final String SEARCH_TYPE = "st";
- public static final String SEARCH_TYPE_DEVICE_LIST = "didList";
- public static final String DEVICE_LIST_KEY = "devices";
-
- // for '/oic/prs' resource
- public static final String PRESENCE_STATE = "state";
- public static final String PRESENCE_LIST = "prslist";
+ /** Database, Table name */
+ public static final String RD_DB_NAME = "RD_DB";
+ public static final String RD_TABLE = "RD_TABLE";
+ public static final String PRESENCE_TABLE = "PRESENCE_TABLE";
- public static final String RS_NON = "non";
- public static final String RS_TRIGGER = "trg";
+ /** A human friendly name of device */
+ public static final String DEVICE_NAME = "n";
+ /** An unique identifier of device */
+ public static final String DEVICE_ID = "di";
+ /** policies that apply for resource */
+ public static final String POLICY = "p";
+ /** To represent bitmap. */
+ public static final String BITMAP = "bm";
+ /** An ordinal number that is not repeated */
+ public static final String INS = "ins";
+ /** Time (in seconds) to indicate how long RD should publish this item */
+ public static final String DEVICE_TTL = "lt";
+ /** Time to live for this link */
+ public static final String RESOURCE_TTL = "ttl";
+ /** URI Reference */
+ public static final String HREF = "href";
+ /** Resource Types */
+ public static final String RESOURCE_TYPE = "rt";
+ /** Resource interface */
+ public static final String INTERFACE = "if";
+ /** Relation between target URI and context URI */
+ public static final String REL = "rel";
+ /** Title for the link relation */
+ public static final String TITLE = "title";
+ /** This is used to override the context URI */
+ public static final String ANCHOR = "anchor";
+ /** Media type. Default : application/json */
+ public static final String MEDIA_TYPE = "type";
+ /** To represent links. */
+ public static final String LINKS = "links";
+ /** To represent resource type with Publish RD. */
+ public static final String RESOURCE_TYPE_RDPUBLISH = "oic.wk.rdpub";
- public static final long OBSERVE_REGISTER = 0;
- public static final long OBSERVE_DEREGISTER = 1;
+ /** '/oic/prs' resource property */
+ public static final String PRESENCE_STATE = "state";
+ public static final String PRESENCE_LIST = "prslist";
+ public static final String DEVICE_PRESENCE = "device_presence";
- public static final byte RES_CREATE = 0;
- public static final byte RES_CHANGE = 1;
- public static final byte RES_DELETE = 2;
+ /** '/oic/ad' resource property */
+ public static final String NON = "non";
+ public static final String TRIGGER = "trg";
+ public static final byte RES_CREATE = 0;
+ public static final byte RES_CHANGE = 1;
+ public static final byte RES_DELETE = 2;
+ public static final String RESOURCE_PRESENCE = "resource_presence";
}
import org.iotivity.cloud.rdserver.resources.presence.resource.ResPresenceResource;
import org.iotivity.cloud.util.Log;
+/**
+ *
+ * This class is in charge of running of resource directory server.
+ *
+ */
public class ResourceDirectoryServer {
public static void main(String[] args) throws Exception {
System.out.println("-----RD SERVER-----");
if (args.length != 2) {
- Log.e("coap server port and TLS mode required\n"
- + "ex) 5684 0\n");
+ Log.e("coap server port and TLS mode required\n" + "ex) 5684 0\n");
return;
}
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.base.exception.ServerException.InternalServerErrorException;
import org.iotivity.cloud.rdserver.Constants;
-import org.iotivity.cloud.rdserver.resources.presence.resource.ResPresencePayload;
+/**
+ *
+ * This class provides a set of APIs to access a DataBase.
+ *
+ */
public class DBManager {
- private static DBManager mDBManager = new DBManager();
- private MongoDB mMongoDB = null;;
+ private static DBManager mDBManager = new DBManager();
+ private MongoDB mMongoDB = null;
+ private HashMap<String, ArrayList<String>> mKeyField = new HashMap<>();
private DBManager() {
+ createDatabase();
+ createTables();
+ createIndexes();
+ }
+
+ /**
+ * API to return DBManager object
+ *
+ * @return DBManager DBManager object
+ */
+ public static DBManager getInstance() {
+ return mDBManager;
+ }
+
+ private void createDatabase() {
+
try {
+
mMongoDB = new MongoDB(Constants.RD_DB_NAME);
- mMongoDB.createTable(Constants.RD_TABLE);
- mMongoDB.createTable(Constants.PRESENCE_TABLE);
} catch (Exception e) {
- // TODO Auto-generated catch block
e.printStackTrace();
+ throw new InternalServerErrorException("Database create failed!");
}
}
- public static DBManager getInstance() {
- return mDBManager;
+ private void createTables() {
+ mMongoDB.createTable(Constants.RD_TABLE);
+ mMongoDB.createTable(Constants.PRESENCE_TABLE);
+ }
+
+ private void createIndexes() {
+
+ ArrayList<String> keys = new ArrayList<>();
+ keys.add(Constants.DEVICE_ID);
+ keys.add(Constants.INS);
+
+ mMongoDB.createIndex(Constants.RD_TABLE, keys);
+ mKeyField.put(Constants.RD_TABLE, keys);
+
+ keys = new ArrayList<>();
+ keys.add(Constants.DEVICE_ID);
+
+ mMongoDB.createIndex(Constants.PRESENCE_TABLE, keys);
+ mKeyField.put(Constants.PRESENCE_TABLE, keys);
+
+ }
+
+ /**
+ * 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 insert
+ * record to be inserted
+ */
+ public void insertRecord(String tableName, HashMap<String, Object> insert) {
+
+ if (!_insertRecord(tableName, insert))
+ throw new InternalServerErrorException(
+ "Database record insert failed");
+ }
+
+ /**
+ * 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) {
+
+ if (!_insertAndReplaceRecord(tableName, replace))
+ throw new InternalServerErrorException(
+ "Database record insert failed");
+ }
+
+ /**
+ * 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);
}
- public ArrayList<ResPresencePayload> registerResource(
- ArrayList<HashMap<Object, Object>> pubResourceList) {
- return mMongoDB.createRDResource(pubResourceList, Constants.RD_TABLE);
+ /**
+ * API for deleting records from DB table.
+ *
+ * @param tableName
+ * table name to be inserted
+ * @param condition
+ * condition record to be deleted
+ */
+ public void deleteRecord(String tableName,
+ HashMap<String, Object> condition) {
+
+ if (!_deleteRecord(tableName, condition))
+ throw new InternalServerErrorException(
+ "Database record delete failed");
}
- public ArrayList<HashMap<Object, Object>> findResourceAboutDi(String di) {
- return mMongoDB.readResourceAboutDid(di, Constants.RD_TABLE);
+ /**
+ * 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) {
+
+ if (!_updateRecord(tableName, replace))
+ throw new InternalServerErrorException(
+ "Database record update failed");
+
}
-
- public ArrayList<HashMap<Object, Object>> findResourceAboutDiAndFilter(String di,
- String key, String value) {
- return mMongoDB.readResourceAboutDidAndFilter(di, key, value,
- Constants.RD_TABLE);
+
+ private Boolean _insertRecord(String tableName,
+ HashMap<String, Object> record) {
+
+ Document doc = createDocument(record);
+
+ return mMongoDB.insertRecord(tableName, doc);
}
- public ArrayList<ResPresencePayload> deleteResourceAboutDi(String di) {
- return mMongoDB.deleteResourceAboutDi(di, Constants.RD_TABLE);
+ private Boolean _insertAndReplaceRecord(String tableName,
+ HashMap<String, Object> record) {
+
+ Document doc = createDocument(record);
+ Document filter = getKeyFilter(tableName, record);
+
+ return mMongoDB.insertAndReplaceRecord(tableName, filter, doc);
}
- public ArrayList<ResPresencePayload> deleteResourceAboutDiAandIns(String di,
- String ins) {
- return mMongoDB.deleteResourceAboutDiAndIns(di, ins,
- Constants.RD_TABLE);
+ private Boolean _deleteRecord(String tableName,
+ HashMap<String, Object> condition) {
+
+ Document doc = createDocument(condition);
+
+ return mMongoDB.deleteRecord(tableName, doc);
}
- public Object findInsAboutDi(String di, String href) {
- return mMongoDB.readInsAboutDid(di, href, Constants.RD_TABLE);
+ private Boolean _updateRecord(String tableName,
+ HashMap<String, Object> record) {
+
+ Document replace = createDocument(record);
+ Document filter = getKeyFilter(tableName, record);
+
+ return mMongoDB.updateRecord(tableName, filter, replace);
}
- public void updateDeviceState(HashMap<Object, Object> deviceState) {
- mMongoDB.createDevicePresenceResource(deviceState,
- Constants.PRESENCE_TABLE);
+ private ArrayList<HashMap<String, Object>> _selectRecord(String tableName,
+ HashMap<String, Object> record) {
+
+ Document doc = createDocument(record);
+
+ return mMongoDB.selectRecord(tableName, doc);
}
- public String findDeviceState(String deviceId) {
- return mMongoDB.readDeviceState(deviceId, Constants.PRESENCE_TABLE);
+ private Document getKeyFilter(String tableName,
+ HashMap<String, Object> record) {
+
+ Document filterDoc = new Document();
+
+ ArrayList<String> keys = mKeyField.get(tableName);
+
+ for (String key : keys) {
+
+ Object value = record.get(key);
+ filterDoc.append(key, value);
+ }
+
+ return filterDoc;
}
-}
+
+ private Document createDocument(HashMap<String, Object> record) {
+
+ 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;
+ }
+
+}
\ No newline at end of file
import java.util.Set;
import org.bson.Document;
-import org.iotivity.cloud.rdserver.Constants;
-import org.iotivity.cloud.rdserver.resources.presence.resource.ResPresencePayload;
+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;
/**
*
* @throws Exception
*/
public MongoDB(String dbname) throws Exception {
+
mongoClient = new MongoClient();
mongoClient.dropDatabase(dbname);
db = mongoClient.getDatabase(dbname);
}
/**
- * API creating collection
+ * API for creating collection
*
* @param tableName
* collection name
*/
public void createTable(String tableName) {
- deleteTable(tableName);
+
db.createCollection(tableName);
}
/**
- * 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();
- }
-
- private Document createDocument(HashMap<Object, Object> storeRes) {
+ public void createIndex(String tablename, ArrayList<String> keys) {
Document doc = new Document();
- Set<Entry<Object, Object>> resEntrySet = storeRes.entrySet();
- Iterator<Entry<Object, Object>> entryIter = resEntrySet.iterator();
-
- while (entryIter.hasNext()) {
- Map.Entry<Object, Object> entry = (Map.Entry<Object, Object>) entryIter
- .next();
- doc.append(entry.getKey().toString(), entry.getValue());
- }
-
- return doc;
- }
-
- private ArrayList<Document> createDocuments(
- ArrayList<HashMap<Object, Object>> storeResList) {
-
- Iterator<HashMap<Object, Object>> resListIter = storeResList.iterator();
-
- ArrayList<Document> docList = new ArrayList<>();
- while (resListIter.hasNext()) {
- Document doc = new Document();
+ for (String key : keys) {
- HashMap<Object, Object> storeRes = resListIter.next();
- Set<Entry<Object, Object>> resEntrySet = storeRes.entrySet();
- Iterator<Entry<Object, Object>> entryIter = resEntrySet.iterator();
-
- while (entryIter.hasNext()) {
- Map.Entry<Object, Object> entry = (Map.Entry<Object, Object>) entryIter
- .next();
- doc.append(entry.getKey().toString(), entry.getValue());
- }
- docList.add(doc);
+ doc.append(key, 1);
}
- return docList;
- }
-
- private HashMap<Object, Object> convertDocumentToHashMap(Document doc) {
- HashMap<Object, Object> resourceMap = new HashMap<Object, Object>();
-
- Set<Entry<String, Object>> entrySet = doc.entrySet();
- Iterator<Entry<String, Object>> entryIter = entrySet.iterator();
- while (entryIter.hasNext()) {
- Map.Entry<String, Object> entry = (Map.Entry<String, Object>) entryIter
- .next();
- if (entry.getValue() != null) {
- resourceMap.put(entry.getKey().toString(), entry.getValue());
- }
- }
+ IndexOptions options = new IndexOptions();
+ options.unique(true);
- return resourceMap;
+ db.getCollection(tablename).createIndex(doc, options);
}
/**
- * API for storing information of published resources
+ * API for deleting collection
*
- * @param publishPayloadFormat
- * information of published resources to store in collection
* @param tableName
* collection name
*/
- public ArrayList<ResPresencePayload> createRDResource(
- ArrayList<HashMap<Object, Object>> storeResList, String tableName) {
- ArrayList<Document> docList = createDocuments(storeResList);
- Iterator<Document> docIter = docList.iterator();
+ public void deleteTable(String tableName) {
+
+ db.getCollection(tableName).drop();
+ }
+
+ /**
+ * API for getting database object
+ *
+ */
+ public MongoDatabase getMongoDatabase() {
+
+ return db;
+ }
+
+ public Boolean insertRecord(String tableName, Document doc) {
+
+ if (tableName == null || doc == null)
+ return false;
MongoCollection<Document> collection = db.getCollection(tableName);
- ArrayList<ResPresencePayload> resPayloadList = new ArrayList<>();
+ try {
- while (docIter.hasNext()) {
- Document doc = docIter.next();
- byte trigger = 0;
+ if (collection.find(doc).first() == null) {
- if (collection.findOneAndReplace(
- Filters.and(
- Filters.eq(Constants.DEVICE_ID,
- doc.get(Constants.DEVICE_ID)),
- Filters.eq(Constants.INS, doc.get(Constants.INS))),
- doc) == null) {
collection.insertOne(doc);
- trigger = Constants.RES_CREATE;
} else {
- trigger = Constants.RES_CHANGE;
+ Log.w("DB insert failed due to duplecated one.");
+ return false;
}
- resPayloadList.add(makeResourcePresencePayload(doc, trigger));
+ } catch (Exception e) {
+
+ e.printStackTrace();
+ return false;
}
- return resPayloadList;
+
+ showRecord(tableName);
+
+ return true;
}
- public void createDevicePresenceResource(HashMap<Object, Object> storeRes,
- String tableName) {
+ public Boolean insertAndReplaceRecord(String tableName, Document filter,
+ Document doc) {
+
+ if (tableName == null || filter == null || doc == null)
+ return false;
- Document doc = createDocument(storeRes);
MongoCollection<Document> collection = db.getCollection(tableName);
- if (collection
- .findOneAndReplace(
- Filters.and(Filters.eq(Constants.DEVICE_ID,
- doc.get(Constants.DEVICE_ID))),
- doc) == null) {
+ try {
+
+ if (collection.findOneAndReplace(filter, doc) == null) {
+
+ collection.insertOne(doc);
+ }
+
+ } catch (Exception e) {
- collection.insertOne(doc);
+ e.printStackTrace();
+ return false;
}
- return;
+ showRecord(tableName);
+
+ return true;
}
- private ResPresencePayload makeResourcePresencePayload(Document doc,
- byte trigger) {
+ public Boolean updateRecord(String tableName, Document filter,
+ Document record) {
- ResPresencePayload resPayload = new ResPresencePayload();
+ if (tableName == null || filter == null || record == null)
+ return false;
- resPayload.setTrg(trigger);
+ MongoCollection<Document> collection = db.getCollection(tableName);
- Object rt = doc.get(Constants.RESOURCE_TYPE);
- if (rt != null) {
- resPayload.setRt(rt.toString());
- }
- Object href = doc.get(Constants.HREF);
- if (href != null) {
- Object di = doc.get(Constants.DEVICE_ID);
- if (di != null) {
- resPayload.setHref(href.toString());
- }
- }
- Object ttl = doc.get(Constants.RESOURCE_TTL);
- if (ttl != null) {
- resPayload.setTtl((int) ttl);
+ if (collection.findOneAndReplace(filter, record) == null) {
+
+ Log.w("DB update failed due to no matched record!");
+ return false;
}
- return resPayload;
+
+ showRecord(tableName);
+
+ return true;
}
- public String readDeviceState(String deviceId, String tableName) {
+ public Boolean deleteRecord(String tableName, Document record) {
- String deviceState = null;
+ if (tableName == null || record == null)
+ return false;
MongoCollection<Document> collection = db.getCollection(tableName);
- MongoCursor<Document> cursor = collection
- .find(Filters.eq(Constants.DEVICE_ID, deviceId))
- .iterator();
-
try {
- while (cursor.hasNext()) {
- Document doc = cursor.next();
- deviceState = doc.getString(Constants.PRESENCE_STATE);
- break;
- }
+ collection.deleteMany(record);
- } finally {
+ } catch (Exception e) {
- cursor.close();
+ e.printStackTrace();
+ return false;
}
- return deviceState;
+ showRecord(tableName);
+
+ return true;
}
- public ArrayList<HashMap<Object, Object>> readResourceAboutDid(String di, String tableName) {
- MongoCollection<Document> collection = db.getCollection(tableName);
- ArrayList<HashMap<Object, Object>> resList = null;
- MongoCursor<Document> cursor = collection
- .find(Filters.eq(Constants.DEVICE_ID, di))
- .iterator();
-
- if (cursor.hasNext()) {
- resList = new ArrayList<>();
- try {
- while (cursor.hasNext()) {
- Document doc = cursor.next();
- resList.add(convertDocumentToHashMap(doc));
- }
- } finally {
- cursor.close();
- }
- }
+ public ArrayList<HashMap<String, Object>> selectRecord(String tableName,
+ Document doc) {
- return resList;
- }
+ if (tableName == null || doc == null)
+ return null;
- /**
- * API for finding resources matched filterValue of filterKey and a
- * particular device ID in collection
- *
- * @param di
- * device id
- * @param filterKey
- * field name in collection
- * @param filterValue
- * field value about field name
- * @param tableName
- * collection name
- * @return ArrayList<PublishPayloadFormat> - array list of resource
- * information
- */
- public ArrayList<HashMap<Object, Object>> readResourceAboutDidAndFilter(String di,
- String filterKey, String filterValue, String tableName) {
MongoCollection<Document> collection = db.getCollection(tableName);
- ArrayList<HashMap<Object, Object>> resList = null;
- MongoCursor<Document> cursor = collection
- .find(Filters.and(Filters.eq(Constants.DEVICE_ID, di),
- Filters.eq(filterKey, filterValue)))
- .iterator();
-
- if (cursor.hasNext()) {
- resList = new ArrayList<>();
- try {
- while (cursor.hasNext()) {
- Document doc = cursor.next();
- resList.add(convertDocumentToHashMap(doc));
- }
- } finally {
- cursor.close();
- }
- }
+ MongoCursor<Document> cursor = collection.find(doc).iterator();
- return resList;
- }
+ ArrayList<HashMap<String, Object>> recordList = new ArrayList<>();
- public Object readInsAboutDid(String di, String href, String tableName) {
- MongoCollection<Document> collection = db.getCollection(tableName);
- MongoCursor<Document> cursor = collection
- .find(Filters.and(Filters.eq(Constants.DEVICE_ID, di),
- Filters.eq(Constants.HREF, href)))
- .iterator();
try {
+
while (cursor.hasNext()) {
- Document doc = cursor.next();
- return doc.get(Constants.INS);
+ Document selectedDoc = cursor.next();
+ recordList.add(convertDocumentToHashMap(selectedDoc));
}
+
} finally {
+
cursor.close();
}
- return null;
+
+ return recordList;
}
- /**
- * API for deleting resources about a particular device ID in collection
- *
- * @param di
- * device id
- * @param tableName
- * collection name
- */
- public ArrayList<ResPresencePayload> deleteResourceAboutDi(String di,
- String tableName) {
+ private HashMap<String, Object> convertDocumentToHashMap(Document doc) {
+ HashMap<String, Object> resourceMap = new HashMap<>();
- MongoCollection<Document> collection = db.getCollection(tableName);
+ Set<Entry<String, Object>> entrySet = doc.entrySet();
+ Iterator<Entry<String, Object>> entryIter = entrySet.iterator();
- MongoCursor<Document> cursor = collection
- .find(Filters.eq(Constants.DEVICE_ID, di)).iterator();
+ while (entryIter.hasNext()) {
- ArrayList<ResPresencePayload> resPayloadList = new ArrayList<>();
+ Map.Entry<String, Object> entry = (Map.Entry<String, Object>) entryIter
+ .next();
- try {
- while (cursor.hasNext()) {
- Document doc = cursor.next();
- resPayloadList.add(
- makeResourcePresencePayload(doc, Constants.RES_DELETE));
- }
+ String entryKey = entry.getKey();
- } finally {
+ // remove a mongoDB index
+ if (entry.getValue() != null && !entryKey.equals("_id")) {
- cursor.close();
+ resourceMap.put(entry.getKey(), entry.getValue());
+ }
}
- collection.deleteMany(Filters.eq(Constants.DEVICE_ID, di));
-
- return resPayloadList;
+ return resourceMap;
}
- /**
- * API for deleting resources about a particular device ID and ins in
- * collection
- *
- * @param di
- * device id
- * @param ins
- * ins
- * @param tableName
- * collection name
- */
- public ArrayList<ResPresencePayload> deleteResourceAboutDiAndIns(String di,
- String ins, String tableName) {
+ private void showRecord(String tableName) {
MongoCollection<Document> collection = db.getCollection(tableName);
+ MongoCursor<Document> cursor = collection.find().iterator();
- MongoCursor<Document> cursor = collection
- .find(Filters.and(Filters.eq(Constants.DEVICE_ID, di),
- Filters.eq(Constants.INS, ins)))
- .iterator();
-
- ArrayList<ResPresencePayload> resPayloadList = new ArrayList<>();
+ Log.i("<" + tableName + ">");
- try {
- while (cursor.hasNext()) {
- Document doc = cursor.next();
- resPayloadList.add(
- makeResourcePresencePayload(doc, Constants.RES_DELETE));
- }
+ HashMap<String, Object> records = null;
+ int index = 0;
+ while (cursor.hasNext()) {
- } finally {
+ Document doc = cursor.next();
+ records = convertDocumentToHashMap(doc);
- cursor.close();
+ Log.i("[" + index + "] " + records.toString());
+ index++;
}
- collection.deleteOne(Filters.and(Filters.eq(Constants.DEVICE_ID, di),
- Filters.eq(Constants.INS, ins)));
-
- return resPayloadList;
-
+ cursor.close();
}
}
--- /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.rdserver.resources.directory;
+
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+
+import org.iotivity.cloud.rdserver.Constants;
+
+/**
+ *
+ * This class provides a set of APIs handle a payload
+ *
+ */
+public class PayloadManager {
+
+ /** tag values of /oic/rd resource payload */
+ public List<String> pubTagKey = Arrays.asList("di", "n", "lt");
+
+ /** links values of /oic/rd resource payload */
+ public List<String> pubLinkKey = Arrays.asList("href", "rel", "rt",
+ "if", "p", "title", "anchor", "ins", "ttl", "type");
+
+ /** tag values of /oic/res resource payload */
+ public List<String> discoverTagKey = Arrays.asList("di", "n");
+
+ /** links values of /oic/res resource payload */
+ public List<String> discoverLinkKey = Arrays.asList("href", "rt", "if",
+ "p");
+
+ /**
+ * API for setting data of payload
+ *
+ * @param payload
+ * payload data
+ * @param keyType
+ * key type
+ * @return data included keys of keyType
+ */
+ public HashMap<String, Object> setPayloadData(
+ HashMap<String, Object> payload, List<String> keyType) {
+
+ HashMap<String, Object> data = new HashMap<String, Object>();
+
+ for (String key : keyType) {
+ Object value = payload.get(key);
+ if (value != null) {
+ data.put(key, value);
+ }
+ }
+ return data;
+ }
+
+ /**
+ * API for changing type of policy property to store in DB
+ *
+ * @param payload
+ * payload data
+ */
+ public void changePolicyTypeToStore(HashMap<String, Object> payload) {
+ Object policy = payload.get(Constants.POLICY);
+ if (policy != null) {
+ HashMap<String, Object> bm = (HashMap<String, Object>) policy;
+ payload.put(Constants.POLICY, (int) (bm.get(Constants.BITMAP)));
+ }
+ }
+
+ /**
+ * API for changing type of policy property to make a discovery response
+ *
+ * @param payload
+ * payload data
+ */
+ public void changePolicyTypeToDiscover(HashMap<String, Object> payload) {
+ Object policy = payload.get(Constants.POLICY);
+ if (policy != null) {
+ HashMap<Object, Object> bm = new HashMap<>();
+ bm.put(Constants.BITMAP, policy);
+ payload.put(Constants.POLICY, bm);
+ }
+ }
+
+}
--- /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.rdserver.resources.directory;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+
+import org.iotivity.cloud.base.exception.ServerException.BadRequestException;
+import org.iotivity.cloud.rdserver.Constants;
+import org.iotivity.cloud.rdserver.db.DBManager;
+import org.iotivity.cloud.rdserver.resources.directory.rd.InsManager;
+import org.iotivity.cloud.util.Log;
+
+/**
+ *
+ * This class provides a set of APIs handle requests about resource information
+ *
+ */
+public class RDManager {
+
+ private InsManager mInsManager = new InsManager();
+ private PayloadManager mPayloadManager = new PayloadManager();
+
+ private ArrayList<HashMap<String, Object>> mResourcePresence = new ArrayList<>();
+
+ /**
+ * API for handling resource-publish process
+ *
+ * @param requestPayload
+ * request payload
+ * @return response payload
+ */
+ public HashMap<String, Object> publishResource(
+ HashMap<String, Object> requestPayload) {
+
+ HashMap<String, Object> deviceInfo = setResourceDeviceInfo(
+ requestPayload);
+ ArrayList<HashMap<String, Object>> links = getLinks(requestPayload);
+
+ // check ins and set ins
+ setResourceIns(deviceInfo.get(Constants.DEVICE_ID).toString(), links);
+
+ storeResource(links, deviceInfo);
+
+ return requestPayload;
+
+ }
+
+ // set di, n, lt info
+ private HashMap<String, Object> setResourceDeviceInfo(
+ HashMap<String, Object> payload) {
+ return mPayloadManager.setPayloadData(payload,
+ mPayloadManager.pubTagKey);
+ }
+
+ private ArrayList<HashMap<String, Object>> getLinks(
+ HashMap<String, Object> requestPayload) {
+ return (ArrayList<HashMap<String, Object>>) requestPayload
+ .get(Constants.LINKS);
+
+ }
+
+ private void storeResource(ArrayList<HashMap<String, Object>> links,
+ HashMap<String, Object> deviceInfo) {
+
+ ArrayList<HashMap<String, Object>> resourcePresence = new ArrayList<>();
+
+ for (HashMap<String, Object> link : links) {
+ HashMap<String, Object> storeInfo = new HashMap<>();
+ HashMap<String, Object> storeLink = mPayloadManager
+ .setPayloadData(link, mPayloadManager.pubLinkKey);
+ mPayloadManager.changePolicyTypeToStore(storeLink);
+ storeInfo.putAll(storeLink);
+ storeInfo.putAll(deviceInfo);
+ storeResourceInDB(storeInfo);
+ resourcePresence.add(storeInfo);
+ }
+ setmResourcePresence(resourcePresence);
+
+ }
+
+ private void storeResourceInDB(HashMap<String, Object> rdInfo) {
+ HashMap<String, Object> condition = new HashMap<>();
+ condition.put(Constants.DEVICE_ID, rdInfo.get(Constants.DEVICE_ID));
+ condition.put(Constants.INS, rdInfo.get(Constants.INS));
+ if (checkResourceExist(condition).isEmpty()) {
+ DBManager.getInstance().insertRecord(Constants.RD_TABLE, rdInfo);
+ // set resource presence
+ rdInfo.put(Constants.TRIGGER, Constants.RES_CREATE);
+ } else {
+ DBManager.getInstance().insertAndReplaceRecord(Constants.RD_TABLE,
+ rdInfo);
+ rdInfo.put(Constants.TRIGGER, Constants.RES_CHANGE);
+ }
+
+ }
+
+ private void setResourceIns(String di,
+ ArrayList<HashMap<String, Object>> links) {
+
+ for (HashMap<String, Object> link : links) {
+ String href = link.get(Constants.HREF).toString();
+ int ins = (int) link.get(Constants.INS);
+ int newIns = checkResourceIns(di, href, ins);
+ if (newIns == -1) {
+ throw new BadRequestException("resource ins is not correct");
+ }
+ link.put(Constants.INS, newIns);
+ }
+ }
+
+ private int checkResourceIns(String di, String href, int ins) {
+ int storedIns = mInsManager.getIns(di, href);
+ if (ins == 0) {
+ if (storedIns == -1) {
+ // create ins
+ ins = mInsManager.createIns(di);
+ } else {
+ ins = storedIns;
+ }
+ } else {
+ if (ins != storedIns) {
+ ins = -1;
+ }
+ }
+ return ins;
+ }
+
+ /**
+ * API for handling resource-delete process
+ *
+ * @param di
+ * device id
+ * @param ins
+ * unique id of resource
+ */
+ public void deleteResource(String di, List<String> insList) {
+
+ HashMap<String, Object> condition = new HashMap<>();
+ condition.put(Constants.DEVICE_ID, di);
+
+ ArrayList<HashMap<String, Object>> foundRecord = new ArrayList<>();
+
+ if (insList == null) {
+ foundRecord = checkResourceExist(condition);
+ DBManager.getInstance().deleteRecord(Constants.RD_TABLE, condition);
+ } else {
+ for (String ins : insList) {
+ condition.put(Constants.INS, Integer.parseInt(ins));
+ if (!checkResourceExist(condition).isEmpty()) {
+ foundRecord.add(checkResourceExist(condition).get(0));
+ DBManager.getInstance().deleteRecord(Constants.RD_TABLE,
+ condition);
+ }
+ }
+ }
+
+ if (!foundRecord.isEmpty()) {
+ setmResourcePresence(foundRecord);
+ }
+ }
+
+ private ArrayList<HashMap<String, Object>> checkResourceExist(
+ HashMap<String, Object> condition) {
+ ArrayList<HashMap<String, Object>> records = DBManager.getInstance()
+ .selectRecord(Constants.RD_TABLE, condition);
+
+ return records;
+ }
+
+ /**
+ * API for handling resource-discover process
+ *
+ * @param diList
+ * list of device id
+ * @param rtList
+ * list of resource type
+ * @param ifList
+ * list of resource interface
+ * @return response payload
+ */
+ public ArrayList<Object> discoverResource(List<String> diList,
+ List<String> rtList, List<String> ifList) {
+
+ HashMap<String, Object> condition = new HashMap<>();
+
+ ArrayList<Object> response = new ArrayList<>();
+
+ if (rtList == null && ifList == null) {
+ readResource(diList, condition, response);
+ }
+
+ if (rtList != null) {
+ for (String rt : rtList) {
+ condition.put(Constants.RESOURCE_TYPE, rt);
+ readResource(diList, condition, response);
+ }
+ }
+
+ if (ifList != null) {
+ for (String itf : ifList) {
+ condition.put(Constants.INTERFACE, itf);
+ readResource(diList, condition, response);
+ }
+ }
+
+ Log.d("discovery payload : " + response);
+
+ return response;
+ }
+
+ private void readResource(List<String> diList,
+ HashMap<String, Object> condition, ArrayList<Object> response) {
+
+ for (String di : diList) {
+ condition.put(Constants.DEVICE_ID, di);
+ ArrayList<HashMap<String, Object>> records = DBManager.getInstance()
+ .selectRecord(Constants.RD_TABLE, condition);
+
+ if (!records.isEmpty()) {
+ response.add(makeDiscoverResponseSegment(records));
+ }
+
+ }
+ }
+
+ private HashMap<String, Object> makeDiscoverResponseSegment(
+ ArrayList<HashMap<String, Object>> records) {
+
+ HashMap<String, Object> responseSegment = new HashMap<>();
+
+ // make Tags
+ HashMap<String, Object> discoverTag = mPayloadManager
+ .setPayloadData(records.get(0), mPayloadManager.discoverTagKey);
+ responseSegment.putAll(discoverTag);
+
+ ArrayList<Object> links = new ArrayList<>();
+ // make links
+ for (HashMap<String, Object> record : records) {
+ HashMap<String, Object> link = mPayloadManager
+ .setPayloadData(record, mPayloadManager.discoverLinkKey);
+ mPayloadManager.changePolicyTypeToDiscover(link);
+ links.add(link);
+ }
+ responseSegment.put(Constants.LINKS, links);
+
+ return responseSegment;
+
+ }
+
+ private void setmResourcePresence(
+ ArrayList<HashMap<String, Object>> resourcePresence) {
+ this.mResourcePresence = resourcePresence;
+ }
+
+ /**
+ * API for getting resource information to notify
+ *
+ * @return resource information
+ */
+ public ArrayList<HashMap<String, Object>> getmResourcePresence() {
+ return mResourcePresence;
+ }
+
+}
*/
package org.iotivity.cloud.rdserver.resources.directory.rd;
+import java.util.ArrayList;
import java.util.HashMap;
+import org.iotivity.cloud.rdserver.Constants;
import org.iotivity.cloud.rdserver.db.DBManager;
+/**
+ *
+ * This class provides a set of APIs to handle ins(unique value of resource)
+ *
+ */
public class InsManager {
private HashMap<String, Integer> mNextIns = new HashMap<>();
private int mInitialValue = 1;
+ /**
+ * API for getting ins from DB
+ *
+ * @param di
+ * device id
+ * @param href
+ * resource uri
+ * @return ins
+ */
public int getIns(String di, String href) {
- Object objectIns = DBManager.getInstance().findInsAboutDi(di, href);
- if (objectIns == null) {
- return 0;
- } else {
- return (int) objectIns;
+ HashMap<String, Object> condition = new HashMap<>();
+ condition.put(Constants.DEVICE_ID, di);
+ condition.put(Constants.HREF, href);
+ ArrayList<HashMap<String, Object>> records = DBManager.getInstance()
+ .selectRecord(Constants.RD_TABLE, condition);
+ if (records.isEmpty()) {
+ return -1;
+ } else {
+ return (int) (records.get(0).get(Constants.INS));
}
}
+ /**
+ * API for creating ins
+ *
+ * @param di
+ * device id
+ * @return created ins
+ */
public int createIns(String di) {
Object objectIns;
+++ /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.rdserver.resources.directory.rd;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-
-import org.iotivity.cloud.rdserver.Constants;
-
-public class PublishLinks {
- /** URI Reference */
- private String href;
- /** Relation between target URI and context URI */
- private String rel;
- /** Resource Types */
- private ArrayList<String> rt = new ArrayList<String>();
- /** Resource interface */
- private ArrayList<String> itf = new ArrayList<String>();
- /** policies that apply for resource */
- private Object p;
- /** Title for the link relation */
- private String title;
- /** This is used to override the context URI */
- private String anchor;
- /** An ordinal number that is not repeated */
- private int ins;
- /** Time to live for this link */
- private int ttl;
- /**
- * A hint of the media type of the representation of the resource referenced
- * by the target URI.
- */
- ArrayList<String> type = new ArrayList<String>();
-
- public PublishLinks copy() {
- PublishLinks links = new PublishLinks();
- links.href = this.href;
- links.rel = this.rel;
- links.rt.addAll(this.rt);
- links.itf.addAll(this.itf);
- links.p = this.p;
- links.title = this.title;
- links.anchor = this.anchor;
- links.ins = this.ins;
- links.ttl = this.ttl;
- return links;
- }
-
- public String getHref() {
- return href;
- }
-
- public void setHref(Object href) {
- this.href = href.toString();
- }
-
- public String getRel() {
- return rel;
- }
-
- public void setRel(Object rel) {
- this.rel = rel.toString();
- }
-
- public ArrayList<String> getRt() {
- return rt;
- }
-
- public void setRt(Object rt) {
- this.rt = (ArrayList<String>) rt;
- }
-
- public ArrayList<String> getItf() {
- return itf;
- }
-
- public void setItf(Object itf) {
- this.itf = (ArrayList<String>) itf;
- }
-
- public Object getP() {
- return p;
- }
-
- public void setP(Object p) {
- HashMap<Object, Object> bm = (HashMap<Object, Object>) p;
- this.p = bm.get(Constants.BITMAP);
- }
-
- public void changePType() {
- HashMap<Object, Object> bm = new HashMap<Object, Object>();
- bm.put(Constants.BITMAP, (int) p);
- this.p = bm;
- }
-
- public String getTitle() {
- return title;
- }
-
- public void setTitle(Object title) {
- this.title = title.toString();
- }
-
- public String getAnchor() {
- return anchor;
- }
-
- public void setAnchor(Object anchor) {
- this.anchor = anchor.toString();
- }
-
- public int getIns() {
- return ins;
- }
-
- public void setIns(Object ins) {
- this.ins = (int) ins;
- }
-
- public int getTtl() {
- return ttl;
- }
-
- public void setTtl(Object ttl) {
- this.ttl = (int) ttl;
- }
-
- public ArrayList<String> getType() {
- return type;
- }
-
- public void setType(Object type) {
- this.type = (ArrayList<String>) type;
- }
-
-}
+++ /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.rdserver.resources.directory.rd;
-
-import java.util.ArrayList;
-
-public class PublishPayload {
-
- private PublishTags tags = new PublishTags();
-
- private ArrayList<PublishLinks> links = new ArrayList<>();
-
- public PublishPayload copy() {
- PublishPayload pubPayload = new PublishPayload();
- pubPayload.tags = this.tags.copy();
-
- pubPayload.links = new ArrayList<>();
-
- for (PublishLinks link : this.links) {
- pubPayload.links.add(link.copy());
- }
-
- return pubPayload;
- }
-
- public PublishTags getTags() {
- return tags;
- }
-
- public void setTags(PublishTags tags) {
- this.tags = tags;
- }
-
- public ArrayList<PublishLinks> getLinks() {
- return links;
- }
-
- public void setLinks(ArrayList<PublishLinks> links) {
- this.links = links;
- }
-}
+++ /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.rdserver.resources.directory.rd;
-
-public class PublishTags {
- /** An unique identifier of device */
- private String di;
- /** A human friendly name of device */
- private String n;
- /** Time (in seconds) to indicate how long RD should publish this item */
- private int lt;
-
- public PublishTags copy() {
- PublishTags tags = new PublishTags();
- tags.di = this.di;
- tags.n = this.n;
- tags.lt = this.lt;
- return tags;
- }
-
- public String getDi() {
- return di;
- }
-
- public void setDi(Object di) {
- this.di = di.toString();
- }
-
- public String getN() {
- return n;
- }
-
- public void setN(Object n) {
- this.n = n.toString();
- }
-
- public int getLt() {
- return lt;
- }
-
- public void setLt(Object lt) {
- this.lt = (int) lt;
- }
-}
import org.iotivity.cloud.base.protocols.enums.ResponseStatus;
import org.iotivity.cloud.base.resource.Resource;
import org.iotivity.cloud.rdserver.Constants;
-import org.iotivity.cloud.rdserver.db.DBManager;
-import org.iotivity.cloud.rdserver.resources.presence.ResPresenceManager;
-import org.iotivity.cloud.rdserver.resources.presence.resource.ResPresencePayload;
-import org.iotivity.cloud.rdserver.util.TypeCastingManager;
+import org.iotivity.cloud.rdserver.resources.directory.RDManager;
+import org.iotivity.cloud.rdserver.resources.presence.PresenceManager;
import org.iotivity.cloud.util.Cbor;
import org.iotivity.cloud.util.Log;
+/**
+ *
+ * This class provides a set of APIs handle requests about resource directory
+ *
+ */
public class ResourceDirectoryResource extends Resource {
- private Cbor<HashMap<Object, Object>> mCbor = new Cbor<>();
- private TypeCastingManager<PublishTags> mPublishTagsTypeManager = new TypeCastingManager<>();
- private TypeCastingManager<PublishLinks> mPublishLinksTypeManager = new TypeCastingManager<>();
- private InsManager mInsManager = new InsManager();
- private String mNotiDeviceId = null;
- private ArrayList<ResPresencePayload> mNotiPayloadList = new ArrayList<ResPresencePayload>();
+ private Cbor<HashMap<String, Object>> mCbor = new Cbor<>();
+ private RDManager mRdManager = new RDManager();
public ResourceDirectoryResource() {
super(Arrays.asList(Constants.PREFIX_OIC, Constants.RD_URI));
break;
default:
- throw new BadRequestException(request.getMethod()
- + " request type is not supported");
+ throw new BadRequestException(
+ request.getMethod() + " request type is not supported");
}
srcDevice.sendResponse(response);
- ResPresenceManager.getInstance().notifyToObservers(mNotiDeviceId,
- mNotiPayloadList);
+ PresenceManager.getInstance()
+ .notifyToObservers(mRdManager.getmResourcePresence());
}
- private IResponse handlePostRequest(IRequest request)
- throws ServerException {
-
- HashMap<String, List<String>> queryMap = request.getUriQueryMap();
-
- byte[] encodedPayload = null;
-
- if (queryMap == null) {
- throw new PreconditionFailedException("query is null");
- }
-
- List<String> listRT = queryMap.get(Constants.RESOURCE_TYPE);
-
- if (listRT == null) {
- throw new PreconditionFailedException("rt property is not include");
- } else if (listRT.get(0).equals(Constants.RESOURCE_TYPE_RDPUBLISH)) {
-
- PublishPayload pubPayload = parsingPublishPayload(request
- .getPayload());
+ private void checkLinksProperty(HashMap<String, Object> payload) {
- mNotiDeviceId = pubPayload.getTags().getDi();
-
- // PublishPayload copyPubPayload = pubPayload.copy();
-
- // ArrayList<HashMap<Object, Object>> storeResList =
- // creatDBStoreResource(changeResourceUri(copyPubPayload));
-
- ArrayList<HashMap<Object, Object>> storeResList = creatDBStoreResource(pubPayload);
-
- mNotiPayloadList = DBManager.getInstance().registerResource(
- storeResList);
-
- encodedPayload = createPublishResponse(pubPayload);
-
- } else {
- throw new PreconditionFailedException(
- "rt property is not rd publish");
+ Object links = payload.get(Constants.LINKS);
+ if (links == null) {
+ throw new BadRequestException("links property is null");
}
-
- return MessageBuilder.createResponse(request, ResponseStatus.CHANGED,
- ContentFormat.APPLICATION_CBOR, encodedPayload);
- }
-
- private byte[] createPublishResponse(PublishPayload pubPayload) {
- HashMap<Object, Object> responseMap = new HashMap<Object, Object>();
-
- PublishTags tags = pubPayload.getTags();
- responseMap.putAll(mPublishTagsTypeManager.convertObjectToMap(tags));
-
- ArrayList<PublishLinks> pubLinksList = pubPayload.getLinks();
-
- ArrayList<HashMap<Object, Object>> links = new ArrayList<HashMap<Object, Object>>();
-
- for (PublishLinks pubLinks : pubLinksList) {
- mPublishLinksTypeManager.callMethod("changePType", pubLinks);
- links.add(mPublishLinksTypeManager.convertObjectToMap(pubLinks));
+ ArrayList<HashMap<String, Object>> linksList = (ArrayList<HashMap<String, Object>>) links;
+ for (HashMap<String, Object> link : linksList) {
+ checkPayloadException(
+ Arrays.asList(Constants.HREF, Constants.RESOURCE_TYPE,
+ Constants.INS, Constants.INTERFACE),
+ link);
}
- responseMap.put(Constants.LINKS, links);
-
- Log.i("publish response :" + responseMap.toString());
-
- byte[] encodedPaylod = mCbor.encodingPayloadToCbor(responseMap);
-
- return encodedPaylod;
}
- private PublishPayload parsingPublishPayload(byte[] payload)
+ private IResponse handlePostRequest(IRequest request)
throws ServerException {
- HashMap<Object, Object> payloadData = mCbor.parsePayloadFromCbor(
- payload, HashMap.class);
-
- if (payloadData == null) {
- throw new BadRequestException("payload is null");
- } else {
- Log.i("publish payload: " + payloadData.toString());
- }
+ HashMap<String, List<String>> queryMap = request.getUriQueryMap();
- PublishTags tags = new PublishTags();
- tags = mPublishTagsTypeManager.convertMaptoObject(payloadData, tags);
-
- String di = tags.getDi();
-
- ArrayList<HashMap<Object, Object>> linksList = (ArrayList<HashMap<Object, Object>>) payloadData
- .get(Constants.LINKS);
-
- ArrayList<PublishLinks> pubLinksList = new ArrayList<PublishLinks>();
-
- for (HashMap<Object, Object> links : linksList) {
- PublishLinks pubLinks = new PublishLinks();
- pubLinks = mPublishLinksTypeManager.convertMaptoObject(links,
- pubLinks);
- String href = pubLinks.getHref();
- // href = "/di/" + di + href;
- int ins = pubLinks.getIns();
- ins = checkResourceIns(di, href, ins);
- if (ins == 0) {
- throw new PreconditionFailedException("ins is null");
- }
- pubLinks.setIns(ins);
- pubLinksList.add(pubLinks);
- }
+ checkQueryException(Arrays.asList(Constants.RESOURCE_TYPE), queryMap);
- PublishPayload pubPayload = new PublishPayload();
- pubPayload.setTags(tags);
- pubPayload.setLinks(pubLinksList);
+ List<String> listRT = queryMap.get(Constants.RESOURCE_TYPE);
- return pubPayload;
- }
+ // check query "rt=oic.rd.pub"
+ if (!listRT.get(0).equals(Constants.RESOURCE_TYPE_RDPUBLISH)) {
+ throw new PreconditionFailedException("rt property is not correct");
+ }
- private PublishPayload changeResourceUri(PublishPayload pubPayload) {
+ HashMap<String, Object> payload = mCbor
+ .parsePayloadFromCbor(request.getPayload(), HashMap.class);
- String di = pubPayload.getTags().getDi();
+ Log.d("publish payload : " + payload);
- for (PublishLinks links : pubPayload.getLinks()) {
- String originHref = links.getHref();
- links.setHref("/di/" + di + originHref);
- }
+ checkPayloadException(
+ Arrays.asList(Constants.DEVICE_ID, Constants.LINKS), payload);
- return pubPayload;
- }
+ // check mandatory property
+ checkLinksProperty(payload);
- private int checkResourceIns(String di, String href, int ins) {
- int storedIns = mInsManager.getIns(di, href);
- if (ins == 0) {
- if (storedIns == 0) {
- ins = mInsManager.createIns(di);
- } else {
- ins = storedIns;
- }
- } else {
- if (ins != storedIns) {
- ins = 0;
- }
- }
- return ins;
- }
+ HashMap<String, Object> response = mRdManager.publishResource(payload);
- private ArrayList<HashMap<Object, Object>> creatDBStoreResource(
- PublishPayload pubPayload) {
- PublishTags tags = pubPayload.getTags();
- ArrayList<PublishLinks> linksList = pubPayload.getLinks();
+ Log.d("publish response : " + response);
- ArrayList<HashMap<Object, Object>> storeResList = new ArrayList<HashMap<Object, Object>>();
- HashMap<Object, Object> storeTags = mPublishTagsTypeManager
- .convertObjectToMap(tags);
+ return MessageBuilder.createResponse(request, ResponseStatus.CHANGED,
+ ContentFormat.APPLICATION_CBOR,
+ mCbor.encodingPayloadToCbor(response));
- for (PublishLinks links : linksList) {
- HashMap<Object, Object> storeRes = new HashMap<Object, Object>();
- storeRes.putAll(storeTags);
- storeRes.putAll(mPublishLinksTypeManager.convertObjectToMap(links));
- storeResList.add(storeRes);
- }
- return storeResList;
}
private IResponse handleDeleteRequest(IRequest request)
throws ServerException {
HashMap<String, List<String>> queryMap = request.getUriQueryMap();
- List<String> diList = null;
- List<String> insList = null;
-
- if (queryMap == null) {
- throw new PreconditionFailedException("query is null");
- } else {
- diList = queryMap.get(Constants.DEVICE_ID);
- insList = queryMap.get(Constants.INS);
-
- if (diList == null) {
- throw new PreconditionFailedException(
- "di property is not include");
- } else {
- String di = diList.get(0);
- mNotiDeviceId = di;
-
- if (insList == null) {
- mNotiPayloadList = DBManager.getInstance()
- .deleteResourceAboutDi(di);
-
- } else {
- String ins = insList.get(0);
- mNotiPayloadList = DBManager.getInstance()
- .deleteResourceAboutDiAandIns(di, ins);
- }
- }
- }
+
+ checkQueryException(Arrays.asList(Constants.DEVICE_ID), queryMap);
+
+ List<String> diList = queryMap.get(Constants.DEVICE_ID);
+ List<String> insList = queryMap.get(Constants.INS);
+
+ mRdManager.deleteResource(diList.get(0), insList);
IResponse response = MessageBuilder.createResponse(request,
ResponseStatus.DELETED);
return response;
}
+
}
+++ /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.rdserver.resources.directory.res;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-
-import org.iotivity.cloud.rdserver.Constants;
-
-public class DiscoveryLinks {
- /** URI Reference */
- private String href;
- /** Resource Types */
- private ArrayList<String> rt = new ArrayList<>();
- /** Resource interface */
- private ArrayList<String> itf = new ArrayList<>();
- /** policies that apply for resource */
- private HashMap<Object, Object> p = new HashMap<>();
-
- public DiscoveryLinks() {
-
- }
-
- public String getHref() {
- return href;
- }
-
- public void setHref(Object href) {
- this.href = href.toString();
- }
-
- public ArrayList<String> getRt() {
- return rt;
- }
-
- public void setRt(Object rt) {
- this.rt = (ArrayList<String>) rt;
- }
-
- public ArrayList<String> getItf() {
- return itf;
- }
-
- public void setItf(Object itf) {
- this.itf = (ArrayList<String>) itf;
- }
-
- public Object getP() {
- return p;
- }
-
- public void setP(Object p) {
- int bm = (int) p;
- this.p.put(Constants.BITMAP, bm);
- }
-}
+++ /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.rdserver.resources.directory.res;
-
-import java.util.ArrayList;
-
-public class DiscoveryPayload {
-
- private DiscoveryTags tags = new DiscoveryTags();
-
- private ArrayList<DiscoveryLinks> links = new ArrayList<>();
-
- public DiscoveryPayload() {
-
- }
-
- public DiscoveryTags getTags() {
- return tags;
- }
-
- public void setTags(DiscoveryTags tags) {
- this.tags = tags;
- }
-
- public ArrayList<DiscoveryLinks> getLinks() {
- return links;
- }
-
- public void setLinks(ArrayList<DiscoveryLinks> links) {
- this.links = links;
- }
-
-}
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.ResponseStatus;
import org.iotivity.cloud.base.resource.Resource;
import org.iotivity.cloud.rdserver.Constants;
-import org.iotivity.cloud.rdserver.db.DBManager;
-import org.iotivity.cloud.rdserver.util.TypeCastingManager;
+import org.iotivity.cloud.rdserver.resources.directory.RDManager;
import org.iotivity.cloud.util.Cbor;
-import org.iotivity.cloud.util.Log;
+/**
+ *
+ * This class provides a set of APIs handle requests about resource discovery
+ *
+ */
public class DiscoveryResource extends Resource {
- private Cbor<HashMap<Object, Object>> mCbor = new Cbor<>();
- private TypeCastingManager<DiscoveryTags> mDiscoveryTagsTypeManager = new TypeCastingManager<>();
- private TypeCastingManager<DiscoveryLinks> mDiscoveryLinkTypeManager = new TypeCastingManager<>();
+ private Cbor<ArrayList<Object>> mCbor = new Cbor<>();
+ private RDManager mRdManager = new RDManager();
public DiscoveryResource() {
super(Arrays.asList(Constants.PREFIX_OIC, Constants.WELL_KNOWN_URI));
HashMap<String, List<String>> queryMap = request.getUriQueryMap();
- ArrayList<DiscoveryPayload> resourceList = new ArrayList<DiscoveryPayload>();
-
- if (queryMap == null) {
- throw new PreconditionFailedException("query is null");
- }
-
- List<String> deviceList = queryMap.get(Constants.DEVICE_ID);
-
- if (deviceList == null) {
- throw new PreconditionFailedException(
- "di property is not included");
- }
-
- List<String> listRT = queryMap.get(Constants.RESOURCE_TYPE);
- List<String> listITF = queryMap.get(Constants.INTERFACE);
- String key = null, value = null;
- ArrayList<HashMap<Object, Object>> foundResList = null;
-
- // TODO: Multiple RT or ITF support required
- if (listRT != null) {
- key = Constants.RESOURCE_TYPE;
- value = listRT.get(0);
- } else if (listITF != null) {
- key = Constants.INTERFACE;
- value = listITF.get(0);
- }
+ List<String> diList = queryMap.get(Constants.DEVICE_ID);
+ List<String> rtList = queryMap.get(Constants.RESOURCE_TYPE);
+ List<String> ifList = queryMap.get(Constants.INTERFACE);
- for (String deviceId : deviceList) {
- if(key != null && value != null){
- foundResList = DBManager.getInstance().findResourceAboutDiAndFilter(deviceId,
- key, value);
- } else {
- foundResList = DBManager.getInstance().findResourceAboutDi(deviceId);
- }
-
- if (foundResList != null) {
- resourceList.add(makeDiscoveryPayloadSegment(foundResList));
- }
- }
+ ArrayList<Object> response = mRdManager.discoverResource(diList, rtList,
+ ifList);
return MessageBuilder.createResponse(request, ResponseStatus.CONTENT,
ContentFormat.APPLICATION_CBOR,
- createDiscoveryResponse(resourceList));
+ mCbor.encodingPayloadToCbor(response));
}
- private DiscoveryPayload makeDiscoveryPayloadSegment(
- ArrayList<HashMap<Object, Object>> foundResList) {
-
- ArrayList<DiscoveryLinks> discoveryLinksList = new ArrayList<DiscoveryLinks>();
-
- for (HashMap<Object, Object> res : foundResList) {
- DiscoveryLinks discoveryLinksPayload = new DiscoveryLinks();
- discoveryLinksPayload = mDiscoveryLinkTypeManager
- .convertMaptoObject(res, discoveryLinksPayload);
- discoveryLinksList.add(discoveryLinksPayload);
- }
-
- DiscoveryPayload discoveryPayload = new DiscoveryPayload();
-
- DiscoveryTags tagsPayload = new DiscoveryTags();
-
- tagsPayload = mDiscoveryTagsTypeManager
- .convertMaptoObject(foundResList.get(0), tagsPayload);
-
- discoveryPayload.setTags(tagsPayload);
- discoveryPayload.setLinks(discoveryLinksList);
-
- return discoveryPayload;
- }
-
- private byte[] createDiscoveryResponse(
- ArrayList<DiscoveryPayload> discoveryPayloadList) {
- ArrayList<HashMap<Object, Object>> responseMapList = new ArrayList<HashMap<Object, Object>>();
-
- for (DiscoveryPayload discoveryPayload : discoveryPayloadList) {
-
- DiscoveryTags tags = discoveryPayload.getTags();
-
- HashMap<Object, Object> responseSegment = mDiscoveryTagsTypeManager
- .convertObjectToMap(tags);
-
- ArrayList<DiscoveryLinks> discoveryLinksList = discoveryPayload
- .getLinks();
-
- ArrayList<HashMap<Object, Object>> links = new ArrayList<HashMap<Object, Object>>();
-
- for (DiscoveryLinks discoveryLinks : discoveryLinksList) {
- links.add(mDiscoveryLinkTypeManager
- .convertObjectToMap(discoveryLinks));
- }
- responseSegment.put(Constants.LINKS, links);
-
- responseMapList.add(responseSegment);
- }
-
- Log.i("discover payload :" + responseMapList.toString());
-
- byte[] encodedPaylod = mCbor.encodingPayloadToCbor(responseMapList);
-
- return encodedPaylod;
- }
}
+++ /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.rdserver.resources.directory.res;
-
-public class DiscoveryTags {
- /** An unique identifier of device */
- private String di;
- /** A human friendly name of device */
- private String n;
-
- public String getDi() {
- return di;
- }
-
- public void setDi(Object di) {
- this.di = di.toString();
- }
-
- public String getN() {
- return n;
- }
-
- public void setN(Object n) {
- this.n = n.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.rdserver.resources.presence;
+
+import java.io.ByteArrayOutputStream;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+
+import org.iotivity.cloud.base.device.Device;
+import org.iotivity.cloud.base.exception.ServerException.InternalServerErrorException;
+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.rdserver.Constants;
+import org.iotivity.cloud.rdserver.db.DBManager;
+import org.iotivity.cloud.util.Cbor;
+import org.iotivity.cloud.util.Log;
+
+import com.fasterxml.jackson.core.JsonEncoding;
+import com.fasterxml.jackson.core.JsonGenerator;
+import com.fasterxml.jackson.dataformat.cbor.CBORFactory;
+import com.fasterxml.jackson.dataformat.cbor.CBORGenerator;
+
+/**
+ *
+ * This class provides a set of APIs handle requests about presence
+ *
+ */
+public class PresenceManager {
+ private static PresenceManager mPresenceManager = new PresenceManager();
+
+ private Cbor<HashMap<String, Object>> mCbor = new Cbor<>();
+
+ private class PresenceSubscriber {
+ PresenceSubscriber(Device subscriber, IRequest request) {
+ mSubscriber = subscriber;
+ mRequest = request;
+ }
+
+ public Device mSubscriber;
+ public IRequest mRequest;
+ }
+
+ private class PresenceInfo {
+
+ PresenceInfo() {
+ mSubscriber = new HashMap<>();
+ mSubscribedDevices = new HashMap<>();
+ mSequenceNumber = new HashMap<>();
+ }
+
+ // di , token, Subscriber list
+ private HashMap<String, HashMap<String, PresenceSubscriber>> mSubscriber;
+ // token, di list
+ private HashMap<String, List<String>> mSubscribedDevices;
+ private HashMap<String, Long> mSequenceNumber;
+ }
+
+ private PresenceInfo mDevicePresence = null;
+ private PresenceInfo mResourcePresence = null;
+
+ private PresenceManager() {
+ mDevicePresence = new PresenceInfo();
+ mResourcePresence = new PresenceInfo();
+ }
+
+ /**
+ * API to return PresenceManager object
+ *
+ * @return PresenceManager object
+ */
+ public static PresenceManager getInstance() {
+ return mPresenceManager;
+ }
+
+ /**
+ * API to add observer
+ *
+ * @param srcDevice
+ * channel information
+ * @param request
+ * request message
+ * @param deviceIdList
+ * subscribed device list
+ * @param presenceType
+ * device presence or resource presence
+ */
+ public void subscribePresence(Device srcDevice, IRequest request,
+ List<String> deviceIdList, String presenceType) {
+
+ PresenceInfo presenceInfo = getPresenceInfo(presenceType);
+
+ for (String deviceId : deviceIdList) {
+ HashMap<String, PresenceSubscriber> subscribers = presenceInfo.mSubscriber
+ .get(deviceId);
+
+ if (subscribers == null) {
+ subscribers = new HashMap<>();
+ presenceInfo.mSubscriber.put(deviceId, subscribers);
+ }
+
+ subscribers.put(request.getRequestId(),
+ new PresenceSubscriber(srcDevice, request));
+ }
+
+ presenceInfo.mSubscribedDevices.put(request.getRequestId(),
+ deviceIdList);
+ presenceInfo.mSequenceNumber.put(request.getRequestId(), (long) 1);
+ }
+
+ /**
+ * API to remove observer
+ *
+ * @param request
+ * request message
+ * @param deviceIdList
+ * unsubscribed device list
+ * @param presenceType
+ * device presence or resource presence
+ */
+ public void unsubscribePresence(IRequest request, List<String> deviceIdList,
+ String presenceType) {
+
+ PresenceInfo presenceInfo = getPresenceInfo(presenceType);
+
+ for (String deviceId : deviceIdList) {
+ HashMap<String, PresenceSubscriber> subscribers = presenceInfo.mSubscriber
+ .get(deviceId);
+
+ if (subscribers == null) {
+ continue;
+ }
+
+ subscribers.remove(request.getRequestId());
+ }
+ }
+
+ /**
+ * API for notifying to observers about device presence
+ *
+ * @param deviceId
+ * device id
+ */
+ public void notifyToObservers(String deviceId) {
+
+ HashMap<String, PresenceSubscriber> tokenNSubscribers = mDevicePresence.mSubscriber
+ .get(deviceId);
+
+ if (tokenNSubscribers != null) {
+ byte[] payload = makeResponsePayload(Arrays.asList(deviceId));
+
+ for (PresenceSubscriber subscriber : tokenNSubscribers.values()) {
+
+ subscriber.mSubscriber.sendResponse(
+ MessageBuilder.createResponse(subscriber.mRequest,
+ ResponseStatus.CONTENT,
+ ContentFormat.APPLICATION_CBOR, payload));
+ }
+ }
+ }
+
+ /**
+ * API to make response payload about device presence
+ *
+ * @param deviceList
+ * device id list
+ * @return payload data
+ */
+ public byte[] makeResponsePayload(List<String> deviceList) {
+
+ HashMap<String, Object> getPayload = new HashMap<>();
+ ArrayList<HashMap<String, Object>> prsList = new ArrayList<>();
+
+ for (String deviceId : deviceList) {
+ HashMap<String, Object> payloadSegment = new HashMap<>();
+
+ String deviceState = getDeviceState(deviceId);
+ if (deviceState != null) {
+ payloadSegment.put(Constants.DEVICE_ID, deviceId);
+ payloadSegment.put(Constants.PRESENCE_STATE, deviceState);
+ prsList.add(payloadSegment);
+ }
+ }
+ getPayload.put(Constants.PRESENCE_LIST, prsList);
+ Log.i("Device presence observe response : " + getPayload.toString());
+
+ return mCbor.encodingPayloadToCbor(getPayload);
+
+ }
+
+ private String getDeviceState(String deviceId) {
+
+ HashMap<String, Object> condition = new HashMap<>();
+ condition.put(Constants.DEVICE_ID, deviceId);
+
+ String state = null;
+
+ ArrayList<HashMap<String, Object>> readRecords = DBManager.getInstance()
+ .selectRecord(Constants.PRESENCE_TABLE, condition);
+
+ if (!readRecords.isEmpty()
+ && readRecords.get(0).get(Constants.PRESENCE_STATE) != null) {
+ state = readRecords.get(0).get(Constants.PRESENCE_STATE).toString();
+ }
+
+ return state;
+ }
+
+ private PresenceInfo getPresenceInfo(String presenceType) {
+
+ PresenceInfo presenceInfo = null;
+ switch (presenceType) {
+ case Constants.DEVICE_PRESENCE:
+ presenceInfo = mDevicePresence;
+ break;
+ case Constants.RESOURCE_PRESENCE:
+ presenceInfo = mResourcePresence;
+ break;
+ default:
+ }
+ return presenceInfo;
+ }
+
+ /**
+ * API for notifying to observers about resource presence
+ *
+ * @param resourceInfo
+ * resource information
+ */
+ public void notifyToObservers(
+ ArrayList<HashMap<String, Object>> resourceInfo) {
+
+ if (resourceInfo.isEmpty()) {
+ return;
+ }
+
+ Object obj = resourceInfo.get(0).get(Constants.DEVICE_ID);
+
+ if (obj == null) {
+ return;
+ }
+
+ String deviceId = obj.toString();
+
+ HashMap<String, PresenceSubscriber> tokenNSubscribers = mResourcePresence.mSubscriber
+ .get(deviceId);
+
+ if (tokenNSubscribers != null) {
+
+ for (PresenceSubscriber subscriber : tokenNSubscribers.values()) {
+
+ for (HashMap<String, Object> resource : resourceInfo) {
+ subscriber.mSubscriber.sendResponse(
+ MessageBuilder.createResponse(subscriber.mRequest,
+ ResponseStatus.CONTENT,
+ ContentFormat.APPLICATION_CBOR,
+ makeResponsePayload(
+ subscriber.mRequest.getRequestId(),
+ resource)));
+ }
+ }
+ }
+ }
+
+ private byte[] makeResponsePayload(String requestId,
+ HashMap<String, Object> resource) {
+
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ CBORFactory f = new CBORFactory();
+ try {
+ JsonGenerator gen = f.createGenerator(out, JsonEncoding.UTF8);
+ gen.writeStartObject();
+ long sequenceId = mResourcePresence.mSequenceNumber.get(requestId);
+ gen.writeNumberField(Constants.NON, sequenceId);
+ mResourcePresence.mSequenceNumber.put(requestId, sequenceId + 1);
+ gen.writeNumberField(Constants.RESOURCE_TTL, Long.parseLong(
+ checkPayload(resource, Constants.RESOURCE_TTL).toString()));
+
+ gen.writeFieldName(Constants.TRIGGER);
+
+ ((CBORGenerator) gen).writeRaw((byte) (224
+ + (byte) (checkPayload(resource, Constants.TRIGGER))));
+
+ gen.writeStringField(Constants.RESOURCE_TYPE,
+ checkPayload(resource, Constants.RESOURCE_TYPE).toString());
+
+ gen.writeStringField(Constants.HREF,
+ checkPayload(resource, Constants.HREF).toString());
+ gen.writeEndObject();
+
+ gen.close();
+ } catch (Exception e) {
+ throw new InternalServerErrorException(
+ "notification payload cbor encoding error");
+ }
+
+ return out.toByteArray();
+ }
+
+ private Object checkPayload(HashMap<String, Object> resource, String key) {
+ Object obj = resource.get(key);
+
+ if (obj == null) {
+ throw new InternalServerErrorException(
+ "property (" + key + ") is null");
+ }
+
+ return obj;
+ }
+
+ /**
+ * API to update device state
+ *
+ * @param payload
+ * payload included device state
+ */
+ public void updateDevicePresence(HashMap<String, Object> payload) {
+ DBManager.getInstance().insertAndReplaceRecord(Constants.PRESENCE_TABLE,
+ payload);
+ }
+}
+++ /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.rdserver.resources.presence;
-
-import java.io.ByteArrayOutputStream;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-
-import org.iotivity.cloud.base.device.Device;
-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.rdserver.Constants;
-import org.iotivity.cloud.rdserver.resources.presence.resource.ResPresencePayload;
-
-import com.fasterxml.jackson.core.JsonEncoding;
-import com.fasterxml.jackson.core.JsonGenerator;
-import com.fasterxml.jackson.dataformat.cbor.CBORFactory;
-import com.fasterxml.jackson.dataformat.cbor.CBORGenerator;
-
-public class ResPresenceManager {
-
- public static ResPresenceManager mResPresenceManager = new ResPresenceManager();
-
- private class PresenceSubscriber {
- PresenceSubscriber(Device subscriber, IRequest request) {
- mSubscriber = subscriber;
- mRequest = request;
- }
-
- public Device mSubscriber;
- public IRequest mRequest;
- }
-
- // di , token, Subscriber list
- private HashMap<String, HashMap<String, PresenceSubscriber>> mDeviceSubscriber = null;
- // token, di list
- private HashMap<String, List<String>> mSubscribedDevices = null;
-
- private HashMap<String, Long> mSubscriberSequenceNumber = null;
-
- public ResPresenceManager() {
-
- mDeviceSubscriber = new HashMap<>();
- mSubscribedDevices = new HashMap<>();
- mSubscriberSequenceNumber = new HashMap<>();
- }
-
- public static ResPresenceManager getInstance() {
- return mResPresenceManager;
- }
-
- public void addObserver(Device srcDevice, IRequest request,
- List<String> deviceIdList) {
-
- for (String deviceId : deviceIdList) {
- HashMap<String, PresenceSubscriber> subscribers = mDeviceSubscriber
- .get(deviceId);
-
- if (subscribers == null) {
- subscribers = new HashMap<>();
- mDeviceSubscriber.put(deviceId, subscribers);
- }
-
- subscribers.put(request.getRequestId(),
- new PresenceSubscriber(srcDevice, request));
- }
-
- mSubscribedDevices.put(request.getRequestId(), deviceIdList);
- mSubscriberSequenceNumber.put(request.getRequestId(), (long) 1);
-
- return;
- }
-
- public void removeObserver(IRequest request) {
-
- List<String> deviceIdList = mSubscribedDevices
- .get(request.getRequestId());
-
- if (deviceIdList == null) {
- return;
- }
-
- for (String deviceId : deviceIdList) {
- HashMap<String, PresenceSubscriber> subscribers = mDeviceSubscriber
- .get(deviceId);
-
- if (subscribers == null) {
- continue;
- }
-
- subscribers.remove(request.getRequestId());
- }
- }
-
- public void notifyToObservers(String deviceId,
- ArrayList<ResPresencePayload> resPayloadList) {
-
- HashMap<String, PresenceSubscriber> tokenNSubscribers = mDeviceSubscriber
- .get(deviceId);
-
- if (tokenNSubscribers != null) {
-
- for (PresenceSubscriber subscriber : tokenNSubscribers.values()) {
-
- for (ResPresencePayload resPayload : resPayloadList) {
- subscriber.mSubscriber.sendResponse(
- MessageBuilder.createResponse(subscriber.mRequest,
- ResponseStatus.CONTENT,
- ContentFormat.APPLICATION_CBOR,
- makeResponsePayload(
- subscriber.mRequest.getRequestId(),
- resPayload)));
- }
-
- }
- }
- }
-
- private byte[] makeResponsePayload(String requestId,
- ResPresencePayload resPayload) {
-
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- CBORFactory f = new CBORFactory();
- try {
- JsonGenerator gen = f.createGenerator(out, JsonEncoding.UTF8);
- gen.writeStartObject();
- long sequenceId = mSubscriberSequenceNumber.get(requestId);
- gen.writeNumberField(Constants.RS_NON, sequenceId);
- mSubscriberSequenceNumber.put(requestId, sequenceId + 1);
- gen.writeNumberField(Constants.RESOURCE_TTL,
- (long) resPayload.getTtl());
-
- gen.writeFieldName(Constants.RS_TRIGGER);
-
- ((CBORGenerator) gen).writeRaw((byte) (224 + resPayload.getTrg()));
-
- gen.writeStringField(Constants.RESOURCE_TYPE, resPayload.getRt());
-
- gen.writeStringField(Constants.HREF, resPayload.getHref());
- gen.writeEndObject();
-
- gen.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- return out.toByteArray();
- }
-}
*/
package org.iotivity.cloud.rdserver.resources.presence.device;
-import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import org.iotivity.cloud.base.protocols.enums.ResponseStatus;
import org.iotivity.cloud.base.resource.Resource;
import org.iotivity.cloud.rdserver.Constants;
-import org.iotivity.cloud.rdserver.db.DBManager;
-import org.iotivity.cloud.rdserver.util.TypeCastingManager;
+import org.iotivity.cloud.rdserver.resources.presence.PresenceManager;
import org.iotivity.cloud.util.Cbor;
-import org.iotivity.cloud.util.Log;
+/**
+ *
+ * This class provides a set of APIs handle requests about device presence
+ *
+ */
public class DevicePresenceResource extends Resource {
private Cbor<HashMap<String, Object>> mCbor = new Cbor<>();
- private class PresenceSubscriber {
- PresenceSubscriber(Device subscriber, IRequest request) {
- mSubscriber = subscriber;
- mRequest = request;
- }
-
- public Device mSubscriber;
- public IRequest mRequest;
- }
-
- // di , token, Subscriber list
- private HashMap<String, HashMap<String, PresenceSubscriber>> mDeviceSubscriber = null;
- // token, di list
- private HashMap<String, List<String>> mSubscribedDevices = null;
-
public DevicePresenceResource() {
super(Arrays.asList(Constants.PREFIX_OIC,
Constants.DEVICE_PRESENCE_URI));
- mDeviceSubscriber = new HashMap<>();
- mSubscribedDevices = new HashMap<>();
}
@Override
throws ServerException {
HashMap<String, List<String>> queryMap = request.getUriQueryMap();
- byte[] payload = null;
+ checkQueryException(Arrays.asList(Constants.DEVICE_ID), queryMap);
- if (checkQueryException(Arrays.asList(Constants.DEVICE_ID), queryMap)) {
+ List<String> deviceList = queryMap.get(Constants.DEVICE_ID);
- List<String> deviceList = queryMap.get(Constants.DEVICE_ID);
-
- switch (request.getObserve()) {
- case SUBSCRIBE:
- addObserver(srcDevice, request, deviceList);
- break;
- case UNSUBSCRIBE:
- removeObserver(request);
- break;
- default:
- }
-
- payload = makeResponsePayload(deviceList);
+ switch (request.getObserve()) {
+ case SUBSCRIBE:
+ PresenceManager.getInstance().subscribePresence(srcDevice,
+ request, deviceList, Constants.DEVICE_PRESENCE);
+ break;
+ case UNSUBSCRIBE:
+ PresenceManager.getInstance().unsubscribePresence(request,
+ deviceList, Constants.DEVICE_PRESENCE);
+ break;
+ default:
}
+ byte[] payload = PresenceManager.getInstance()
+ .makeResponsePayload(deviceList);
+
return MessageBuilder.createResponse(request, ResponseStatus.CONTENT,
ContentFormat.APPLICATION_CBOR, payload);
+
}
- public IResponse handlePostRequest(IRequest request)
+ private IResponse handlePostRequest(IRequest request)
throws ServerException {
// check payload
byte[] payload = request.getPayload();
HashMap<String, Object> parsedPayload = mCbor
.parsePayloadFromCbor(payload, HashMap.class);
- if (checkPayloadException(
+ checkPayloadException(
Arrays.asList(Constants.DEVICE_ID, Constants.PRESENCE_STATE),
- parsedPayload)) {
-
- String deviceId = parsedPayload.get(Constants.DEVICE_ID).toString();
- String state = parsedPayload.get(Constants.PRESENCE_STATE)
- .toString();
- DeviceState deviceState = new DeviceState();
- deviceState.setDi(deviceId);
- deviceState.setState(state);
+ parsedPayload);
- TypeCastingManager<DeviceState> deviceStateTypeManager = new TypeCastingManager<DeviceState>();
- HashMap<Object, Object> storeMap = deviceStateTypeManager
- .convertObjectToMap(deviceState);
+ // store db
+ PresenceManager.getInstance().updateDevicePresence(parsedPayload);
- // store db
- DBManager.getInstance().updateDeviceState(storeMap);
-
- // notification to observers
- notifyToObservers(deviceId);
- }
+ // notification to observers
+ String di = parsedPayload.get(Constants.DEVICE_ID).toString();
+ PresenceManager.getInstance().notifyToObservers(di);
return MessageBuilder.createResponse(request, ResponseStatus.CHANGED);
- }
-
- private void addObserver(Device srcDevice, IRequest request,
- List<String> deviceIdList) {
-
- for (String deviceId : deviceIdList) {
- HashMap<String, PresenceSubscriber> subscribers = mDeviceSubscriber
- .get(deviceId);
-
- if (subscribers == null) {
- subscribers = new HashMap<>();
- mDeviceSubscriber.put(deviceId, subscribers);
- }
-
- subscribers.put(request.getRequestId(),
- new PresenceSubscriber(srcDevice, request));
- }
-
- mSubscribedDevices.put(request.getRequestId(), deviceIdList);
- }
-
- private void removeObserver(IRequest request) {
-
- List<String> deviceIdList = mSubscribedDevices
- .get(request.getRequestId());
-
- if (deviceIdList == null) {
- return;
- }
-
- for (String deviceId : deviceIdList) {
- HashMap<String, PresenceSubscriber> subscribers = mDeviceSubscriber
- .get(deviceId);
-
- if (subscribers == null) {
- continue;
- }
-
- subscribers.remove(request.getRequestId());
- }
- }
-
- private void notifyToObservers(String deviceId) {
-
- HashMap<String, PresenceSubscriber> tokenNSubscribers = mDeviceSubscriber
- .get(deviceId);
-
- if (tokenNSubscribers != null) {
- byte[] paylod = makeResponsePayload(Arrays.asList(deviceId));
-
- for (PresenceSubscriber subscriber : tokenNSubscribers.values()) {
-
- subscriber.mSubscriber.sendResponse(
- MessageBuilder.createResponse(subscriber.mRequest,
- ResponseStatus.CONTENT,
- ContentFormat.APPLICATION_CBOR, paylod));
- }
- }
- }
-
- private byte[] makeResponsePayload(List<String> deviceList) {
-
- HashMap<String, Object> getPayload = new HashMap<>();
- ArrayList<HashMap<String, String>> prsList = new ArrayList<HashMap<String, String>>();
-
- for (String deviceId : deviceList) {
- HashMap<String, String> payloadSegment = new HashMap<String, String>();
- payloadSegment.put(Constants.DEVICE_ID, deviceId);
- payloadSegment.put(Constants.PRESENCE_STATE,
- DBManager.getInstance().findDeviceState(deviceId));
- prsList.add(payloadSegment);
- }
- getPayload.put(Constants.PRESENCE_LIST, prsList);
- Log.i("Get observe response" + getPayload.toString());
- return mCbor.encodingPayloadToCbor(getPayload);
}
}
+++ /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.rdserver.resources.presence.device;
-
-public class DeviceState {
-
- private String di;
- private String state;
-
- public String getState() {
- return state;
- }
-
- public void setState(String state) {
- this.state = state;
- }
-
- public String getDi() {
- return di;
- }
-
- public void setDi(String deviceId) {
- this.di = deviceId;
- }
-
-}
+++ /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.rdserver.resources.presence.resource;
-
-public class ResPresencePayload {
- int non;
- int ttl;
- byte trg;
- String rt;
- String href;
-
- public int getNon() {
- return non;
- }
-
- public void setNon(int non) {
- this.non = non;
- }
-
- public int getTtl() {
- return ttl;
- }
-
- public void setTtl(int ttl) {
- this.ttl = ttl;
- }
-
- public byte getTrg() {
- return trg;
- }
-
- public void setTrg(byte trg) {
- this.trg = trg;
- }
-
- public String getRt() {
- return rt;
- }
-
- public void setRt(String rt) {
- this.rt = rt;
- }
-
- public String getHref() {
- return href;
- }
-
- public void setHref(String href) {
- this.href = href;
- }
-}
\ No newline at end of file
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.ResponseStatus;
import org.iotivity.cloud.base.resource.Resource;
import org.iotivity.cloud.rdserver.Constants;
-import org.iotivity.cloud.rdserver.resources.presence.ResPresenceManager;
+import org.iotivity.cloud.rdserver.resources.presence.PresenceManager;
+/**
+ *
+ * This class provides a set of APIs handle requests about resource presence
+ *
+ */
public class ResPresenceResource extends Resource {
public ResPresenceResource() {
switch (request.getMethod()) {
case GET:
- response = handleRegisterRequest(srcDevice, request);
+ response = handleGetRequest(srcDevice, request);
break;
default:
srcDevice.sendResponse(response);
}
- public IResponse handleRegisterRequest(Device srcDevice, IRequest request)
+ private IResponse handleGetRequest(Device srcDevice, IRequest request)
throws ServerException {
HashMap<String, List<String>> queryMap = request.getUriQueryMap();
- if (queryMap == null) {
- throw new PreconditionFailedException("query is null");
- }
+ checkQueryException(Arrays.asList(Constants.DEVICE_ID), queryMap);
List<String> deviceList = queryMap.get(Constants.DEVICE_ID);
- if (deviceList == null) {
- throw new PreconditionFailedException("deviceList is null");
- }
-
- ResPresenceManager.getInstance().addObserver(srcDevice, request,
- deviceList);
+ PresenceManager.getInstance().subscribePresence(srcDevice, request,
+ deviceList, Constants.RESOURCE_PRESENCE);
return MessageBuilder.createResponse(request, ResponseStatus.CONTENT);
}
+++ /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.rdserver.util;
-
-import java.lang.reflect.Field;
-import java.lang.reflect.Method;
-import java.util.HashMap;
-import java.util.Iterator;
-
-import org.iotivity.cloud.rdserver.Constants;
-
-public class TypeCastingManager<T> {
-
- public TypeCastingManager() {
-
- }
-
- public void callMethod(String methodName, T objClass) {
- try {
- Method method = objClass.getClass().getDeclaredMethod(methodName);
- method.invoke(objClass);
-
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- public HashMap<Object, Object> convertObjectToMap(T objClass) {
-
- HashMap<Object, Object> map = new HashMap<Object, Object>();
-
- try {
- Field[] fieldList = objClass.getClass().getDeclaredFields();
-
- for (Field field : fieldList) {
- field.setAccessible(true);
- Object value = field.get(objClass);
- if (value != null) {
- String fieldName = field.getName();
- if (fieldName.equals("itf")) {
- fieldName = Constants.INTERFACE;
- }
- map.put(fieldName, value);
- }
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
-
- return map;
- }
-
- public T convertMaptoObject(HashMap<Object, Object> map, T objClass) {
-
- String keyAttribute = null;
- String methodName = null;
- Iterator<Object> 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();
- }
- }
- }
- }
- return objClass;
- }
-
- private String makeMethodName(String keyAttribute, String prefixName) {
-
- // Exception case
- if (keyAttribute.equals(Constants.INTERFACE)) {
- keyAttribute = "itf";
- }
-
- String methodName = null;
-
- methodName = prefixName + keyAttribute.substring(0, 1).toUpperCase()
- + keyAttribute.substring(1);
-
- return methodName;
- }
-}
import org.mockito.stubbing.Answer;
public class DevicePresenceResourceTest {
- private Cbor<HashMap<String, Object>> mCbor = new Cbor<>();
- private ResourceDirectoryResource mRDResource = null;
- private DevicePresenceResource mockDevicePresenceResource = null;
- private CoapDevice mockDevice = null;
- private CountDownLatch mLatch = null;
+ private Cbor<HashMap<String, Object>> mCbor = new Cbor<>();
+ private ResourceDirectoryResource mRDResource = null;
+ private DevicePresenceResource mMockDevicePresenceResource = null;
+ private CoapDevice mMockDevice = null;
+ private CountDownLatch mLatch = null;
private IResponse mResponse;
@Before
public void setUp() throws Exception {
mResponse = null;
- mockDevice = mock(CoapDevice.class);
+ mMockDevice = mock(CoapDevice.class);
mLatch = new CountDownLatch(1);
mRDResource = new ResourceDirectoryResource();
- mockDevicePresenceResource = new DevicePresenceResource();
+ mMockDevicePresenceResource = new DevicePresenceResource();
// callback mock
Mockito.doAnswer(new Answer<Object>() {
@Override
mResponse = resp;
return null;
}
- }).when(mockDevice).sendResponse(Mockito.anyObject());
+ }).when(mMockDevice).sendResponse(Mockito.anyObject());
}
@After
request = MessageBuilder.createRequest(RequestMethod.GET,
RDServerTestUtils.DEVICE_PRS_REQ_URI, query);
} else if (obs.compareTo(Observe.UNSUBSCRIBE) == 0) {
- ArrayList<String> devices = new ArrayList<>();
- devices.add(RDServerTestUtils.DI);
- HashMap<String, ArrayList<String>> payload = new HashMap<>();
- payload.put(Constants.DEVICE_LIST_KEY, devices);
request = MessageBuilder.createRequest(RequestMethod.GET,
- RDServerTestUtils.DEVICE_PRS_REQ_URI, query,
- ContentFormat.APPLICATION_CBOR,
- mCbor.encodingPayloadToCbor(payload));
+ RDServerTestUtils.DEVICE_PRS_REQ_URI, query);
}
((CoapRequest) request).setObserve(obs);
return request;
ArrayList<HashMap<String, String>> prsList = (ArrayList<HashMap<String, String>>) payloadData
.get(Constants.PRESENCE_LIST);
- HashMap<String, String> mapData = prsList.get(0);
+ if (prsList.isEmpty()) {
+ return null;
+ } else {
+ return prsList.get(0);
- return mapData;
+ }
}
@Test
public void testSubscribeRequest() throws Exception {
System.out.println("\t------testHandleGetSubscribeRequest");
- mRDResource.onDefaultRequestReceived(mockDevice,
+ mRDResource.onDefaultRequestReceived(mMockDevice,
RDServerTestUtils.makePublishRequest());
IRequest request = makePresenceGetRequest(Observe.SUBSCRIBE);
- mockDevicePresenceResource.onDefaultRequestReceived(mockDevice,
+ mMockDevicePresenceResource.onDefaultRequestReceived(mMockDevice,
request);
// assertion: if the response status is "CONTENT"
assertTrue(mLatch.await(2L, SECONDS));
assertTrue(checkResponseCode(mResponse, ResponseStatus.CONTENT));
- // assertion : if the payload has "di" and "state"
- assertTrue(checkPayloadProperty(mResponse, Constants.DEVICE_ID));
- assertTrue(checkPayloadProperty(mResponse, Constants.PRESENCE_STATE));
- assertNull(parsePayload(mResponse).get(Constants.PRESENCE_STATE));
+ assertNull(parsePayload(mResponse));
}
@Test
public void testUnsubscribeRequest() throws Exception {
System.out.println("\t------testHandleGetUnsubscribeRequest");
IRequest request = makePresenceGetRequest(Observe.UNSUBSCRIBE);
- mRDResource.onDefaultRequestReceived(mockDevice,
+ mRDResource.onDefaultRequestReceived(mMockDevice,
RDServerTestUtils.makePublishRequest());
- mockDevicePresenceResource.onDefaultRequestReceived(mockDevice,
+ mMockDevicePresenceResource.onDefaultRequestReceived(mMockDevice,
request);
// assertion: if the response status is "CONTENT"
assertTrue(mLatch.await(2L, SECONDS));
assertTrue(checkResponseCode(mResponse, ResponseStatus.CONTENT));
- // assertion : if the payload has "di" and "state"
- assertTrue(checkPayloadProperty(mResponse, Constants.DEVICE_ID));
- assertTrue(checkPayloadProperty(mResponse, Constants.PRESENCE_STATE));
- assertNull(parsePayload(mResponse).get(Constants.PRESENCE_STATE));
+ assertNull(parsePayload(mResponse));
}
@Test
}).when(observerDevice).sendResponse(Mockito.anyObject());
// subscribe request (specific device)
IRequest subRequest = makePresenceGetRequest(Observe.SUBSCRIBE);
- mockDevicePresenceResource.onDefaultRequestReceived(observerDevice,
+ mMockDevicePresenceResource.onDefaultRequestReceived(observerDevice,
subRequest);
// POST device presence off
HashMap<String, Object> payload = new HashMap<>();
RDServerTestUtils.DEVICE_PRS_REQ_URI, null,
ContentFormat.APPLICATION_CBOR,
mCbor.encodingPayloadToCbor(payload));
- mockDevicePresenceResource.onDefaultRequestReceived(mockDevice,
+ mMockDevicePresenceResource.onDefaultRequestReceived(mMockDevice,
request);
// assertion for resource server device : responseStatus is "CHANGED"
assertTrue(mLatch.await(2L, SECONDS));
}).when(observerDevice).sendResponse(Mockito.anyObject());
// subscribe request (specific device)
IRequest subRequest = makePresenceGetRequest(Observe.UNSUBSCRIBE);
- mockDevicePresenceResource.onDefaultRequestReceived(observerDevice,
+ mMockDevicePresenceResource.onDefaultRequestReceived(observerDevice,
subRequest);
HashMap<String, Object> payload = new HashMap<>();
payload.put(Constants.DEVICE_ID, RDServerTestUtils.DI);
RDServerTestUtils.DEVICE_PRS_REQ_URI, null,
ContentFormat.APPLICATION_CBOR,
mCbor.encodingPayloadToCbor(payload));
- mockDevicePresenceResource.onDefaultRequestReceived(mockDevice,
+ mMockDevicePresenceResource.onDefaultRequestReceived(mMockDevice,
request);
// assertion for resource server device : responseStatus is "CHANGED"
assertTrue(mLatch.await(2L, SECONDS));
private ResourceDirectoryResource mRDResource = null;
private DiscoveryResource mDiscoveryResource = null;
private CoapDevice mockDevice = null;
- CountDownLatch latch = null;
- IResponse res;
+ private CountDownLatch mLatch = null;
+ private IResponse mResponse;
@Before
public void setUp() throws Exception {
- res = null;
+ mResponse = null;
mockDevice = mock(CoapDevice.class);
- latch = new CountDownLatch(1);
+ mLatch = new CountDownLatch(1);
mRDResource = new ResourceDirectoryResource();
mDiscoveryResource = new DiscoveryResource();
// callback mock
public CoapResponse answer(InvocationOnMock invocation)
throws Throwable {
CoapResponse resp = (CoapResponse) invocation.getArguments()[0];
- latch.countDown();
- res = resp;
+ mLatch.countDown();
+ mResponse = resp;
return resp;
}
}).when(mockDevice).sendResponse(Mockito.anyObject());
mDiscoveryResource.onDefaultRequestReceived(mockDevice, request);
// assertion: if the response status is "CONTENT"
// assertion : if the payload is null
- assertTrue(latch.await(2L, SECONDS));
- assertTrue(methodCheck(res, ResponseStatus.CONTENT));
- assertTrue(nullPayloadCheck(res));
+ assertTrue(mLatch.await(2L, SECONDS));
+ assertTrue(methodCheck(mResponse, ResponseStatus.CONTENT));
+ assertTrue(nullPayloadCheck(mResponse));
}
@Test
mDiscoveryResource.onDefaultRequestReceived(mockDevice, request);
// assertion: if the response status is "CONTENT"
// assertion : if the payload contains resource info
- assertTrue(latch.await(2L, SECONDS));
- assertTrue(methodCheck(res, ResponseStatus.CONTENT));
- assertTrue(discoverHashmapCheck(res, "di"));
- assertTrue(discoveredResourceCheck(res, "href"));
- assertTrue(discoveredResourceCheck(res, "rt"));
- assertTrue(discoveredResourceCheck(res, "if"));
+ assertTrue(mLatch.await(2L, SECONDS));
+ assertTrue(methodCheck(mResponse, ResponseStatus.CONTENT));
+ assertTrue(discoverHashmapCheck(mResponse, "di"));
+ assertTrue(discoveredResourceCheck(mResponse, "href"));
+ assertTrue(discoveredResourceCheck(mResponse, "rt"));
+ assertTrue(discoveredResourceCheck(mResponse, "if"));
}
private boolean discoverHashmapCheck(IResponse response,
private boolean nullPayloadCheck(IResponse response) {
ArrayList<Object> payloadData = mCbor
- .parsePayloadFromCbor(res.getPayload(), ArrayList.class);
+ .parsePayloadFromCbor(mResponse.getPayload(), ArrayList.class);
return (payloadData.isEmpty());
}
}
\ No newline at end of file
public static final String RES_PRS_URI = Constants.RESOURCE_PRESENCE_FULL_URI;
public static IRequest makePublishRequest() throws Exception {
+
HashMap<Object, Object> payload = new HashMap<>();
payload.put(Constants.DEVICE_ID, DI);
ArrayList<HashMap<Object, Object>> publishLinks = new ArrayList<>();
link.put(Constants.RESOURCE_TYPE, rt);
link.put(Constants.INTERFACE, itf);
link.put(Constants.POLICY, policy);
+ link.put(Constants.INS, 0);
+ link.put(Constants.RESOURCE_TTL, 3000);
publishLinks.add(link);
payload.put(Constants.LINKS, publishLinks);
Cbor<HashMap<Object, Object>> cbor = new Cbor<>();
private Cbor<HashMap<String, Object>> mCbor = new Cbor<>();
private ResourceDirectoryResource mRDResource = null;
private CoapDevice mockDevice = null;
- CountDownLatch latch = null;
- IResponse res;
+ CountDownLatch mLatch = null;
+ IResponse mResponse;
@Before
public void setUp() throws Exception {
- res = null;
+ mResponse = null;
mockDevice = mock(CoapDevice.class);
- latch = new CountDownLatch(1);
+ mLatch = new CountDownLatch(1);
mRDResource = new ResourceDirectoryResource();
// callback mock
Mockito.doAnswer(new Answer<Object>() {
public CoapResponse answer(InvocationOnMock invocation)
throws Throwable {
CoapResponse resp = (CoapResponse) invocation.getArguments()[0];
- latch.countDown();
- res = resp;
+ mLatch.countDown();
+ mResponse = resp;
return resp;
}
}).when(mockDevice).sendResponse(Mockito.anyObject());
RDServerTestUtils.makePublishRequest());
// assertion: if the response status is "CHANGED" according to
// the resource publication
- assertTrue(latch.await(2L, SECONDS));
- assertTrue(methodCheck(res, ResponseStatus.CHANGED));
+ assertTrue(mLatch.await(2L, SECONDS));
+ assertTrue(methodCheck(mResponse, ResponseStatus.CHANGED));
// assertion : if the mandatory properties are received in the
// response
- assertTrue(linkCheck(res, "href"));
- assertTrue(linkCheck(res, "rt"));
- assertTrue(linkCheck(res, "if"));
- assertTrue(linkCheck(res, "ins"));
- assertTrue(hashmapCheck(res, "di"));
+ assertTrue(linkCheck(mResponse, "href"));
+ assertTrue(linkCheck(mResponse, "rt"));
+ assertTrue(linkCheck(mResponse, "if"));
+ assertTrue(linkCheck(mResponse, "ins"));
+ assertTrue(hashmapCheck(mResponse, "di"));
}
@Test
mRDResource.onDefaultRequestReceived(mockDevice, request);
// assertion: if the response status is "DELETED" according to the
// resource publication
- assertTrue(latch.await(2L, SECONDS));
- assertTrue(methodCheck(res, ResponseStatus.DELETED));
+ assertTrue(mLatch.await(2L, SECONDS));
+ assertTrue(methodCheck(mResponse, ResponseStatus.DELETED));
}
@Test
mRDResource.onDefaultRequestReceived(mockDevice, request);
// assertion: if the response status is "DELETED" according to the
// resource publication
- assertTrue(latch.await(2L, SECONDS));
- assertTrue(methodCheck(res, ResponseStatus.DELETED));
+ assertTrue(mLatch.await(2L, SECONDS));
+ assertTrue(methodCheck(mResponse, ResponseStatus.DELETED));
}
@Test
mRDResource.onDefaultRequestReceived(mockDevice, request);
// assertion: if the response status is "DELETED" according to the
// resource publication
- assertTrue(latch.await(2L, SECONDS));
- assertTrue(methodCheck(res, ResponseStatus.DELETED));
+ assertTrue(mLatch.await(2L, SECONDS));
+ assertTrue(methodCheck(mResponse, ResponseStatus.DELETED));
}
@Test
mRDResource.onDefaultRequestReceived(mockDevice, request);
// assertion: if the response status is "DELETED" according to the
// resource publication
- assertTrue(latch.await(2L, SECONDS));
- assertTrue(methodCheck(res, ResponseStatus.DELETED));
+ assertTrue(mLatch.await(2L, SECONDS));
+ assertTrue(methodCheck(mResponse, ResponseStatus.DELETED));
}
private boolean hashmapCheck(IResponse response, String propertyName) {
private ResourceDirectoryResource mRDResource = null;
private ResPresenceResource mResPresenceResource = null;
private CoapDevice mockDevice = null;
- CountDownLatch latch = null;
- IResponse res;
+ private CountDownLatch mLatch = null;
+ private IResponse mResponse;
@Before
public void setUp() throws Exception {
mRDResource = new ResourceDirectoryResource();
mResPresenceResource = new ResPresenceResource();
- res = null;
+ mResponse = null;
mockDevice = mock(CoapDevice.class);
- latch = new CountDownLatch(1);
+ mLatch = new CountDownLatch(1);
// callback mock
Mockito.doAnswer(new Answer<Object>() {
@Override
public CoapResponse answer(InvocationOnMock invocation)
throws Throwable {
CoapResponse resp = (CoapResponse) invocation.getArguments()[0];
- latch.countDown();
- res = resp;
+ mLatch.countDown();
+ mResponse = resp;
return resp;
}
}).when(mockDevice).sendResponse(Mockito.anyObject());
IRequest request = MessageBuilder.createRequest(RequestMethod.GET,
RDServerTestUtils.RES_PRS_URI, "di=" + RDServerTestUtils.DI);
mResPresenceResource.onDefaultRequestReceived(mockDevice, request);
- assertTrue(latch.await(2L, SECONDS));
- assertTrue(methodCheck(res, ResponseStatus.CONTENT));
+ assertTrue(mLatch.await(2L, SECONDS));
+ assertTrue(methodCheck(mResponse, ResponseStatus.CONTENT));
}
@Test
mRDResource.onDefaultRequestReceived(mockDevice,
RDServerTestUtils.makePublishRequest());
// assertion: if the response status is "CHANGED"
- assertTrue(latch.await(2L, SECONDS));
- assertTrue(methodCheck(res, ResponseStatus.CHANGED));
+ assertTrue(mLatch.await(2L, SECONDS));
+ assertTrue(methodCheck(mResponse, ResponseStatus.CHANGED));
}
private boolean methodCheck(IResponse response,