Merge test folder of test branch
[iotivity.git] / test / src / tc / ns / junit / src / org / iotivity / test / ns / tc / helper / NSHelper.java
1 //******************************************************************
2 //
3 // Copyright 2017 Samsung Electronics All Rights Reserved.
4 //
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
6 //
7 // Licensed under the Apache License, Version 2.0 (the "License");
8 // you may not use this file except in compliance with the License.
9 // You may obtain a copy of the License at
10 //
11 //      http://www.apache.org/licenses/LICENSE-2.0
12 //
13 // Unless required by applicable law or agreed to in writing, software
14 // distributed under the License is distributed on an "AS IS" BASIS,
15 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 // See the License for the specific language governing permissions and
17 // limitations under the License.
18 //
19 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
20
21 package org.iotivity.test.ns.tc.helper;
22
23 import org.iotivity.base.ModeType;
24 import org.iotivity.base.OcPlatform;
25 import org.iotivity.base.PlatformConfig;
26 import org.iotivity.base.QualityOfService;
27 import org.iotivity.base.ServiceType;
28 import org.iotivity.service.ns.provider.*;
29 import org.iotivity.service.ns.common.*;
30 import org.iotivity.service.ns.common.SyncInfo.SyncType;
31 import org.iotivity.service.ns.consumer.*;
32 import org.iotivity.service.ns.consumer.Provider.ProviderState;
33
34 import static org.iotivity.test.ns.tc.helper.NSTestUtilily.*;
35 import android.content.Context;
36 import android.util.Log;
37
38 public class NSHelper implements ProviderService.OnConsumerSubscribedListener,
39         ProviderService.OnMessageSynchronizedListener,
40         ConsumerService.OnProviderDiscoveredListener,
41         Provider.OnMessageReceivedListener, Provider.OnProviderStateListener,
42         Provider.OnSyncInfoReceivedListener {
43     private static NSHelper sNSHelperInstance   = null;
44     private Context         mContext           = null;
45     private Consumer        mConsumer          = null;
46     private Provider        mProvider          = null;
47     private ProviderService mProviderService   = null;
48     private ConsumerService mConsumerService   = null;
49     private Message         mMessage           = null;
50     private ProviderState   mProviderState     = null;
51     private SyncInfo        mProviderSyncInfo  = null;
52     private SyncInfo        mConsumerSyncInfo  = null;
53     private boolean         mIsProviderStarted = false;
54     private boolean         mIsConsumerStarted = false;
55
56     private NSHelper(Context context) {
57         mContext = context;
58         configPlatform();
59     }
60
61     public static synchronized NSHelper getInstance(Context context) {
62         if (sNSHelperInstance == null) {
63             sNSHelperInstance = new NSHelper(context);
64         }
65
66         return sNSHelperInstance;
67     }
68
69     private void configPlatform() {
70         PlatformConfig platformConfig = new PlatformConfig(mContext,
71                 ServiceType.IN_PROC, ModeType.CLIENT_SERVER, "0.0.0.0", 0,
72                 QualityOfService.LOW);
73
74         Log.i(TAG, "Configuring platform.");
75
76         OcPlatform.Configure(platformConfig);
77         try {
78             OcPlatform.stopPresence();
79         } catch (Exception e) {
80             Log.e(TAG, "Exception: stopping presence when configuration step: "
81                     + e);
82         }
83         Log.i(TAG, "Configuration done Successfully");
84     }
85
86     public ProviderService getProviderService() {
87         if (mProviderService == null) {
88             mProviderService = ProviderService.getInstance();
89         }
90         return mProviderService;
91     }
92
93     public ConsumerService getConsumerService() {
94         if (mConsumerService == null) {
95             mConsumerService = ConsumerService.getInstance();
96         }
97         return mConsumerService;
98     }
99
100     public void setProviderStartStatus(boolean isStarted) {
101         mIsProviderStarted = isStarted;
102     }
103
104     public void setConsumerStartStatus(boolean isStarted) {
105         mIsConsumerStarted = isStarted;
106     }
107
108     public void stopServices() {
109
110         if (mIsConsumerStarted && (mConsumerService != null)) {
111             try {
112                 mConsumerService.stop();
113                 mIsConsumerStarted = false;
114                 Log.i(TAG, "Consumer Service Stopped Successfully");
115             } catch (NSException e) {
116                 Log.e(TAG, e.getMessage());
117             }
118
119             waitInSecond(WAIT_MIN_TIME + WAIT_MIN_TIME);
120         }
121         mConsumerService = null;
122
123         if (mIsProviderStarted && (mProviderService != null)) {
124             try {
125                 mProviderService.stop();
126                 mIsProviderStarted = false;
127                 Log.i(TAG, "Provider Service Stopped Successfully");
128
129             } catch (NSException e) {
130                 Log.e(TAG, "Failed to stop Provider Service");
131                 Log.e(TAG, e.getMessage());
132             }
133
134             waitInSecond(WAIT_MIN_TIME);
135         }
136         mProviderService = null;
137     }
138
139     public boolean stopProviderService() {
140         if (mProviderService == null) {
141             return false;
142         }
143
144         try {
145             mProviderService.stop();
146         } catch (NSException e) {
147             Log.e(TAG, "Can't stop provider service");
148             e.printStackTrace();
149             return false;
150         }
151
152         mIsProviderStarted = false;
153         mProviderService = null;
154         return true;
155     }
156
157     public Consumer getConsumer(boolean subControllability,
158             boolean isTopicRegister) {
159         mProvider = null;
160         mConsumer = null;
161
162         stopServices();
163         mProviderService = getProviderService();
164         mConsumerService = getConsumerService();
165
166         try {
167             mProviderService.start(this, this, subControllability, USER_INFO,
168                     IS_SECURED);
169             mIsProviderStarted = true;
170             Log.d(TAG, "provider service started");
171
172             if (isTopicRegister)
173                 mProviderService.registerTopic(TOPIC_NAME);
174             Log.d(TAG, "topic registered");
175
176             waitInSecond(WAIT_MIN_TIME);
177
178             mConsumerService.start(this);
179             mIsConsumerStarted = true;
180             Log.d(TAG, "consumer service started");
181
182             waitInSecond(WAIT_MIN_TIME);
183
184             mConsumerService.rescanProvider();
185             waitInSecond(WAIT_MIN_TIME * 3);
186         } catch (NSException e) {
187             Log.e(TAG, "Can't Start Consumer Service");
188             return null;
189         }
190
191         if (subControllability) {
192             boolean isFound = waitForService(WAIT_MAX_TIME, false);
193             Log.d(TAG, "waiting for provider with provider control");
194
195             if (!isFound) {
196                 Log.w(TAG, "Can't find provider");
197             }
198         } else {
199             boolean isFound = waitForService(WAIT_MAX_TIME, true);
200             Log.d(TAG, "waiting for provider with consumer control");
201             if (isFound) {
202                 try {
203                     mProvider.subscribe();
204                 } catch (NSException e) {
205                     Log.e(TAG, "Can't Subscribe to provider");
206                 }
207             } else {
208                 Log.e(TAG, "Can't find provider");
209             }
210
211             isFound = waitForService(WAIT_MAX_TIME, false);
212
213             if (isFound) {
214                 Log.i(TAG, "Consumer Found Successfully");
215             } else {
216                 Log.w(TAG, "Can't find any Consumer");
217             }
218         }
219
220         return mConsumer;
221     }
222
223     public Provider getProvider(boolean subControllability) {
224         mProvider = null;
225         mConsumer = null;
226
227         mProviderService = ProviderService.getInstance();
228         mConsumerService = ConsumerService.getInstance();
229
230         try {
231             mProviderService.start(this, this, subControllability, USER_INFO,
232                     IS_SECURED);
233             mProviderService.registerTopic(TOPIC_NAME);
234             mIsProviderStarted = true;
235             waitInSecond(WAIT_MIN_TIME);
236
237             mConsumerService.start(this);
238             mIsConsumerStarted = true;
239             mConsumerService.rescanProvider();
240         } catch (NSException e) {
241             Log.e(TAG, "Can't Start. Exception is " + e.getLocalizedMessage());
242         }
243
244         waitForService(WAIT_MAX_TIME, true);
245
246         return mProvider;
247     }
248
249     public boolean sendNotification() {
250         if (mProviderService == null || mConsumer == null) {
251             Log.e(TAG, "ProviderService or Consumer is null");
252             return false;
253         }
254
255         try {
256             mProviderService.registerTopic(TOPIC_NAME);
257             mConsumer.setTopic(TOPIC_NAME);
258         } catch (NSException e) {
259             e.printStackTrace();
260             return false;
261         }
262
263         Message msg = null;
264
265         try {
266             msg = mProviderService.createMessage();
267             msg.setTitle(MSG_TITLE);
268             msg.setContentText(MSG_BODY);
269             msg.setSourceName(MSG_SOURCE);
270             msg.setTopic(TOPIC_NAME);
271
272             MediaContents mediaContents = new MediaContents("Image");
273
274             msg.setMediaContents(mediaContents);
275         } catch (NSException e) {
276             e.printStackTrace();
277             return false;
278         }
279
280         try {
281             mMessage = null;
282             mProviderService.sendMessage(msg);
283         } catch (NSException e) {
284             Log.e(TAG, "SendMessage is failed.");
285             e.printStackTrace();
286             return false;
287         }
288
289         Log.i(TAG, "Notification Sent");
290
291         return true;
292     }
293
294     public Message getNotification() {
295         return mMessage;
296     }
297
298     private boolean waitForService(int timeOut, boolean isProvider) {
299         int progessTime = 0;
300
301         while (true) {
302             if (isProvider)
303                 Log.d(TAG, "Waiting for Provider " + progessTime + "...");
304             else
305                 Log.d(TAG, "Waiting for Consumer " + progessTime + "...");
306
307             if (isProvider) {
308                 if (mProvider != null) {
309                     Log.i(TAG, "Provider found with ID: "
310                             + mProvider.getProviderId());
311                     return true;
312                 }
313             } else {
314                 if (mConsumer != null) {
315                     Log.i(TAG, "Consumer found with ID: "
316                             + mConsumer.getConsumerId());
317                     return true;
318                 }
319             }
320
321             waitInSecond(WAIT_MIN_TIME);
322
323             if (++progessTime > timeOut) {
324                 break;
325             }
326         }
327
328         return false;
329     }
330
331     public void waitInSecond(int time) {
332         int timeInSec = time * 1000;
333         try {
334             Thread.sleep(timeInSec);
335         } catch (InterruptedException ex) {
336             Thread.currentThread().interrupt();
337         }
338     }
339
340     public boolean sendSyncInfo(boolean isProvider, SyncType type) {
341         if (mMessage == null) {
342             Log.e(TAG, "Notification is null");
343             return false;
344         }
345
346         if (isProvider) {
347             if (mProviderService == null) {
348                 Log.e(TAG, "Provider service is null");
349                 return false;
350             }
351         } else {
352             if (mProvider == null) {
353                 Log.e(TAG, "Provider is null");
354                 return false;
355             }
356         }
357
358         try {
359             if (isProvider)
360                 mProviderService.sendSyncInfo(mMessage.getMessageId(), type);
361             else
362                 mProvider.sendSyncInfo(mMessage.getMessageId(), type);
363         } catch (NSException e) {
364             e.printStackTrace();
365             return false;
366         }
367
368         return true;
369     }
370
371     public SyncInfo getSyncInfo(boolean isProvider) {
372         if (isProvider)
373             return mProviderSyncInfo;
374         else
375             return mConsumerSyncInfo;
376     }
377
378     public ProviderState getProviderState() {
379         return mProviderState;
380     }
381
382     // Provider Callback
383     @Override
384     public void onMessageSynchronized(SyncInfo syncInfo) {
385         Log.i(TAG, "onMessageSynchronized Listener Called...");
386
387         mConsumerSyncInfo = syncInfo;
388
389         printSyncInfo(syncInfo);
390     }
391
392     @Override
393     public void onConsumerSubscribed(Consumer consumer) {
394         Log.i(TAG, "onConsumerSubscribed Listener Called with ConsumerID: "
395                 + consumer.getConsumerId() + "...");
396         mConsumer = consumer;
397     }
398
399     // Consumer Callback
400     @Override
401     public void onSyncInfoReceived(SyncInfo sync) {
402         Log.i(TAG, "onSyncInfoReceived Listener Called ...");
403
404         mProviderSyncInfo = sync;
405
406         printSyncInfo(sync);
407     }
408
409     @Override
410     public void onProviderStateReceived(ProviderState state) {
411         Log.i(TAG, "onProviderStateReceived Listener Called...");
412
413         mProviderState = state;
414     }
415
416     @Override
417     public void onMessageReceived(Message message) {
418         Log.i(TAG, "onMessageReceived Listener Called...");
419
420         mMessage = message;
421
422         printMessage(mMessage);
423     }
424
425     @Override
426     public void onProviderDiscovered(Provider provider) {
427         Log.i(TAG, "onProviderDiscovered Listener Called with ProviderID: "
428                 + provider.getProviderId() + "...");
429
430         mProvider = provider;
431
432         try {
433             mProvider.setListener(this, this, this);
434         } catch (NSException e) {
435             Log.e(TAG, "Can't set listener");
436         }
437     }
438
439     void printMessage(Message message) {
440         String log = "MessageID: " + message.getMessageId();
441         log += " Title = " + message.getTitle();
442         log += " Body = " + message.getContentText();
443         log += " Topic = " + message.getTopic();
444         log += " ProviderID = " + message.getProviderId();
445
446         Log.i(TAG, log);
447     }
448
449     void printSyncInfo(SyncInfo info) {
450         try {
451             Log.i(TAG,
452                     "SyncInfo --> ProviderID: " + info.getProviderId()
453                             + " MessageID: " + info.getMessageId() + " State: "
454                             + getSyncType(info.getState()));
455         } catch (Exception e) {
456             Log.w(TAG, "Can't print syncInfo. Exception: "
457                     + e.getLocalizedMessage());
458         }
459     }
460
461     String getSyncType(SyncType type) {
462         switch (type) {
463             case UNREAD:
464                 return "UNREAD";
465
466             case READ:
467                 return "READ";
468
469             case DELETED:
470                 return "DELETED";
471
472             default:
473                 return "UNKNOWN";
474         }
475     }
476 }