[IOT-1604] Fix cloud routing code
[iotivity.git] / cloud / interface / src / test / java / org / iotivity / cloud / ciserver / resources / proxy / rd / ResourceDirectoryTest.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.resources.proxy.rd;
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.ArrayList;
31 import java.util.HashMap;
32 import java.util.concurrent.CountDownLatch;
33
34 import org.iotivity.cloud.base.device.CoapDevice;
35 import org.iotivity.cloud.base.device.IRequestChannel;
36 import org.iotivity.cloud.base.protocols.IRequest;
37 import org.iotivity.cloud.base.protocols.IResponse;
38 import org.iotivity.cloud.base.protocols.MessageBuilder;
39 import org.iotivity.cloud.base.protocols.coap.CoapRequest;
40 import org.iotivity.cloud.base.protocols.coap.CoapResponse;
41 import org.iotivity.cloud.base.protocols.enums.ContentFormat;
42 import org.iotivity.cloud.base.protocols.enums.RequestMethod;
43 import org.iotivity.cloud.base.protocols.enums.ResponseStatus;
44 import org.iotivity.cloud.ciserver.Constants;
45 import org.iotivity.cloud.ciserver.DeviceServerSystem;
46 import org.iotivity.cloud.util.Cbor;
47 import org.junit.Before;
48 import org.junit.Test;
49 import org.mockito.InjectMocks;
50 import org.mockito.Mock;
51 import org.mockito.Mockito;
52 import org.mockito.MockitoAnnotations;
53 import org.mockito.invocation.InvocationOnMock;
54 import org.mockito.stubbing.Answer;
55
56 public class ResourceDirectoryTest {
57     private static final String TEST_RD_URI         = Constants.RD_FULL_URI;
58     public static final String  DEVICE_LIST_KEY     = "devices";
59
60     private String              mDi                 = "B371C481-38E6-4D47-8320-7688D8A5B58C";
61     String                      mUserId             = "testuser";
62     private CoapDevice          mMockDevice         = null;
63     IRequest                    mReqRDServer        = null;
64     IRequest                    mReqASServer        = null;
65     DeviceServerSystem          mDeviceServerSystem = new DeviceServerSystem();
66     final CountDownLatch        mLatch              = new CountDownLatch(1);
67     @Mock(name = "mRDServer")
68     IRequestChannel             mRequestChannelRDServer;
69     @Mock(name = "mASServer")
70     IRequestChannel             mRequestChannelASServer;
71
72     @InjectMocks
73     ResourceDirectory           mRdHandler          = new ResourceDirectory();
74
75     @Before
76     public void setUp() throws Exception {
77         MockitoAnnotations.initMocks(this);
78         mDeviceServerSystem.addResource(mRdHandler);
79         mMockDevice = mock(CoapDevice.class);
80         Mockito.doReturn(mUserId).when(mMockDevice).getUserId();
81         Mockito.doReturn(mDi).when(mMockDevice).getDeviceId();
82
83         Mockito.doAnswer(new Answer<Object>() {
84             @Override
85             public CoapRequest answer(InvocationOnMock invocation)
86                     throws Throwable {
87                 Object[] args = invocation.getArguments();
88                 CoapRequest request = (CoapRequest) args[0];
89                 System.out.println("\t----------mRDServer --------------");
90                 System.out.println(
91                         "\t----------payload : " + request.getPayloadString());
92                 System.out.println("\t----------uripath : "
93                         + request.getMethod() + " " + request.getUriPath());
94                 System.out.println(
95                         "\t---------uriquery : " + request.getUriQuery());
96                 mReqRDServer = request;
97                 mLatch.countDown();
98                 return request;
99             }
100         }).when(mRequestChannelRDServer).sendRequest(
101                 Mockito.any(IRequest.class), Mockito.any(CoapDevice.class));
102
103         Mockito.doAnswer(new Answer<Object>() {
104             @Override
105             public CoapRequest answer(InvocationOnMock invocation)
106                     throws Throwable {
107                 Object[] args = invocation.getArguments();
108                 CoapRequest request = (CoapRequest) args[0];
109                 System.out.println("\t----------mASServer --------------");
110                 System.out.println(
111                         "\t----------payload : " + request.getPayloadString());
112                 System.out.println("\t----------uripath : "
113                         + request.getMethod() + " " + request.getUriPath());
114                 System.out.println(
115                         "\t---------uriquery : " + request.getUriQuery());
116                 mReqASServer = request;
117                 mLatch.countDown();
118                 return request;
119             }
120         }).when(mRequestChannelASServer).sendRequest(
121                 Mockito.any(IRequest.class), Mockito.any(CoapDevice.class));
122
123     }
124
125     @Test
126     public void testRDResourcePublishOnRequestReceived() throws Exception {
127         IRequest request = makeResourcePublishRequest();
128         mDeviceServerSystem.onRequestReceived(mMockDevice, request);
129         assertTrue(mLatch.await(1L, SECONDS));
130         assertTrue(mReqASServer.getMethod().equals(RequestMethod.POST));
131         assertTrue(mReqASServer.getUriPath()
132                 .contains(Constants.GROUP_FULL_URI + "/"));
133     }
134
135     @Test
136     public void testRDResourceDeleteOnRequestReceived() throws Exception {
137         IRequest request = makeResourceDeleteRequest();
138         mDeviceServerSystem.onRequestReceived(mMockDevice, request);
139         assertTrue(mLatch.await(1L, SECONDS));
140         assertTrue(mReqRDServer.getMethod().equals(RequestMethod.DELETE));
141         assertTrue(mReqRDServer.getUriPath().contains(TEST_RD_URI));
142     }
143
144     IRequest  rdPublishRequest  = makeResourcePublishRequest();
145     IResponse rdPublishResponse = makeResourcePublishResponse();
146
147     @Test
148     public void testRDResourcePublishOnResponseReceived() throws Exception {
149
150         ResourceDirectory.AccountReceiveHandler accountReceiveHandler = mRdHandler.new AccountReceiveHandler(
151                 rdPublishRequest, mMockDevice);
152
153         IRequest request = makeResourcePublishRequest();
154         accountReceiveHandler.onResponseReceived(
155                 MessageBuilder.createResponse(request, ResponseStatus.CHANGED));
156
157         assertEquals(mReqRDServer, rdPublishRequest);
158         assertTrue(mLatch.await(1L, SECONDS));
159     }
160
161     @Test
162     public void testRDResourcePublishPayloadConverted() throws Exception {
163
164         ResourceDirectory.AccountReceiveHandler accountReceiveHandler = mRdHandler.new AccountReceiveHandler(
165                 rdPublishRequest, mMockDevice);
166
167         IRequest request = makeResourcePublishRequest();
168         accountReceiveHandler.onResponseReceived(
169                 MessageBuilder.createResponse(request, ResponseStatus.CHANGED));
170
171         assertEquals(getHrefInTestPublishPayload(mReqRDServer.getPayload()),
172                 "/oic/route/" + mDi + "/a/light");
173     }
174
175     @Test
176     public void testRDResourcePublishResponse() throws Exception {
177
178         ResourceDirectory.PublishResponseHandler publishResponseHandler = mRdHandler.new PublishResponseHandler(
179                 mMockDevice);
180
181         CountDownLatch latch = new CountDownLatch(1);
182
183         Mockito.doAnswer(new Answer<Object>() {
184             @Override
185             public CoapResponse answer(InvocationOnMock invocation)
186                     throws Throwable {
187                 Object[] args = invocation.getArguments();
188                 CoapResponse resp = (CoapResponse) args[0];
189
190                 assertEquals(getHrefInTestPublishPayload(resp.getPayload()),
191                         "/a/light");
192
193                 latch.countDown();
194                 return resp;
195             }
196         }).when(mMockDevice).sendResponse(Mockito.anyObject());
197
198         publishResponseHandler
199                 .onResponseReceived(makeResourcePublishResponse());
200
201         assertTrue(latch.await(1L, SECONDS));
202     }
203
204     private IRequest makeResourcePublishRequest() {
205         HashMap<Object, Object> payload = new HashMap<>();
206         payload.put(Constants.DEVICE_ID, mDi);
207         ArrayList<HashMap<Object, Object>> publishLinks = new ArrayList<>();
208         HashMap<Object, Object> link = new HashMap<>();
209         link.put("href", "/a/light");
210         ArrayList<String> rt = new ArrayList<String>();
211         rt.add("core.light");
212         ArrayList<String> itf = new ArrayList<String>();
213         itf.add("oic.if.baseline");
214         HashMap<String, Object> policy = new HashMap<>();
215         policy.put("bm", 5);
216         link.put("rt", rt);
217         link.put("if", itf);
218         link.put("p", policy);
219         publishLinks.add(link);
220         payload.put("links", publishLinks);
221         Cbor<HashMap<Object, Object>> cbor = new Cbor<>();
222         IRequest request = MessageBuilder.createRequest(RequestMethod.POST,
223                 TEST_RD_URI, "rt" + "=" + "oic.wk.rdpub",
224                 ContentFormat.APPLICATION_CBOR,
225                 cbor.encodingPayloadToCbor(payload));
226         return request;
227     }
228
229     private IResponse makeResourcePublishResponse() {
230         HashMap<Object, Object> payload = new HashMap<>();
231         payload.put(Constants.DEVICE_ID, mDi);
232         ArrayList<HashMap<Object, Object>> publishLinks = new ArrayList<>();
233         HashMap<Object, Object> link = new HashMap<>();
234         link.put("href", "/oic/route/" + mDi + "/a/light");
235         ArrayList<String> rt = new ArrayList<String>();
236         rt.add("core.light");
237         ArrayList<String> itf = new ArrayList<String>();
238         itf.add("oic.if.baseline");
239         HashMap<String, Object> policy = new HashMap<>();
240         policy.put("bm", 5);
241         link.put("rt", rt);
242         link.put("if", itf);
243         link.put("p", policy);
244         publishLinks.add(link);
245         payload.put("links", publishLinks);
246
247         Cbor<HashMap<Object, Object>> cbor = new Cbor<>();
248         return MessageBuilder.createResponse(makeResourcePublishRequest(),
249                 ResponseStatus.CHANGED, ContentFormat.APPLICATION_CBOR,
250                 cbor.encodingPayloadToCbor(payload));
251     }
252
253     private IRequest makeResourceDeleteRequest() {
254         IRequest request = MessageBuilder.createRequest(RequestMethod.DELETE,
255                 TEST_RD_URI, "di" + "=" + mDi + ";" + "ins" + "=" + "1234",
256                 null, null);
257         return request;
258     }
259
260     private String getHrefInTestPublishPayload(byte[] payload) {
261
262         Cbor<HashMap<String, Object>> cbor = new Cbor<>();
263         HashMap<String, Object> parsedPayload = cbor
264                 .parsePayloadFromCbor(payload, HashMap.class);
265
266         @SuppressWarnings("unchecked")
267         ArrayList<HashMap<String, Object>> links = (ArrayList<HashMap<String, Object>>) parsedPayload
268                 .get(Constants.REQ_LINKS);
269
270         return (String) links.get(0).get(Constants.REQ_HREF);
271     }
272
273 }