From: eunok.shin Date: Tue, 6 Sep 2016 06:20:57 +0000 (+0900) Subject: refactoring RD server X-Git-Tag: 1.2.0+RC3~79 X-Git-Url: http://review.tizen.org/git/?a=commitdiff_plain;h=c3511740e60a2450476b8e5b1e5bcf48ccfae655;p=platform%2Fupstream%2Fiotivity.git refactoring RD server Change-Id: Icd024741fabdfd518dac7236a82f78607905270a Signed-off-by: eunok.shin Reviewed-on: https://gerrit.iotivity.org/gerrit/12279 Tested-by: jenkins-iotivity Reviewed-by: Jee Hyeok Kim --- diff --git a/cloud/interface/src/main/java/org/iotivity/cloud/ciserver/Constants.java b/cloud/interface/src/main/java/org/iotivity/cloud/ciserver/Constants.java index 9ef30d0..8ca99b5 100644 --- a/cloud/interface/src/main/java/org/iotivity/cloud/ciserver/Constants.java +++ b/cloud/interface/src/main/java/org/iotivity/cloud/ciserver/Constants.java @@ -50,5 +50,5 @@ public class Constants extends OICConstants { public static final String REQ_LINKS = "links"; public static final String REQ_HREF = "href"; - + public static final String REQ_CRL = "crl"; } diff --git a/cloud/interface/src/test/java/org/iotivity/cloud/ciserver/resources/proxy/rd/DevicePresenceTest.java b/cloud/interface/src/test/java/org/iotivity/cloud/ciserver/resources/proxy/rd/DevicePresenceTest.java index 42943f6..1d58984 100644 --- a/cloud/interface/src/test/java/org/iotivity/cloud/ciserver/resources/proxy/rd/DevicePresenceTest.java +++ b/cloud/interface/src/test/java/org/iotivity/cloud/ciserver/resources/proxy/rd/DevicePresenceTest.java @@ -56,18 +56,16 @@ import org.mockito.invocation.InvocationOnMock; 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 { diff --git a/cloud/interface/src/test/java/org/iotivity/cloud/ciserver/resources/proxy/rd/ResourcePresenceTest.java b/cloud/interface/src/test/java/org/iotivity/cloud/ciserver/resources/proxy/rd/ResourcePresenceTest.java index c28a978..9ed3e0a 100644 --- a/cloud/interface/src/test/java/org/iotivity/cloud/ciserver/resources/proxy/rd/ResourcePresenceTest.java +++ b/cloud/interface/src/test/java/org/iotivity/cloud/ciserver/resources/proxy/rd/ResourcePresenceTest.java @@ -56,7 +56,6 @@ import org.mockito.stubbing.Answer; 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); diff --git a/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/Constants.java b/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/Constants.java index 57ef745..b23d643 100644 --- a/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/Constants.java +++ b/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/Constants.java @@ -21,52 +21,59 @@ */ 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 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"; } diff --git a/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/ResourceDirectoryServer.java b/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/ResourceDirectoryServer.java index 16fccc3..b5f41c2 100644 --- a/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/ResourceDirectoryServer.java +++ b/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/ResourceDirectoryServer.java @@ -32,6 +32,11 @@ import org.iotivity.cloud.rdserver.resources.presence.device.DevicePresenceResou 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 { @@ -40,8 +45,7 @@ public class ResourceDirectoryServer { 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; } diff --git a/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/db/DBManager.java b/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/db/DBManager.java index aefb1bb..734c52f 100644 --- a/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/db/DBManager.java +++ b/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/db/DBManager.java @@ -23,65 +23,226 @@ package org.iotivity.cloud.rdserver.db; import java.util.ArrayList; import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; +import org.bson.Document; +import org.iotivity.cloud.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> 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 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 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 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> selectRecord(String tableName, + HashMap condition) { + + return _selectRecord(tableName, condition); } - public ArrayList registerResource( - ArrayList> 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 condition) { + + if (!_deleteRecord(tableName, condition)) + throw new InternalServerErrorException( + "Database record delete failed"); } - public ArrayList> 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 replace) { + + if (!_updateRecord(tableName, replace)) + throw new InternalServerErrorException( + "Database record update failed"); + } - - public ArrayList> findResourceAboutDiAndFilter(String di, - String key, String value) { - return mMongoDB.readResourceAboutDidAndFilter(di, key, value, - Constants.RD_TABLE); + + private Boolean _insertRecord(String tableName, + HashMap record) { + + Document doc = createDocument(record); + + return mMongoDB.insertRecord(tableName, doc); } - public ArrayList deleteResourceAboutDi(String di) { - return mMongoDB.deleteResourceAboutDi(di, Constants.RD_TABLE); + private Boolean _insertAndReplaceRecord(String tableName, + HashMap record) { + + Document doc = createDocument(record); + Document filter = getKeyFilter(tableName, record); + + return mMongoDB.insertAndReplaceRecord(tableName, filter, doc); } - public ArrayList deleteResourceAboutDiAandIns(String di, - String ins) { - return mMongoDB.deleteResourceAboutDiAndIns(di, ins, - Constants.RD_TABLE); + private Boolean _deleteRecord(String tableName, + HashMap 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 record) { + + Document replace = createDocument(record); + Document filter = getKeyFilter(tableName, record); + + return mMongoDB.updateRecord(tableName, filter, replace); } - public void updateDeviceState(HashMap deviceState) { - mMongoDB.createDevicePresenceResource(deviceState, - Constants.PRESENCE_TABLE); + private ArrayList> _selectRecord(String tableName, + HashMap 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 record) { + + Document filterDoc = new Document(); + + ArrayList keys = mKeyField.get(tableName); + + for (String key : keys) { + + Object value = record.get(key); + filterDoc.append(key, value); + } + + return filterDoc; } -} + + private Document createDocument(HashMap record) { + + Document doc = new Document(); + Set> resEntrySet = record.entrySet(); + Iterator> entryIter = resEntrySet.iterator(); + + while (entryIter.hasNext()) { + Map.Entry entry = (Map.Entry) entryIter + .next(); + doc.append(entry.getKey().toString(), entry.getValue()); + } + + return doc; + } + +} \ No newline at end of file diff --git a/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/db/MongoDB.java b/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/db/MongoDB.java index ff48f63..8abde68 100644 --- a/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/db/MongoDB.java +++ b/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/db/MongoDB.java @@ -29,14 +29,13 @@ import java.util.Map.Entry; 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; /** * @@ -56,349 +55,230 @@ public class MongoDB { * @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 storeRes) { + public void createIndex(String tablename, ArrayList keys) { Document doc = new Document(); - Set> resEntrySet = storeRes.entrySet(); - Iterator> entryIter = resEntrySet.iterator(); - - while (entryIter.hasNext()) { - Map.Entry entry = (Map.Entry) entryIter - .next(); - doc.append(entry.getKey().toString(), entry.getValue()); - } - - return doc; - } - - private ArrayList createDocuments( - ArrayList> storeResList) { - - Iterator> resListIter = storeResList.iterator(); - - ArrayList docList = new ArrayList<>(); - while (resListIter.hasNext()) { - Document doc = new Document(); + for (String key : keys) { - HashMap storeRes = resListIter.next(); - Set> resEntrySet = storeRes.entrySet(); - Iterator> entryIter = resEntrySet.iterator(); - - while (entryIter.hasNext()) { - Map.Entry entry = (Map.Entry) entryIter - .next(); - doc.append(entry.getKey().toString(), entry.getValue()); - } - docList.add(doc); + doc.append(key, 1); } - return docList; - } - - private HashMap convertDocumentToHashMap(Document doc) { - HashMap resourceMap = new HashMap(); - - Set> entrySet = doc.entrySet(); - Iterator> entryIter = entrySet.iterator(); - while (entryIter.hasNext()) { - Map.Entry entry = (Map.Entry) 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 createRDResource( - ArrayList> storeResList, String tableName) { - ArrayList docList = createDocuments(storeResList); - Iterator 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 collection = db.getCollection(tableName); - ArrayList 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 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 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 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 collection = db.getCollection(tableName); - MongoCursor 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> readResourceAboutDid(String di, String tableName) { - MongoCollection collection = db.getCollection(tableName); - ArrayList> resList = null; - MongoCursor 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> 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 - array list of resource - * information - */ - public ArrayList> readResourceAboutDidAndFilter(String di, - String filterKey, String filterValue, String tableName) { MongoCollection collection = db.getCollection(tableName); - ArrayList> resList = null; - MongoCursor 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 cursor = collection.find(doc).iterator(); - return resList; - } + ArrayList> recordList = new ArrayList<>(); - public Object readInsAboutDid(String di, String href, String tableName) { - MongoCollection collection = db.getCollection(tableName); - MongoCursor 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 deleteResourceAboutDi(String di, - String tableName) { + private HashMap convertDocumentToHashMap(Document doc) { + HashMap resourceMap = new HashMap<>(); - MongoCollection collection = db.getCollection(tableName); + Set> entrySet = doc.entrySet(); + Iterator> entryIter = entrySet.iterator(); - MongoCursor cursor = collection - .find(Filters.eq(Constants.DEVICE_ID, di)).iterator(); + while (entryIter.hasNext()) { - ArrayList resPayloadList = new ArrayList<>(); + Map.Entry entry = (Map.Entry) 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 deleteResourceAboutDiAndIns(String di, - String ins, String tableName) { + private void showRecord(String tableName) { MongoCollection collection = db.getCollection(tableName); + MongoCursor cursor = collection.find().iterator(); - MongoCursor cursor = collection - .find(Filters.and(Filters.eq(Constants.DEVICE_ID, di), - Filters.eq(Constants.INS, ins))) - .iterator(); - - ArrayList resPayloadList = new ArrayList<>(); + Log.i("<" + tableName + ">"); - try { - while (cursor.hasNext()) { - Document doc = cursor.next(); - resPayloadList.add( - makeResourcePresencePayload(doc, Constants.RES_DELETE)); - } + HashMap 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(); } } diff --git a/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/directory/PayloadManager.java b/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/directory/PayloadManager.java new file mode 100644 index 0000000..bf1e91f --- /dev/null +++ b/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/directory/PayloadManager.java @@ -0,0 +1,103 @@ +/* + * //****************************************************************** + * // + * // 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 pubTagKey = Arrays.asList("di", "n", "lt"); + + /** links values of /oic/rd resource payload */ + public List pubLinkKey = Arrays.asList("href", "rel", "rt", + "if", "p", "title", "anchor", "ins", "ttl", "type"); + + /** tag values of /oic/res resource payload */ + public List discoverTagKey = Arrays.asList("di", "n"); + + /** links values of /oic/res resource payload */ + public List 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 setPayloadData( + HashMap payload, List keyType) { + + HashMap data = new HashMap(); + + 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 payload) { + Object policy = payload.get(Constants.POLICY); + if (policy != null) { + HashMap bm = (HashMap) 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 payload) { + Object policy = payload.get(Constants.POLICY); + if (policy != null) { + HashMap bm = new HashMap<>(); + bm.put(Constants.BITMAP, policy); + payload.put(Constants.POLICY, bm); + } + } + +} diff --git a/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/directory/RDManager.java b/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/directory/RDManager.java new file mode 100644 index 0000000..281c8f4 --- /dev/null +++ b/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/directory/RDManager.java @@ -0,0 +1,285 @@ +/* + * //****************************************************************** + * // + * // 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> mResourcePresence = new ArrayList<>(); + + /** + * API for handling resource-publish process + * + * @param requestPayload + * request payload + * @return response payload + */ + public HashMap publishResource( + HashMap requestPayload) { + + HashMap deviceInfo = setResourceDeviceInfo( + requestPayload); + ArrayList> 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 setResourceDeviceInfo( + HashMap payload) { + return mPayloadManager.setPayloadData(payload, + mPayloadManager.pubTagKey); + } + + private ArrayList> getLinks( + HashMap requestPayload) { + return (ArrayList>) requestPayload + .get(Constants.LINKS); + + } + + private void storeResource(ArrayList> links, + HashMap deviceInfo) { + + ArrayList> resourcePresence = new ArrayList<>(); + + for (HashMap link : links) { + HashMap storeInfo = new HashMap<>(); + HashMap 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 rdInfo) { + HashMap 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> links) { + + for (HashMap 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 insList) { + + HashMap condition = new HashMap<>(); + condition.put(Constants.DEVICE_ID, di); + + ArrayList> 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> checkResourceExist( + HashMap condition) { + ArrayList> 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 discoverResource(List diList, + List rtList, List ifList) { + + HashMap condition = new HashMap<>(); + + ArrayList 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 diList, + HashMap condition, ArrayList response) { + + for (String di : diList) { + condition.put(Constants.DEVICE_ID, di); + ArrayList> records = DBManager.getInstance() + .selectRecord(Constants.RD_TABLE, condition); + + if (!records.isEmpty()) { + response.add(makeDiscoverResponseSegment(records)); + } + + } + } + + private HashMap makeDiscoverResponseSegment( + ArrayList> records) { + + HashMap responseSegment = new HashMap<>(); + + // make Tags + HashMap discoverTag = mPayloadManager + .setPayloadData(records.get(0), mPayloadManager.discoverTagKey); + responseSegment.putAll(discoverTag); + + ArrayList links = new ArrayList<>(); + // make links + for (HashMap record : records) { + HashMap link = mPayloadManager + .setPayloadData(record, mPayloadManager.discoverLinkKey); + mPayloadManager.changePolicyTypeToDiscover(link); + links.add(link); + } + responseSegment.put(Constants.LINKS, links); + + return responseSegment; + + } + + private void setmResourcePresence( + ArrayList> resourcePresence) { + this.mResourcePresence = resourcePresence; + } + + /** + * API for getting resource information to notify + * + * @return resource information + */ + public ArrayList> getmResourcePresence() { + return mResourcePresence; + } + +} diff --git a/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/directory/rd/InsManager.java b/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/directory/rd/InsManager.java index 980e092..f97e2fc 100644 --- a/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/directory/rd/InsManager.java +++ b/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/directory/rd/InsManager.java @@ -21,26 +21,53 @@ */ 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 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 condition = new HashMap<>(); + condition.put(Constants.DEVICE_ID, di); + condition.put(Constants.HREF, href); + ArrayList> 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; diff --git a/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/directory/rd/PublishLinks.java b/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/directory/rd/PublishLinks.java deleted file mode 100644 index 6a64e36..0000000 --- a/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/directory/rd/PublishLinks.java +++ /dev/null @@ -1,155 +0,0 @@ -/* - * //****************************************************************** - * // - * // 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 rt = new ArrayList(); - /** Resource interface */ - private ArrayList itf = new ArrayList(); - /** 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 type = new ArrayList(); - - 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 getRt() { - return rt; - } - - public void setRt(Object rt) { - this.rt = (ArrayList) rt; - } - - public ArrayList getItf() { - return itf; - } - - public void setItf(Object itf) { - this.itf = (ArrayList) itf; - } - - public Object getP() { - return p; - } - - public void setP(Object p) { - HashMap bm = (HashMap) p; - this.p = bm.get(Constants.BITMAP); - } - - public void changePType() { - HashMap bm = new HashMap(); - 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 getType() { - return type; - } - - public void setType(Object type) { - this.type = (ArrayList) type; - } - -} diff --git a/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/directory/rd/PublishPayload.java b/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/directory/rd/PublishPayload.java deleted file mode 100644 index e02b726..0000000 --- a/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/directory/rd/PublishPayload.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * //****************************************************************** - * // - * // 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 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 getLinks() { - return links; - } - - public void setLinks(ArrayList links) { - this.links = links; - } -} diff --git a/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/directory/rd/PublishTags.java b/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/directory/rd/PublishTags.java deleted file mode 100644 index f240ff9..0000000 --- a/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/directory/rd/PublishTags.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * //****************************************************************** - * // - * // 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; - } -} diff --git a/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/directory/rd/ResourceDirectoryResource.java b/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/directory/rd/ResourceDirectoryResource.java index 9d465a4..f56f29d 100644 --- a/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/directory/rd/ResourceDirectoryResource.java +++ b/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/directory/rd/ResourceDirectoryResource.java @@ -37,21 +37,20 @@ import org.iotivity.cloud.base.protocols.enums.ContentFormat; import org.iotivity.cloud.base.protocols.enums.ResponseStatus; import org.iotivity.cloud.base.resource.Resource; import org.iotivity.cloud.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> mCbor = new Cbor<>(); - private TypeCastingManager mPublishTagsTypeManager = new TypeCastingManager<>(); - private TypeCastingManager mPublishLinksTypeManager = new TypeCastingManager<>(); - private InsManager mInsManager = new InsManager(); - private String mNotiDeviceId = null; - private ArrayList mNotiPayloadList = new ArrayList(); + private Cbor> mCbor = new Cbor<>(); + private RDManager mRdManager = new RDManager(); public ResourceDirectoryResource() { super(Arrays.asList(Constants.PREFIX_OIC, Constants.RD_URI)); @@ -73,208 +72,83 @@ public class ResourceDirectoryResource extends Resource { 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> queryMap = request.getUriQueryMap(); - - byte[] encodedPayload = null; - - if (queryMap == null) { - throw new PreconditionFailedException("query is null"); - } - - List 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 payload) { - mNotiDeviceId = pubPayload.getTags().getDi(); - - // PublishPayload copyPubPayload = pubPayload.copy(); - - // ArrayList> storeResList = - // creatDBStoreResource(changeResourceUri(copyPubPayload)); - - ArrayList> 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 responseMap = new HashMap(); - - PublishTags tags = pubPayload.getTags(); - responseMap.putAll(mPublishTagsTypeManager.convertObjectToMap(tags)); - - ArrayList pubLinksList = pubPayload.getLinks(); - - ArrayList> links = new ArrayList>(); - - for (PublishLinks pubLinks : pubLinksList) { - mPublishLinksTypeManager.callMethod("changePType", pubLinks); - links.add(mPublishLinksTypeManager.convertObjectToMap(pubLinks)); + ArrayList> linksList = (ArrayList>) links; + for (HashMap 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 payloadData = mCbor.parsePayloadFromCbor( - payload, HashMap.class); - - if (payloadData == null) { - throw new BadRequestException("payload is null"); - } else { - Log.i("publish payload: " + payloadData.toString()); - } + HashMap> queryMap = request.getUriQueryMap(); - PublishTags tags = new PublishTags(); - tags = mPublishTagsTypeManager.convertMaptoObject(payloadData, tags); - - String di = tags.getDi(); - - ArrayList> linksList = (ArrayList>) payloadData - .get(Constants.LINKS); - - ArrayList pubLinksList = new ArrayList(); - - for (HashMap 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 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 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 response = mRdManager.publishResource(payload); - private ArrayList> creatDBStoreResource( - PublishPayload pubPayload) { - PublishTags tags = pubPayload.getTags(); - ArrayList linksList = pubPayload.getLinks(); + Log.d("publish response : " + response); - ArrayList> storeResList = new ArrayList>(); - HashMap storeTags = mPublishTagsTypeManager - .convertObjectToMap(tags); + return MessageBuilder.createResponse(request, ResponseStatus.CHANGED, + ContentFormat.APPLICATION_CBOR, + mCbor.encodingPayloadToCbor(response)); - for (PublishLinks links : linksList) { - HashMap storeRes = new HashMap(); - storeRes.putAll(storeTags); - storeRes.putAll(mPublishLinksTypeManager.convertObjectToMap(links)); - storeResList.add(storeRes); - } - return storeResList; } private IResponse handleDeleteRequest(IRequest request) throws ServerException { HashMap> queryMap = request.getUriQueryMap(); - List diList = null; - List 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 diList = queryMap.get(Constants.DEVICE_ID); + List insList = queryMap.get(Constants.INS); + + mRdManager.deleteResource(diList.get(0), insList); IResponse response = MessageBuilder.createResponse(request, ResponseStatus.DELETED); return response; } + } diff --git a/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/directory/res/DiscoveryLinks.java b/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/directory/res/DiscoveryLinks.java deleted file mode 100644 index e4caa38..0000000 --- a/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/directory/res/DiscoveryLinks.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * //****************************************************************** - * // - * // 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 rt = new ArrayList<>(); - /** Resource interface */ - private ArrayList itf = new ArrayList<>(); - /** policies that apply for resource */ - private HashMap p = new HashMap<>(); - - public DiscoveryLinks() { - - } - - public String getHref() { - return href; - } - - public void setHref(Object href) { - this.href = href.toString(); - } - - public ArrayList getRt() { - return rt; - } - - public void setRt(Object rt) { - this.rt = (ArrayList) rt; - } - - public ArrayList getItf() { - return itf; - } - - public void setItf(Object itf) { - this.itf = (ArrayList) itf; - } - - public Object getP() { - return p; - } - - public void setP(Object p) { - int bm = (int) p; - this.p.put(Constants.BITMAP, bm); - } -} diff --git a/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/directory/res/DiscoveryPayload.java b/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/directory/res/DiscoveryPayload.java deleted file mode 100644 index edae490..0000000 --- a/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/directory/res/DiscoveryPayload.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * //****************************************************************** - * // - * // 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 links = new ArrayList<>(); - - public DiscoveryPayload() { - - } - - public DiscoveryTags getTags() { - return tags; - } - - public void setTags(DiscoveryTags tags) { - this.tags = tags; - } - - public ArrayList getLinks() { - return links; - } - - public void setLinks(ArrayList links) { - this.links = links; - } - -} diff --git a/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/directory/res/DiscoveryResource.java b/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/directory/res/DiscoveryResource.java index 0462ed3..3a1da17 100644 --- a/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/directory/res/DiscoveryResource.java +++ b/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/directory/res/DiscoveryResource.java @@ -29,7 +29,6 @@ import java.util.List; 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; @@ -37,15 +36,17 @@ import org.iotivity.cloud.base.protocols.enums.ContentFormat; import org.iotivity.cloud.base.protocols.enums.ResponseStatus; import org.iotivity.cloud.base.resource.Resource; import org.iotivity.cloud.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> mCbor = new Cbor<>(); - private TypeCastingManager mDiscoveryTagsTypeManager = new TypeCastingManager<>(); - private TypeCastingManager mDiscoveryLinkTypeManager = new TypeCastingManager<>(); + private Cbor> mCbor = new Cbor<>(); + private RDManager mRdManager = new RDManager(); public DiscoveryResource() { super(Arrays.asList(Constants.PREFIX_OIC, Constants.WELL_KNOWN_URI)); @@ -75,105 +76,16 @@ public class DiscoveryResource extends Resource { HashMap> queryMap = request.getUriQueryMap(); - ArrayList resourceList = new ArrayList(); - - if (queryMap == null) { - throw new PreconditionFailedException("query is null"); - } - - List deviceList = queryMap.get(Constants.DEVICE_ID); - - if (deviceList == null) { - throw new PreconditionFailedException( - "di property is not included"); - } - - List listRT = queryMap.get(Constants.RESOURCE_TYPE); - List listITF = queryMap.get(Constants.INTERFACE); - String key = null, value = null; - ArrayList> 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 diList = queryMap.get(Constants.DEVICE_ID); + List rtList = queryMap.get(Constants.RESOURCE_TYPE); + List 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 response = mRdManager.discoverResource(diList, rtList, + ifList); return MessageBuilder.createResponse(request, ResponseStatus.CONTENT, ContentFormat.APPLICATION_CBOR, - createDiscoveryResponse(resourceList)); + mCbor.encodingPayloadToCbor(response)); } - private DiscoveryPayload makeDiscoveryPayloadSegment( - ArrayList> foundResList) { - - ArrayList discoveryLinksList = new ArrayList(); - - for (HashMap 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 discoveryPayloadList) { - ArrayList> responseMapList = new ArrayList>(); - - for (DiscoveryPayload discoveryPayload : discoveryPayloadList) { - - DiscoveryTags tags = discoveryPayload.getTags(); - - HashMap responseSegment = mDiscoveryTagsTypeManager - .convertObjectToMap(tags); - - ArrayList discoveryLinksList = discoveryPayload - .getLinks(); - - ArrayList> links = new ArrayList>(); - - 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; - } } diff --git a/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/directory/res/DiscoveryTags.java b/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/directory/res/DiscoveryTags.java deleted file mode 100644 index bc1fe35..0000000 --- a/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/directory/res/DiscoveryTags.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * //****************************************************************** - * // - * // 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(); - } -} diff --git a/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/presence/PresenceManager.java b/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/presence/PresenceManager.java new file mode 100644 index 0000000..0079716 --- /dev/null +++ b/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/presence/PresenceManager.java @@ -0,0 +1,343 @@ +/* + * //****************************************************************** + * // + * // 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> 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> mSubscriber; + // token, di list + private HashMap> mSubscribedDevices; + private HashMap 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 deviceIdList, String presenceType) { + + PresenceInfo presenceInfo = getPresenceInfo(presenceType); + + for (String deviceId : deviceIdList) { + HashMap 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 deviceIdList, + String presenceType) { + + PresenceInfo presenceInfo = getPresenceInfo(presenceType); + + for (String deviceId : deviceIdList) { + HashMap 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 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 deviceList) { + + HashMap getPayload = new HashMap<>(); + ArrayList> prsList = new ArrayList<>(); + + for (String deviceId : deviceList) { + HashMap 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 condition = new HashMap<>(); + condition.put(Constants.DEVICE_ID, deviceId); + + String state = null; + + ArrayList> 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> resourceInfo) { + + if (resourceInfo.isEmpty()) { + return; + } + + Object obj = resourceInfo.get(0).get(Constants.DEVICE_ID); + + if (obj == null) { + return; + } + + String deviceId = obj.toString(); + + HashMap tokenNSubscribers = mResourcePresence.mSubscriber + .get(deviceId); + + if (tokenNSubscribers != null) { + + for (PresenceSubscriber subscriber : tokenNSubscribers.values()) { + + for (HashMap 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 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 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 payload) { + DBManager.getInstance().insertAndReplaceRecord(Constants.PRESENCE_TABLE, + payload); + } +} diff --git a/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/presence/ResPresenceManager.java b/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/presence/ResPresenceManager.java deleted file mode 100644 index f0779db..0000000 --- a/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/presence/ResPresenceManager.java +++ /dev/null @@ -1,170 +0,0 @@ -/* - * //****************************************************************** - * // - * // 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> mDeviceSubscriber = null; - // token, di list - private HashMap> mSubscribedDevices = null; - - private HashMap 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 deviceIdList) { - - for (String deviceId : deviceIdList) { - HashMap 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 deviceIdList = mSubscribedDevices - .get(request.getRequestId()); - - if (deviceIdList == null) { - return; - } - - for (String deviceId : deviceIdList) { - HashMap subscribers = mDeviceSubscriber - .get(deviceId); - - if (subscribers == null) { - continue; - } - - subscribers.remove(request.getRequestId()); - } - } - - public void notifyToObservers(String deviceId, - ArrayList resPayloadList) { - - HashMap 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(); - } -} diff --git a/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/presence/device/DevicePresenceResource.java b/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/presence/device/DevicePresenceResource.java index bd8780b..fe4556f 100644 --- a/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/presence/device/DevicePresenceResource.java +++ b/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/presence/device/DevicePresenceResource.java @@ -21,7 +21,6 @@ */ package org.iotivity.cloud.rdserver.resources.presence.device; -import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; @@ -36,36 +35,22 @@ import org.iotivity.cloud.base.protocols.enums.ContentFormat; import org.iotivity.cloud.base.protocols.enums.ResponseStatus; import org.iotivity.cloud.base.resource.Resource; import org.iotivity.cloud.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> 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> mDeviceSubscriber = null; - // token, di list - private HashMap> mSubscribedDevices = null; - public DevicePresenceResource() { super(Arrays.asList(Constants.PREFIX_OIC, Constants.DEVICE_PRESENCE_URI)); - mDeviceSubscriber = new HashMap<>(); - mSubscribedDevices = new HashMap<>(); } @Override @@ -95,30 +80,31 @@ public class DevicePresenceResource extends Resource { throws ServerException { HashMap> queryMap = request.getUriQueryMap(); - byte[] payload = null; + checkQueryException(Arrays.asList(Constants.DEVICE_ID), queryMap); - if (checkQueryException(Arrays.asList(Constants.DEVICE_ID), queryMap)) { + List deviceList = queryMap.get(Constants.DEVICE_ID); - List 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(); @@ -126,104 +112,18 @@ public class DevicePresenceResource extends Resource { HashMap 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 deviceStateTypeManager = new TypeCastingManager(); - HashMap 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 deviceIdList) { - - for (String deviceId : deviceIdList) { - HashMap 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 deviceIdList = mSubscribedDevices - .get(request.getRequestId()); - - if (deviceIdList == null) { - return; - } - - for (String deviceId : deviceIdList) { - HashMap subscribers = mDeviceSubscriber - .get(deviceId); - - if (subscribers == null) { - continue; - } - - subscribers.remove(request.getRequestId()); - } - } - - private void notifyToObservers(String deviceId) { - - HashMap 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 deviceList) { - - HashMap getPayload = new HashMap<>(); - ArrayList> prsList = new ArrayList>(); - - for (String deviceId : deviceList) { - HashMap payloadSegment = new HashMap(); - 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); } } diff --git a/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/presence/device/DeviceState.java b/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/presence/device/DeviceState.java deleted file mode 100644 index 72fd80c..0000000 --- a/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/presence/device/DeviceState.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * //****************************************************************** - * // - * // 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; - } - -} diff --git a/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/presence/resource/ResPresencePayload.java b/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/presence/resource/ResPresencePayload.java deleted file mode 100644 index 8a9839a..0000000 --- a/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/presence/resource/ResPresencePayload.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * //****************************************************************** - * // - * // 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 diff --git a/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/presence/resource/ResPresenceResource.java b/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/presence/resource/ResPresenceResource.java index 1472463..8ab8640 100644 --- a/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/presence/resource/ResPresenceResource.java +++ b/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/presence/resource/ResPresenceResource.java @@ -28,15 +28,19 @@ import java.util.List; 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() { @@ -51,7 +55,7 @@ public class ResPresenceResource extends Resource { switch (request.getMethod()) { case GET: - response = handleRegisterRequest(srcDevice, request); + response = handleGetRequest(srcDevice, request); break; default: @@ -62,23 +66,17 @@ public class ResPresenceResource extends Resource { srcDevice.sendResponse(response); } - public IResponse handleRegisterRequest(Device srcDevice, IRequest request) + private IResponse handleGetRequest(Device srcDevice, IRequest request) throws ServerException { HashMap> queryMap = request.getUriQueryMap(); - if (queryMap == null) { - throw new PreconditionFailedException("query is null"); - } + checkQueryException(Arrays.asList(Constants.DEVICE_ID), queryMap); List 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); } diff --git a/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/util/TypeCastingManager.java b/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/util/TypeCastingManager.java deleted file mode 100644 index cc9df99..0000000 --- a/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/util/TypeCastingManager.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * //****************************************************************** - * // - * // 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 { - - 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 convertObjectToMap(T objClass) { - - HashMap map = new HashMap(); - - 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 map, T objClass) { - - String keyAttribute = null; - String methodName = null; - Iterator 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; - } -} diff --git a/cloud/resourcedirectory/src/test/java/org/iotivity/cloud/testrdserver/DevicePresenceResourceTest.java b/cloud/resourcedirectory/src/test/java/org/iotivity/cloud/testrdserver/DevicePresenceResourceTest.java index 3e4e851..86243c9 100644 --- a/cloud/resourcedirectory/src/test/java/org/iotivity/cloud/testrdserver/DevicePresenceResourceTest.java +++ b/cloud/resourcedirectory/src/test/java/org/iotivity/cloud/testrdserver/DevicePresenceResourceTest.java @@ -52,20 +52,20 @@ import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; public class DevicePresenceResourceTest { - private Cbor> mCbor = new Cbor<>(); - private ResourceDirectoryResource mRDResource = null; - private DevicePresenceResource mockDevicePresenceResource = null; - private CoapDevice mockDevice = null; - private CountDownLatch mLatch = null; + private Cbor> 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() { @Override @@ -76,7 +76,7 @@ public class DevicePresenceResourceTest { mResponse = resp; return null; } - }).when(mockDevice).sendResponse(Mockito.anyObject()); + }).when(mMockDevice).sendResponse(Mockito.anyObject()); } @After @@ -91,14 +91,8 @@ public class DevicePresenceResourceTest { request = MessageBuilder.createRequest(RequestMethod.GET, RDServerTestUtils.DEVICE_PRS_REQ_URI, query); } else if (obs.compareTo(Observe.UNSUBSCRIBE) == 0) { - ArrayList devices = new ArrayList<>(); - devices.add(RDServerTestUtils.DI); - HashMap> 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; @@ -112,43 +106,40 @@ public class DevicePresenceResourceTest { ArrayList> prsList = (ArrayList>) payloadData .get(Constants.PRESENCE_LIST); - HashMap 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 @@ -186,7 +177,7 @@ public class DevicePresenceResourceTest { }).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 payload = new HashMap<>(); @@ -196,7 +187,7 @@ public class DevicePresenceResourceTest { 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)); @@ -229,7 +220,7 @@ public class DevicePresenceResourceTest { }).when(observerDevice).sendResponse(Mockito.anyObject()); // subscribe request (specific device) IRequest subRequest = makePresenceGetRequest(Observe.UNSUBSCRIBE); - mockDevicePresenceResource.onDefaultRequestReceived(observerDevice, + mMockDevicePresenceResource.onDefaultRequestReceived(observerDevice, subRequest); HashMap payload = new HashMap<>(); payload.put(Constants.DEVICE_ID, RDServerTestUtils.DI); @@ -238,7 +229,7 @@ public class DevicePresenceResourceTest { 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)); diff --git a/cloud/resourcedirectory/src/test/java/org/iotivity/cloud/testrdserver/DiscoveryResourceTest.java b/cloud/resourcedirectory/src/test/java/org/iotivity/cloud/testrdserver/DiscoveryResourceTest.java index 193e298..b3709b5 100644 --- a/cloud/resourcedirectory/src/test/java/org/iotivity/cloud/testrdserver/DiscoveryResourceTest.java +++ b/cloud/resourcedirectory/src/test/java/org/iotivity/cloud/testrdserver/DiscoveryResourceTest.java @@ -51,14 +51,14 @@ public class DiscoveryResourceTest { 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 @@ -67,8 +67,8 @@ public class DiscoveryResourceTest { 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()); @@ -87,9 +87,9 @@ public class DiscoveryResourceTest { 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 @@ -102,12 +102,12 @@ public class DiscoveryResourceTest { 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, @@ -147,7 +147,7 @@ public class DiscoveryResourceTest { private boolean nullPayloadCheck(IResponse response) { ArrayList payloadData = mCbor - .parsePayloadFromCbor(res.getPayload(), ArrayList.class); + .parsePayloadFromCbor(mResponse.getPayload(), ArrayList.class); return (payloadData.isEmpty()); } } \ No newline at end of file diff --git a/cloud/resourcedirectory/src/test/java/org/iotivity/cloud/testrdserver/RDServerTestUtils.java b/cloud/resourcedirectory/src/test/java/org/iotivity/cloud/testrdserver/RDServerTestUtils.java index 7859888..4b06246 100644 --- a/cloud/resourcedirectory/src/test/java/org/iotivity/cloud/testrdserver/RDServerTestUtils.java +++ b/cloud/resourcedirectory/src/test/java/org/iotivity/cloud/testrdserver/RDServerTestUtils.java @@ -19,6 +19,7 @@ public class RDServerTestUtils { public static final String RES_PRS_URI = Constants.RESOURCE_PRESENCE_FULL_URI; public static IRequest makePublishRequest() throws Exception { + HashMap payload = new HashMap<>(); payload.put(Constants.DEVICE_ID, DI); ArrayList> publishLinks = new ArrayList<>(); @@ -33,6 +34,8 @@ public class RDServerTestUtils { 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> cbor = new Cbor<>(); diff --git a/cloud/resourcedirectory/src/test/java/org/iotivity/cloud/testrdserver/ResourceDirectoryResourceTest.java b/cloud/resourcedirectory/src/test/java/org/iotivity/cloud/testrdserver/ResourceDirectoryResourceTest.java index 4d67b08..8acc787 100644 --- a/cloud/resourcedirectory/src/test/java/org/iotivity/cloud/testrdserver/ResourceDirectoryResourceTest.java +++ b/cloud/resourcedirectory/src/test/java/org/iotivity/cloud/testrdserver/ResourceDirectoryResourceTest.java @@ -49,14 +49,14 @@ public class ResourceDirectoryResourceTest { private Cbor> 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() { @@ -64,8 +64,8 @@ public class ResourceDirectoryResourceTest { 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()); @@ -83,15 +83,15 @@ public class ResourceDirectoryResourceTest { 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 @@ -102,8 +102,8 @@ public class ResourceDirectoryResourceTest { 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 @@ -116,8 +116,8 @@ public class ResourceDirectoryResourceTest { 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 @@ -130,8 +130,8 @@ public class ResourceDirectoryResourceTest { 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 @@ -145,8 +145,8 @@ public class ResourceDirectoryResourceTest { 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) { diff --git a/cloud/resourcedirectory/src/test/java/org/iotivity/cloud/testrdserver/ResourcePresenceResourceTest.java b/cloud/resourcedirectory/src/test/java/org/iotivity/cloud/testrdserver/ResourcePresenceResourceTest.java index 0c647d1..d2773fa 100644 --- a/cloud/resourcedirectory/src/test/java/org/iotivity/cloud/testrdserver/ResourcePresenceResourceTest.java +++ b/cloud/resourcedirectory/src/test/java/org/iotivity/cloud/testrdserver/ResourcePresenceResourceTest.java @@ -47,24 +47,24 @@ public class ResourcePresenceResourceTest { 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() { @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()); @@ -81,8 +81,8 @@ public class ResourcePresenceResourceTest { 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 @@ -125,8 +125,8 @@ public class ResourcePresenceResourceTest { 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,