[IOT-1616] CSM signaling supported in CoAP D2S communication
[iotivity.git] / cloud / interface / src / test / java / org / iotivity / cloud / ciserver / DeviceServerSystemTest.java
1 /*
2  * //******************************************************************
3  * //
4  * // Copyright 2016 Samsung Electronics All Rights Reserved.
5  * //
6  * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
7  * //
8  * // Licensed under the Apache License, Version 2.0 (the "License");
9  * // you may not use this file except in compliance with the License.
10  * // You may obtain a copy of the License at
11  * //
12  * //      http://www.apache.org/licenses/LICENSE-2.0
13  * //
14  * // Unless required by applicable law or agreed to in writing, software
15  * // distributed under the License is distributed on an "AS IS" BASIS,
16  * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * // See the License for the specific language governing permissions and
18  * // limitations under the License.
19  * //
20  * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
21  */
22
23 package org.iotivity.cloud.ciserver;
24
25 import static java.util.concurrent.TimeUnit.SECONDS;
26 import static org.junit.Assert.assertEquals;
27 import static org.junit.Assert.assertTrue;
28 import static org.mockito.Mockito.mock;
29
30 import java.util.HashMap;
31 import java.util.concurrent.CountDownLatch;
32
33 import org.iotivity.cloud.base.OICConstants;
34 import org.iotivity.cloud.base.device.CoapDevice;
35 import org.iotivity.cloud.base.device.Device;
36 import org.iotivity.cloud.base.device.IRequestChannel;
37 import org.iotivity.cloud.base.protocols.IRequest;
38 import org.iotivity.cloud.base.protocols.IResponse;
39 import org.iotivity.cloud.base.protocols.ISignaling;
40 import org.iotivity.cloud.base.protocols.MessageBuilder;
41 import org.iotivity.cloud.base.protocols.coap.CoapRequest;
42 import org.iotivity.cloud.base.protocols.coap.CoapResponse;
43 import org.iotivity.cloud.base.protocols.coap.CoapSignaling;
44 import org.iotivity.cloud.base.protocols.enums.ContentFormat;
45 import org.iotivity.cloud.base.protocols.enums.RequestMethod;
46 import org.iotivity.cloud.base.protocols.enums.ResponseStatus;
47 import org.iotivity.cloud.base.protocols.enums.SignalingMethod;
48 import org.iotivity.cloud.base.server.CoapServer;
49 import org.iotivity.cloud.base.server.HttpServer;
50 import org.iotivity.cloud.ciserver.DeviceServerSystem.CoapDevicePool;
51 import org.iotivity.cloud.ciserver.DeviceServerSystem.CoapSignalingHandler;
52 import org.iotivity.cloud.ciserver.resources.proxy.account.Account;
53 import org.iotivity.cloud.ciserver.resources.proxy.mq.MessageQueue;
54 import org.iotivity.cloud.ciserver.resources.proxy.rd.ResourceDirectory;
55 import org.iotivity.cloud.ciserver.resources.proxy.rd.ResourceFind;
56 import org.iotivity.cloud.ciserver.resources.proxy.rd.ResourcePresence;
57 import org.iotivity.cloud.util.Cbor;
58 import org.iotivity.cloud.util.Log;
59 import org.junit.Before;
60 import org.junit.Test;
61 import org.mockito.InjectMocks;
62 import org.mockito.Mock;
63 import org.mockito.Mockito;
64 import org.mockito.MockitoAnnotations;
65 import org.mockito.invocation.InvocationOnMock;
66 import org.mockito.stubbing.Answer;
67
68 import io.netty.channel.Channel;
69 import io.netty.channel.ChannelHandlerContext;
70 import io.netty.channel.ChannelId;
71 import io.netty.channel.ChannelPromise;
72 import io.netty.util.Attribute;
73
74 public class DeviceServerSystemTest {
75     private ChannelHandlerContext                   mCtx                  = null;
76     private ChannelHandlerContext                   mCtxSignal            = null;
77     private String                                  mDi                   = "B371C481-38E6-4D47-8320-7688D8A5B58C";
78     private String                                  mUserId               = "testuser";
79     private String                                  mAccessToken          = "1689c70ffa245effc563017fee36d250";
80     private Device                                  mDevice               = mock(
81             Device.class);
82     private CoapDevice                              mMockDevice           = mock(
83             CoapDevice.class);
84     private IResponse                               mRes                  = null;
85     private IRequest                                mReq                  = null;
86     private ISignaling                              mSig                  = null;
87     final CountDownLatch                            mLatch                = new CountDownLatch(
88             1);
89     private Cbor<HashMap<Object, Object>>           mCbor                 = new Cbor<>();
90     @Mock
91     private IRequestChannel                         mRequestChannel;
92
93     @InjectMocks
94     private DeviceServerSystem                      mDeviceServerSystem   = new DeviceServerSystem();
95     @InjectMocks
96     private DeviceServerSystem.CoapLifecycleHandler mCoapLifecycleHandler = mDeviceServerSystem.new CoapLifecycleHandler();
97     @InjectMocks
98     private DeviceServerSystem.CoapAuthHandler      mCoapAuthHandler      = mDeviceServerSystem.new CoapAuthHandler();
99     @InjectMocks
100     private CoapSignalingHandler                    mCoapSignalingHandler = mDeviceServerSystem.new CoapSignalingHandler();
101
102     @Before
103     public void setUp() throws Exception {
104         Log.createfile();
105         MockitoAnnotations.initMocks(this);
106         mRes = null;
107         mReq = null;
108         mCtx = mock(ChannelHandlerContext.class);
109         mCtxSignal = mock(ChannelHandlerContext.class);
110         Cbor<HashMap<Object, Object>> cbor = new Cbor<>();
111         Channel channel = mock(Channel.class);
112         Attribute<Device> attribute = mock(Attribute.class);
113         ChannelId channelId = mock(ChannelId.class);
114         Mockito.doReturn(channel).when(mCtx).channel();
115         Mockito.doReturn(attribute).when(channel).attr(Mockito.any());
116         Mockito.doReturn(channelId).when(channel).id();
117         Mockito.doReturn(
118                 "0000000141f3edcfc2c3000000000001d0000000000000000000000000000000000000")
119                 .when(channelId).asLongText();
120         Mockito.doReturn(mMockDevice).when(attribute).get();
121         Mockito.doReturn("sampleDeviceID").when(mMockDevice).getDeviceId();
122         Mockito.doAnswer(new Answer<Object>() {
123             @Override
124             public CoapRequest answer(InvocationOnMock invocation)
125                     throws Throwable {
126                 Object[] args = invocation.getArguments();
127                 CoapRequest request = (CoapRequest) args[0];
128                 System.out.println(
129                         "\t----------payload : " + request.getPayloadString());
130                 System.out.println(
131                         "\t----------uripath : " + request.getUriPath());
132                 System.out.println(
133                         "\t---------uriquery : " + request.getUriQuery());
134                 mReq = request;
135                 mLatch.countDown();
136                 return null;
137             }
138         }).when(mCtx).fireChannelRead(Mockito.any());
139
140         Mockito.doAnswer(new Answer<Object>() {
141             @Override
142             public CoapSignaling answer(InvocationOnMock invocation)
143                     throws Throwable {
144                 Object[] args = invocation.getArguments();
145                 CoapSignaling signaling = (CoapSignaling) args[0];
146                 System.out.println("\t----------payload : "
147                         + signaling.getPayloadString());
148                 System.out.println("\t----------signaling method : "
149                         + signaling.getSignalingMethod());
150                 if (signaling.getSignalingMethod()
151                         .equals(SignalingMethod.CSM)) {
152                     System.out.println("\t----------CSM Blockwise Transfer : "
153                             + signaling.getCsmBlockWiseTransfer());
154                     System.out.println("\t----------CSM Max Message Size : "
155                             + signaling.getCsmMaxMessageSize());
156                     System.out.println("\t----------CSM Server Name : "
157                             + signaling.getCsmServerName());
158                 }
159                 mSig = signaling;
160                 mLatch.countDown();
161                 return null;
162             }
163         }).when(mCtxSignal).fireChannelRead(Mockito.any());
164
165         Mockito.doAnswer(new Answer<Object>() {
166             @Override
167             public CoapResponse answer(InvocationOnMock invocation)
168                     throws Throwable {
169                 Object[] args = invocation.getArguments();
170                 CoapResponse response = (CoapResponse) args[0];
171                 System.out.println(
172                         "\t----------payload : " + response.getPayloadString());
173                 System.out.println(
174                         "\t----------status : " + response.getStatus());
175                 mRes = response;
176                 mLatch.countDown();
177                 return null;
178             }
179         }).when(mCtx).writeAndFlush(Mockito.any());
180
181     }
182
183     @Test
184     public void testAddHttpServer() throws Exception {
185         HttpServer httpServer = new HttpServer(null);
186         mDeviceServerSystem.addServer(httpServer);
187     }
188
189     @Test
190     public void testAddCoapServer() throws Exception {
191         CoapServer coapServer = new CoapServer(null);
192         mDeviceServerSystem.addServer(coapServer);
193     }
194
195     @Test
196     public void testGetDevicePool() throws Exception {
197         CoapDevicePool devicePool = mDeviceServerSystem.getDevicePool();
198         if (devicePool != null) {
199             System.out.println("devicePool returned :" + devicePool);
200         }
201     }
202
203     @Test
204     public void testAddDevice() throws Exception {
205         CoapDevice coapDevice = new CoapDevice(null);
206         coapDevice.updateDevice(mDi, mUserId, mAccessToken);
207         CoapDevicePool devicePool = mDeviceServerSystem.getDevicePool();
208         devicePool.addDevice(coapDevice);
209     }
210
211     @Test
212     public void testRemoveNotRegisteredDevice() throws Exception {
213         CoapDevice coapDevice = new CoapDevice(null);
214         coapDevice.updateDevice(mDi, mUserId, mAccessToken);
215         CoapDevicePool devicePool = mDeviceServerSystem.getDevicePool();
216         devicePool.removeDevice(coapDevice);
217     }
218
219     @Test
220     public void testRemoveDevice() throws Exception {
221         CoapDevice coapDevice = new CoapDevice(null);
222         coapDevice.updateDevice(mDi, mUserId, mAccessToken);
223         CoapDevicePool devicePool = mDeviceServerSystem.getDevicePool();
224         devicePool.addDevice(coapDevice);
225         devicePool.removeDevice(coapDevice);
226     }
227
228     @Test
229     public void testQueryDevice() throws Exception {
230         CoapDevice coapDevice = new CoapDevice(null);
231         coapDevice.updateDevice(mDi, mUserId, mAccessToken);
232         CoapDevicePool devicePool = mDeviceServerSystem.getDevicePool();
233         devicePool.addDevice(coapDevice);
234         devicePool.queryDevice(mDi);
235     }
236
237     @Test
238     public void testStopSystem() throws Exception {
239         mDeviceServerSystem.stopSystem();
240     }
241
242     @Test
243     public void testAddAccountResource() {
244         Account acHandler = new Account();
245         ResourceDirectory rdHandler = new ResourceDirectory();
246         ResourceFind resHandler = new ResourceFind();
247         ResourcePresence adHandler = new ResourcePresence();
248         MessageQueue mqHandler = new MessageQueue();
249         mDeviceServerSystem.addResource(acHandler);
250         mDeviceServerSystem.addResource(rdHandler);
251         mDeviceServerSystem.addResource(resHandler);
252         mDeviceServerSystem.addResource(adHandler);
253         mDeviceServerSystem.addResource(mqHandler);
254     }
255
256     @Test
257     public void coapAuthHandlerAccountCtxNullChannelReadRequest()
258             throws InterruptedException {
259         System.out.println(
260                 "\t--------------coapAuthHandler Account ctx is null ChannelReadRequest Test------------");
261         Channel channel = mock(Channel.class);
262         Attribute<Device> attribute = mock(Attribute.class);
263         Mockito.doReturn(channel).when(mCtx).channel();
264         Mockito.doReturn(attribute).when(channel).attr(Mockito.any());
265         Mockito.doReturn(null).when(attribute).get();
266         HashMap<String, Object> payloadData = new HashMap<>();
267         payloadData.put(Constants.DEVICE_ID, "sampleDevice");
268
269         IRequest request = MessageBuilder.createRequest(RequestMethod.POST,
270                 OICConstants.ACCOUNT_FULL_URI, null,
271                 ContentFormat.APPLICATION_CBOR,
272                 mCbor.encodingPayloadToCbor(payloadData));
273         mCoapAuthHandler.channelRead(mCtx, request);
274
275         assertEquals(mReq.getUriPath(), OICConstants.ACCOUNT_FULL_URI);
276         assertTrue(mCbor.parsePayloadFromCbor(mReq.getPayload(), HashMap.class)
277                 .containsKey(Constants.DEVICE_ID));
278     }
279
280     @Test
281     public void coapAuthHandlerPingChannelReadRequest()
282             throws InterruptedException {
283         System.out.println(
284                 "\t--------------coapAuthHandler Ping ChannelReadRequest Test------------");
285
286         IRequest request = MessageBuilder.createRequest(RequestMethod.POST,
287                 OICConstants.KEEP_ALIVE_FULL_URI, null, null, null);
288         mCoapAuthHandler.channelRead(mCtx, request);
289
290         assertEquals(mReq.getUriPath(), OICConstants.KEEP_ALIVE_FULL_URI);
291     }
292
293     @Test
294     public void coapAuthHandlerAccountSessionChannelReadRequest()
295             throws InterruptedException {
296         System.out.println(
297                 "\t--------------coapAuthHandler AccountSession ChannelReadRequest Test------------");
298
299         HashMap<String, Object> payloadData = new HashMap<>();
300         payloadData.put(Constants.DEVICE_ID, mDi);
301         payloadData.put(Constants.USER_ID, mAccessToken);
302         payloadData.put(Constants.ACCESS_TOKEN, mAccessToken);
303
304         IRequest request = MessageBuilder.createRequest(RequestMethod.POST,
305                 OICConstants.ACCOUNT_SESSION_FULL_URI, null,
306                 ContentFormat.APPLICATION_CBOR,
307                 mCbor.encodingPayloadToCbor(payloadData));
308         mCoapAuthHandler.channelRead(mCtx, request);
309
310         assertEquals(mReq.getUriPath(), OICConstants.ACCOUNT_SESSION_FULL_URI);
311         assertTrue(mCbor.parsePayloadFromCbor(mReq.getPayload(), HashMap.class)
312                 .containsKey(Constants.DEVICE_ID));
313         assertTrue(mCbor.parsePayloadFromCbor(mReq.getPayload(), HashMap.class)
314                 .containsKey(Constants.USER_ID));
315         assertTrue(mCbor.parsePayloadFromCbor(mReq.getPayload(), HashMap.class)
316                 .containsKey(Constants.ACCESS_TOKEN));
317     }
318
319     @Test
320     public void coapAuthHandlerAccountSessionCtxNullChannelReadRequest()
321             throws InterruptedException {
322         System.out.println(
323                 "\t--------------coapAuthHandler AccountSession ctx is null ChannelReadRequest Test------------");
324         Channel channel = mock(Channel.class);
325         Attribute<Device> attribute = mock(Attribute.class);
326         Mockito.doReturn(channel).when(mCtx).channel();
327         Mockito.doReturn(attribute).when(channel).attr(Mockito.any());
328         Mockito.doReturn(null).when(attribute).get();
329         HashMap<String, Object> payloadData = new HashMap<>();
330         payloadData.put(Constants.DEVICE_ID, mDi);
331         payloadData.put(Constants.USER_ID, mAccessToken);
332         payloadData.put(Constants.ACCESS_TOKEN, mAccessToken);
333
334         IRequest request = MessageBuilder.createRequest(RequestMethod.POST,
335                 OICConstants.ACCOUNT_SESSION_FULL_URI, null,
336                 ContentFormat.APPLICATION_CBOR,
337                 mCbor.encodingPayloadToCbor(payloadData));
338         mCoapAuthHandler.channelRead(mCtx, request);
339
340         assertEquals(mReq.getUriPath(), OICConstants.ACCOUNT_SESSION_FULL_URI);
341         assertTrue(mCbor.parsePayloadFromCbor(mReq.getPayload(), HashMap.class)
342                 .containsKey(Constants.DEVICE_ID));
343         assertTrue(mCbor.parsePayloadFromCbor(mReq.getPayload(), HashMap.class)
344                 .containsKey(Constants.USER_ID));
345         assertTrue(mCbor.parsePayloadFromCbor(mReq.getPayload(), HashMap.class)
346                 .containsKey(Constants.ACCESS_TOKEN));
347         mLatch.countDown();
348     }
349
350     @Test
351     public void coapAuthHandlerUnAuthorizedExceptionChannelReadRequest()
352             throws Exception {
353
354         System.out.println(
355                 "\t--------------coapAuthHandler UnAuthorizedException ChannelReadRequest Test------------");
356
357         IRequest request = MessageBuilder.createRequest(RequestMethod.POST,
358                 OICConstants.ACCOUNT_SESSION_FULL_URI + "/" + "errorURI", null,
359                 null, null);
360         mCoapAuthHandler.channelRead(mCtx, request);
361         assertEquals(mRes.getStatus(), ResponseStatus.UNAUTHORIZED);
362     }
363
364     @Test
365     public void coapAuthHandlerAccountSessionChannelReadResponse()
366             throws Exception {
367         System.out.println(
368                 "\t--------------coapAuthHandler AccountSession ChannelReadResponse Test------------");
369
370         IRequest request = MessageBuilder.createRequest(RequestMethod.POST,
371                 OICConstants.ACCOUNT_SESSION_FULL_URI, null, null, null);
372         HashMap<String, Object> payloadData = new HashMap<>();
373         payloadData.put(Constants.EXPIRES_IN, 3300);
374         IResponse response = MessageBuilder.createResponse(request,
375                 ResponseStatus.CHANGED, ContentFormat.APPLICATION_CBOR,
376                 mCbor.encodingPayloadToCbor(payloadData));
377         ChannelPromise channelPromise = null;
378         mCoapAuthHandler.write(mCtx, response, channelPromise);
379         assertEquals(((IRequest) mRes).getUriPath(),
380                 OICConstants.ACCOUNT_SESSION_FULL_URI);
381         assertTrue(mCbor.parsePayloadFromCbor(mRes.getPayload(), HashMap.class)
382                 .containsKey(Constants.EXPIRES_IN));
383     }
384
385     @Test
386     public void coapAuthHandlerUnAuthorizedExceptionChannelReadResponse()
387             throws Exception {
388         System.out.println(
389                 "\t--------------coapAuthHandler UnAuthorizedException ChannelReadResponse Test------------");
390
391         IRequest request = MessageBuilder.createRequest(RequestMethod.POST,
392                 OICConstants.ACCOUNT_SESSION_FULL_URI, null, null, null);
393         HashMap<String, Object> payloadData = new HashMap<>();
394         payloadData.put(Constants.EXPIRES_IN, -1);
395         IResponse response = MessageBuilder.createResponse(request,
396                 ResponseStatus.UNAUTHORIZED, ContentFormat.APPLICATION_CBOR,
397                 mCbor.encodingPayloadToCbor(payloadData));
398         ChannelPromise channelPromise = null;
399         mCoapAuthHandler.write(mCtx, response, channelPromise);
400         assertEquals(mRes.getStatus(), ResponseStatus.UNAUTHORIZED);
401     }
402
403     @Test
404     public void coapAuthHandlerCSMSignaling() throws Exception {
405
406         System.out.println(
407                 "\t--------------coapAuthHandler coapAuthHandlerCSMSignaling Test------------");
408         ISignaling signal = MessageBuilder.createSignaling(SignalingMethod.CSM);
409         CoapSignaling signaling = (CoapSignaling) signal;
410         signaling.setCsmBlockWiseTransfer(true);
411         signaling.setCsmMaxMessageSize(1124);
412         signaling.setCsmServerName("default_server_name");
413         mCoapSignalingHandler.channelRead(mCtxSignal, signal);
414         assertEquals(mSig.getSignalingMethod(), SignalingMethod.CSM);
415     }
416
417     @Test
418     public void CoapLifecycleHandlerChannelReadRequest()
419             throws InterruptedException {
420         System.out.println(
421                 "\t--------------CoapLifecycleHandler ChannelReadCoapRequest Test------------");
422
423         mCoapLifecycleHandler.channelRead(mCtx,
424                 MessageBuilder.createRequest(RequestMethod.GET, null, null));
425         assertTrue(mLatch.await(1L, SECONDS));
426     }
427
428     @Test
429     public void CoapLifecycleHandlerUnAuthorizedExceptionChannelReadRequest()
430             throws Exception {
431         System.out.println(
432                 "\t--------------CoapLifecycleHandler ChannelReadCoapRequest Test------------");
433         Channel channel = mock(Channel.class);
434         Attribute<Device> attribute = mock(Attribute.class);
435         Mockito.doReturn(channel).when(mCtx).channel();
436         Mockito.doReturn(attribute).when(channel).attr(Mockito.any());
437         Mockito.doReturn(mMockDevice).when(attribute).get();
438         Mockito.doReturn(true).when(mMockDevice).isExpiredTime();
439         ChannelId channelId = mock(ChannelId.class);
440         Mockito.doReturn(channelId).when(channel).id();
441         Mockito.doReturn(
442                 "0000000141f3edcfc2c3000000000001d0000000000000000000000000000000000000")
443                 .when(channelId).asLongText();
444         mCoapLifecycleHandler.channelRead(mCtx,
445                 MessageBuilder.createRequest(RequestMethod.GET, null, null));
446         assertEquals(mRes.getStatus(), ResponseStatus.UNAUTHORIZED);
447     }
448
449     @Test
450     public void CoapLifecycleHandlerchannelActive() throws Exception {
451         System.out.println(
452                 "\t--------------CoapLifecycleHandler ChannelReadCoapRequest    Test------------");
453         Mockito.doAnswer(new Answer<Object>() {
454             @Override
455             public CoapRequest answer(InvocationOnMock invocation)
456                     throws Throwable {
457
458                 Object[] args = invocation.getArguments();
459                 CoapRequest req = (CoapRequest) args[0];
460                 assertTrue(req.getUriPath().contains(Constants.PREFIX_OIC + "/"
461                         + Constants.DEVICE_PRESENCE_URI));
462                 assertTrue(mCbor
463                         .parsePayloadFromCbor(req.getPayload(), HashMap.class)
464                         .containsKey(Constants.PRESENCE_STATE));
465
466                 mLatch.countDown();
467                 return null;
468             }
469
470         }).when(mRequestChannel).sendRequest(Mockito.any(), Mockito.any());
471         mCoapLifecycleHandler.channelActive(mCtx);
472     }
473
474     @Test
475     public void CoapLifecycleHandlerchannelInActive() throws Exception {
476         System.out.println(
477                 "\t--------------CoapLifecycleHandler ChannelReadCoapRequest    Test------------");
478
479         Mockito.doAnswer(new Answer<Object>() {
480             @Override
481             public CoapRequest answer(InvocationOnMock invocation)
482                     throws Throwable {
483
484                 Object[] args = invocation.getArguments();
485                 CoapRequest req = (CoapRequest) args[0];
486                 assertTrue(req.getUriPath().contains(Constants.PREFIX_OIC + "/"
487                         + Constants.DEVICE_PRESENCE_URI));
488                 assertTrue(mCbor
489                         .parsePayloadFromCbor(req.getPayload(), HashMap.class)
490                         .containsKey(Constants.PRESENCE_STATE));
491
492                 mLatch.countDown();
493                 return null;
494             }
495
496         }).when(mRequestChannel).sendRequest(Mockito.any(), Mockito.any());
497         mCoapLifecycleHandler.channelInactive(mCtx);
498     }
499
500 }