remove prefix .well-known uri & change from 'ocf' to 'oic' uri
[iotivity.git] / cloud / account / src / test / java / org / iotivity / cloud / accountserver / resources / acl / group / GroupResourceTest.java
1
2 /*
3  * //******************************************************************
4  * //
5  * // Copyright 2016 Samsung Electronics All Rights Reserved.
6  * //
7  * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
8  * //
9  * // Licensed under the Apache License, Version 2.0 (the "License");
10  * // you may not use this file except in compliance with the License.
11  * // You may obtain a copy of the License at
12  * //
13  * //      http://www.apache.org/licenses/LICENSE-2.0
14  * //
15  * // Unless required by applicable law or agreed to in writing, software
16  * // distributed under the License is distributed on an "AS IS" BASIS,
17  * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * // See the License for the specific language governing permissions and
19  * // limitations under the License.
20  * //
21  * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
22  */
23 package org.iotivity.cloud.accountserver.resources.acl.group;
24
25 import static java.util.concurrent.TimeUnit.SECONDS;
26 import static org.junit.Assert.assertTrue;
27 import static org.mockito.Mockito.mock;
28
29 import java.util.ArrayList;
30 import java.util.HashMap;
31 import java.util.concurrent.CountDownLatch;
32
33 import org.iotivity.cloud.accountserver.Constants;
34 import org.iotivity.cloud.accountserver.db.MongoDB;
35 import org.iotivity.cloud.base.device.CoapDevice;
36 import org.iotivity.cloud.base.exception.ServerException;
37 import org.iotivity.cloud.base.protocols.IRequest;
38 import org.iotivity.cloud.base.protocols.IResponse;
39 import org.iotivity.cloud.base.protocols.MessageBuilder;
40 import org.iotivity.cloud.base.protocols.coap.CoapRequest;
41 import org.iotivity.cloud.base.protocols.coap.CoapResponse;
42 import org.iotivity.cloud.base.protocols.enums.ContentFormat;
43 import org.iotivity.cloud.base.protocols.enums.Observe;
44 import org.iotivity.cloud.base.protocols.enums.RequestMethod;
45 import org.iotivity.cloud.base.protocols.enums.ResponseStatus;
46 import org.iotivity.cloud.util.Cbor;
47 import org.junit.Before;
48 import org.junit.Test;
49 import org.mockito.Mockito;
50 import org.mockito.MockitoAnnotations;
51 import org.mockito.invocation.InvocationOnMock;
52 import org.mockito.stubbing.Answer;
53
54 public class GroupResourceTest {
55     private static final String           GROUP_URI         = Constants.GROUP_FULL_URI;
56     private final String                  mUserUuid         = "bc38f243-aab5-44d3-8eb9-4a54ebbaf359";
57     private String                        mGroupId          = null;
58     final CountDownLatch                  mLatch            = new CountDownLatch(
59             1);
60     private CoapDevice                    mMockDevice       = Mockito
61             .mock(CoapDevice.class);
62     private Cbor<HashMap<String, Object>> mCbor             = new Cbor<>();
63     private IResponse                     mResponse         = null;
64     private IResponse                     mResponseObserver = null;
65     private GroupResource                 mGroupResource    = new GroupResource();
66
67     @Before
68     public void setUp() throws Exception {
69         MockitoAnnotations.initMocks(this);
70         // reset data base
71         resetDB();
72         Mockito.doAnswer(new Answer<Object>() {
73             @Override
74             public CoapResponse answer(InvocationOnMock invocation)
75                     throws Throwable {
76                 Object[] args = invocation.getArguments();
77                 CoapResponse resp = (CoapResponse) args[0];
78                 System.out.println(
79                         "\t----------payload : " + resp.getPayloadString());
80                 System.out.println("\t---------method : " + resp.getStatus());
81                 mResponse = resp;
82                 if (mGroupId == null) {
83                     HashMap<String, Object> payloadData = mCbor
84                             .parsePayloadFromCbor(resp.getPayload(),
85                                     HashMap.class);
86                     if (payloadData.containsKey("gid")) {
87                         mGroupId = (String) payloadData.get("gid");
88                     }
89                 }
90                 mLatch.countDown();
91                 return null;
92             }
93         }).when(mMockDevice).sendResponse(Mockito.anyObject());
94     }
95
96     @Test
97     public void testCreateGroup() throws Exception {
98         getTestMethodName();
99         createGroup(mMockDevice, mUserUuid + "create", "Public");
100         assertTrue(methodCheck(mResponse, ResponseStatus.CHANGED));
101         assertTrue(hashmapCheck(mResponse, "gid"));
102         assertTrue(mLatch.await(2L, SECONDS));
103     }
104
105     @Test
106     public void testFindMyGroup() throws Exception {
107         getTestMethodName();
108         String uuid = this.mUserUuid + "find";
109         createGroup(mMockDevice, uuid, "Public");
110         findGroup(mMockDevice, uuid);
111         assertTrue(methodCheck(mResponse, ResponseStatus.CONTENT));
112         assertTrue(hashmapCheck(mResponse, "gidlist"));
113         assertTrue(mLatch.await(2L, SECONDS));
114     }
115
116     @Test(expected = ServerException.BadRequestException.class)
117     public void testCreateGroupNotSupportedType() throws Exception {
118         getTestMethodName();
119         String uuid = this.mUserUuid + "delete";
120         createGroup(mMockDevice, uuid, "NotSupported");
121         deleteGroup(mMockDevice, uuid);
122     }
123
124     @Test
125     public void testDeleteGroup() throws Exception {
126         getTestMethodName();
127         String uuid = this.mUserUuid + "delete";
128         createGroup(mMockDevice, uuid, "Public");
129         deleteGroup(mMockDevice, uuid);
130         assertTrue(methodCheck(mResponse, ResponseStatus.DELETED));
131         assertTrue(mLatch.await(2L, SECONDS));
132     }
133
134     @Test(expected = ServerException.PreconditionFailedException.class)
135     public void testDeleteGroupWithoutGid() throws Exception {
136         getTestMethodName();
137         String uuid = this.mUserUuid + "delete";
138         createGroup(mMockDevice, uuid, "Public");
139         deleteGroupWithoutGid(mMockDevice, uuid);
140     }
141
142     @Test
143     public void testAddDeviceAndUserToGroup() throws Exception {
144         getTestMethodName();
145         String uuid = this.mUserUuid + "AddDeviceAndUser";
146         createGroup(mMockDevice, uuid, "Public");
147         ArrayList<String> midList = new ArrayList<>();
148         midList.add("member0001");
149         midList.add("member0002");
150         ArrayList<String> diList = new ArrayList<>();
151         diList.add("device0001");
152         diList.add("device0002");
153         addDeviceAndUser(mMockDevice, midList, diList);
154     }
155
156     @Test
157     public void testDeleteDeviceAndUserToGroup() throws Exception {
158         getTestMethodName();
159         String uuid = this.mUserUuid + "AddDeviceAndUser";
160         createGroup(mMockDevice, uuid, "Public");
161         ArrayList<String> midList = new ArrayList<>();
162         midList.add("member0001");
163         midList.add("member0002");
164         ArrayList<String> diList = new ArrayList<>();
165         diList.add("device0001");
166         diList.add("device0002");
167         addDeviceAndUser(mMockDevice, midList, diList);
168         deleteDeviceAndUser(mMockDevice, midList, diList);
169     }
170
171     @Test(expected = ServerException.BadRequestException.class)
172     public void testDeleteGroupInvalidGmid() throws Exception {
173         getTestMethodName();
174         String uuid = this.mUserUuid + "delete";
175         createGroup(mMockDevice, uuid, "Public");
176         deleteGroup(mMockDevice, uuid + "invlidGmid");
177     }
178
179     @Test
180     public void testJoinToinvitedGroup() throws Exception {
181         getTestMethodName();
182         String uuid = this.mUserUuid + "join";
183         createGroup(mMockDevice, uuid, "Public");
184         joinGroup(mMockDevice, "u0002");
185         assertTrue(methodCheck(mResponse, ResponseStatus.CHANGED));
186         assertTrue(mLatch.await(2L, SECONDS));
187     }
188
189     @Test
190     public void testObserveGroup() throws Exception {
191         getTestMethodName();
192         String uuid = this.mUserUuid + "obs";
193         createGroup(mMockDevice, uuid, "Public");
194         observeGroup(mMockDevice, uuid);
195         assertTrue(methodCheck(mResponse, ResponseStatus.CONTENT));
196         assertTrue(hashmapCheck(mResponse, "gid"));
197         assertTrue(hashmapCheck(mResponse, "gmid"));
198         assertTrue(hashmapCheck(mResponse, "midlist"));
199         assertTrue(hashmapCheck(mResponse, "dilist"));
200         assertTrue(mLatch.await(2L, SECONDS));
201     }
202
203     @Test
204     public void testObserveDeregisterGroup() throws Exception {
205         getTestMethodName();
206         String uuid = this.mUserUuid + "obs";
207         createGroup(mMockDevice, uuid, "Public");
208         observeGroup(mMockDevice, uuid);
209         observeDeregisterGroup(mMockDevice, uuid);
210         assertTrue(methodCheck(mResponse, ResponseStatus.CONTENT));
211     }
212
213     @Test
214     public void testShareDeviceIntoGroup() throws Exception {
215         getTestMethodName();
216         String uuid = this.mUserUuid + "share";
217         createGroup(mMockDevice, uuid, "Public");
218         shareDevice(mMockDevice, "d0002");
219         assertTrue(methodCheck(mResponse, ResponseStatus.CHANGED));
220         assertTrue(mLatch.await(2L, SECONDS));
221     }
222
223     @Test
224     public void testShareDeviceNotification() throws Exception {
225         getTestMethodName();
226         String uuid = this.mUserUuid + "share";
227         String uuidGuest = "u0002guest";
228         CoapDevice mockDeviceGuest = mock(CoapDevice.class);
229         CountDownLatch memberLatch = new CountDownLatch(1);
230         Mockito.doAnswer(new Answer<Object>() {
231             @Override
232             public CoapResponse answer(InvocationOnMock invocation)
233                     throws Throwable {
234                 Object[] args = invocation.getArguments();
235                 CoapResponse resp = (CoapResponse) args[0];
236                 System.out.println("\t----------new member payload : "
237                         + resp.getPayloadString());
238                 System.out.println(
239                         "\t---------new member method : " + resp.getStatus());
240                 memberLatch.countDown();
241                 mResponseObserver = resp;
242                 return resp;
243             }
244         }).when(mockDeviceGuest).sendResponse(Mockito.anyObject());
245         createGroup(mMockDevice, uuid, "Public");
246         joinGroup(mockDeviceGuest, uuidGuest);
247         observeGroup(mockDeviceGuest, uuidGuest);
248         shareDevice(mMockDevice, "d0002");
249         // assertion for the group master
250         assertTrue(methodCheck(mResponse, ResponseStatus.CHANGED));
251         // assertion for the observer
252         assertTrue(methodCheck(mResponseObserver, ResponseStatus.CONTENT));
253         assertTrue(mLatch.await(2L, SECONDS));
254         assertTrue(memberLatch.await(2L, SECONDS));
255     }
256
257     public void addDeviceAndUser(CoapDevice device, ArrayList<String> midList,
258             ArrayList<String> diList) throws Exception {
259         HashMap<String, Object> payloadData = new HashMap<>();
260         payloadData.put("midlist", midList);
261         payloadData.put("dilist", diList);
262         IRequest request = MessageBuilder.createRequest(RequestMethod.POST,
263                 GROUP_URI + "/" + mGroupId, null,
264                 ContentFormat.APPLICATION_CBOR,
265                 mCbor.encodingPayloadToCbor(payloadData));
266         System.out.println("-----add Device and User : " + payloadData);
267         mGroupResource.onDefaultRequestReceived(device, request);
268     }
269
270     public void deleteDeviceAndUser(CoapDevice device,
271             ArrayList<String> midList, ArrayList<String> diList)
272             throws Exception {
273         String midListString = "";
274         String didListString = "";
275         for (String mid : midList) {
276             midListString += "midlist=";
277             midListString += mid;
278             midListString += ";";
279         }
280         for (String di : diList) {
281             didListString += "dilist=";
282             didListString += di;
283             didListString += ";";
284         }
285         System.out.println("-----delete Device and User, Query: "
286                 + midListString + didListString);
287         IRequest request = MessageBuilder.createRequest(RequestMethod.DELETE,
288                 GROUP_URI + "/" + mGroupId, midListString + didListString);
289         mGroupResource.onDefaultRequestReceived(device, request);
290     }
291
292     private void shareDevice(CoapDevice device, String deviceId)
293             throws Exception {
294         System.out.println("-----Share Device");
295         IRequest request = null;
296         request = createShareDeviceRequest(deviceId);
297         mGroupResource.onDefaultRequestReceived(device, request);
298     }
299
300     private void createGroup(CoapDevice device, String gmid, String gtype)
301             throws Exception {
302         System.out.println("-----Create Group");
303         IRequest request = null;
304         request = createGroupRequest(gmid, gtype);
305         mGroupResource.onDefaultRequestReceived(device, request);
306     }
307
308     private void findGroup(CoapDevice device, String uuid) throws Exception {
309         System.out.println("-----Find Group");
310         IRequest request = null;
311         request = findGroupRequest(uuid);
312         mGroupResource.onDefaultRequestReceived(device, request);
313     }
314
315     private void observeDeregisterGroup(CoapDevice device, String uuid)
316             throws Exception {
317         System.out.println("-----Observe Deregister Group");
318         IRequest request = null;
319         request = observeDeregisterGroupRequest(uuid);
320         mGroupResource.onDefaultRequestReceived(device, request);
321     }
322
323     private void observeGroup(CoapDevice device, String uuid) throws Exception {
324         System.out.println("-----Observe Group");
325         IRequest request = null;
326         request = observeGroupRequest(uuid);
327         mGroupResource.onDefaultRequestReceived(device, request);
328     }
329
330     private void joinGroup(CoapDevice device, String uuid) throws Exception {
331         System.out.println("-----Join Group");
332         IRequest request = null;
333         request = joinGroupRequest(uuid);
334         mGroupResource.onDefaultRequestReceived(device, request);
335     }
336
337     private void deleteGroup(CoapDevice device, String uuid) throws Exception {
338         System.out.println("-----Delete Group");
339         IRequest request = null;
340         request = deleteGroupRequest(uuid);
341         mGroupResource.onDefaultRequestReceived(device, request);
342     }
343
344     private void deleteGroupWithoutGid(CoapDevice device, String uuid)
345             throws Exception {
346         System.out.println("-----Delete Group");
347         IRequest request = null;
348         request = deleteGroupWithoutGidRequest(uuid);
349         mGroupResource.onDefaultRequestReceived(device, request);
350     }
351
352     private IRequest deleteGroupWithoutGidRequest(String uuid) {
353         IRequest request = null;
354         request = MessageBuilder.createRequest(RequestMethod.DELETE, GROUP_URI,
355                 "gmid=" + uuid);
356         return request;
357     }
358
359     private IRequest deleteGroupRequest(String uuid) {
360         IRequest request = null;
361         request = MessageBuilder.createRequest(RequestMethod.DELETE, GROUP_URI,
362                 "gid=" + mGroupId + ";" + "gmid=" + uuid);
363         return request;
364     }
365
366     private IRequest findGroupRequest(String uuid) {
367         IRequest request = null;
368         request = MessageBuilder.createRequest(RequestMethod.GET, GROUP_URI,
369                 "mid=" + uuid);
370         return request;
371     }
372
373     private IRequest createShareDeviceRequest(String deviceId) {
374         IRequest request = null;
375         HashMap<String, Object> payloadData = new HashMap<String, Object>();
376         ArrayList<String> diList = new ArrayList<>();
377         diList.add(deviceId);
378         payloadData.put("dilist", diList);
379         request = MessageBuilder.createRequest(RequestMethod.POST,
380                 GROUP_URI + "/" + mGroupId, null,
381                 ContentFormat.APPLICATION_CBOR,
382                 mCbor.encodingPayloadToCbor(payloadData));
383         return request;
384     }
385
386     private IRequest observeDeregisterGroupRequest(String uuid) {
387         IRequest request = null;
388         request = MessageBuilder.createRequest(RequestMethod.GET,
389                 GROUP_URI + "/" + mGroupId, "mid=" + uuid);
390         ((CoapRequest) request).setObserve(Observe.UNSUBSCRIBE);
391         return request;
392     }
393
394     private IRequest observeGroupRequest(String uuid) {
395         IRequest request = null;
396         request = MessageBuilder.createRequest(RequestMethod.GET,
397                 GROUP_URI + "/" + mGroupId, "mid=" + uuid);
398         ((CoapRequest) request).setObserve(Observe.SUBSCRIBE);
399         return request;
400     }
401
402     private IRequest joinGroupRequest(String uuid) {
403         IRequest request = null;
404         HashMap<String, Object> payloadData = new HashMap<String, Object>();
405         ArrayList<String> midList = new ArrayList<>();
406         midList.add(uuid);
407         payloadData.put("midlist", midList);
408         request = MessageBuilder.createRequest(RequestMethod.POST,
409                 GROUP_URI + "/" + mGroupId, null,
410                 ContentFormat.APPLICATION_CBOR,
411                 mCbor.encodingPayloadToCbor(payloadData));
412         return request;
413     }
414
415     private IRequest createGroupRequest(String uuid, String gtype) {
416         IRequest request = null;
417         HashMap<String, Object> payloadData = new HashMap<String, Object>();
418         payloadData.put("gmid", uuid);
419         payloadData.put("gtype", gtype);
420         request = MessageBuilder.createRequest(RequestMethod.POST, GROUP_URI,
421                 null, ContentFormat.APPLICATION_CBOR,
422                 mCbor.encodingPayloadToCbor(payloadData));
423         return request;
424     }
425
426     private boolean hashmapCheck(IResponse response, String propertyName) {
427         HashMap<String, Object> payloadData = mCbor
428                 .parsePayloadFromCbor(response.getPayload(), HashMap.class);
429         if (payloadData.containsKey(propertyName))
430             return true;
431         else
432             return false;
433     }
434
435     private boolean methodCheck(IResponse response,
436             ResponseStatus responseStatus) {
437         if (responseStatus == response.getStatus())
438             return true;
439         else
440             return false;
441     }
442
443     private void getTestMethodName() {
444         StackTraceElement[] stacks = new Throwable().getStackTrace();
445         StackTraceElement currentStack = stacks[1];
446         System.out.println("\t---Test Name : " + currentStack.getMethodName());
447     }
448
449     public void resetDB() throws Exception {
450         MongoDB mongoDB = new MongoDB(Constants.DB_NAME);
451         mongoDB.deleteTable(Constants.GROUP_TABLE);
452         mongoDB.createTable(Constants.GROUP_TABLE);
453         mongoDB.deleteTable(Constants.USER_TABLE);
454         mongoDB.createTable(Constants.USER_TABLE);
455         mongoDB.deleteTable(Constants.TOKEN_TABLE);
456         mongoDB.createTable(Constants.TOKEN_TABLE);
457     }
458 }