Merge test folder of test branch
[iotivity.git] / test / src / iBtestapp / modules / ns / android / src / org / iotivity / test / ns / app / testapp / NSAppHelper.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
22 package org.iotivity.test.ns.app.testapp;
23
24 import java.util.Vector;
25
26 import org.iotivity.service.ns.provider.*;
27 import org.iotivity.base.OcException;
28 import org.iotivity.base.OcPlatform;
29 import org.iotivity.service.ns.common.*;
30 import org.iotivity.service.ns.common.SyncInfo.SyncType;
31 import org.iotivity.service.ns.common.Topic.TopicState;
32 import org.iotivity.service.ns.consumer.*;
33 import org.iotivity.service.ns.consumer.Provider.OnMessageReceivedListener;
34 import org.iotivity.service.ns.consumer.Provider.OnSyncInfoReceivedListener;
35 import org.iotivity.service.ns.consumer.Provider.ProviderState;
36
37 import static org.iotivity.test.ns.app.testapp.NSAppUtility.*;
38
39 import org.iotivity.service.testapp.framework.Base;
40
41 import android.util.Log;
42
43 public class NSAppHelper extends Base implements
44         ProviderService.OnConsumerSubscribedListener,
45         ProviderService.OnMessageSynchronizedListener,
46         ConsumerService.OnProviderDiscoveredListener,
47         OnSyncInfoReceivedListener, OnMessageReceivedListener,
48         Provider.OnProviderStateListener {
49
50     private static NSAppHelper instance           = null;
51     private Boolean            mIsProvider        = true;
52     private ProviderService    mProviderService   = null;
53     private ConsumerService    mConsumerService   = null;
54     private Boolean            mIsProviderStarted = false;
55     private Boolean            mIsConsumerStarted = false;
56     private Consumer           mConsumer          = null;
57     private Provider           mProvider          = null;
58     private SyncInfo           mProviderSyncInfo  = null;
59     private Message            mNotification      = null;
60     private static int         id                 = 0;
61
62     private NSAppHelper() {
63     }
64
65     public static NSAppHelper getInstance() {
66         if (instance == null) {
67             instance = new NSAppHelper();
68         }
69
70         return instance;
71     }
72
73     public void startProvider(Boolean subcontrollability) {
74         mIsProvider = subcontrollability;
75         try {
76             OcPlatform.stopPresence();
77             showLog(LogLevel.INFO, "stopPresence Calleded Successfully", false);
78         } catch (OcException e1) {
79             e1.printStackTrace();
80             showLog(LogLevel.INFO, "stopPresence generated exception", false);
81         }
82         mProviderService = ProviderService.getInstance();
83
84         try {
85             mProviderService.start(this, this, subcontrollability,
86                     USER_INFO, IS_SECURED);
87             showLog(LogLevel.INFO, "Provider Started Successfully", false);
88         } catch (NSException e) {
89             showLog(LogLevel.ERROR,
90                     "Failed to Start Provider. Exception is "
91                             + e.getLocalizedMessage(), false);
92             return;
93         }
94
95     }
96
97     public void stopProvider() {
98         if (!mIsProviderStarted) {
99             showLog(LogLevel.ERROR, "Provider Service is not started yet",
100                     false);
101             return;
102         }
103
104         try {
105             mProviderService.stop();
106             showLog(LogLevel.INFO, "Provider is stopped successfully", false);
107         } catch (NSException e) {
108             showLog(LogLevel.ERROR,
109                     "Fail to stop provider. Exception is "
110                             + e.getLocalizedMessage(), false);
111             return;
112         }
113     }
114
115     public void pendingSubscripton(Boolean isAccept) {
116         if (!mIsProviderStarted) {
117             showLog(LogLevel.ERROR, "Provider Service is not started yet",
118                     false);
119             return;
120         }
121
122         if (mConsumer != null) {
123             try {
124                 mConsumer.acceptSubscription(isAccept);
125                 showLog(LogLevel.INFO,
126                         "Accept/Reject sucessfully. ConsumerID: "
127                                 + mConsumer.getConsumerId(), false);
128             } catch (NSException e) {
129                 showLog(LogLevel.ERROR,
130                         "Failed to Accept/Reject Consumer",
131                         false);
132             }
133         } else {
134             showLog(LogLevel.ERROR, "No consumer found...", false);
135         }
136     }
137
138     public void sendMessage() {
139         if (!mIsProviderStarted) {
140             showLog(LogLevel.ERROR, "Provider Service is not started yet",
141                     false);
142             return;
143         }
144
145         Message message = null;
146
147         try {
148             message = mProviderService.createMessage();
149             message.setTitle(MSG_TITLE + id);
150             message.setContentText(MSG_BODY + id);
151             message.setSourceName(MSG_SOURCE);
152         } catch (NSException e1) {
153             showLog(LogLevel.ERROR,
154                     "Can't create message. Exception: "
155                             + e1.getLocalizedMessage(), false);
156             return;
157         }
158
159         message.setTTL(10);
160         // message.setTime(DateFormat.getDateTimeInstance().format(new Date()));
161         message.setTopic(TOPIC_NAME + id);
162         MediaContents mediaContents = new MediaContents("Image");
163         message.setMediaContents(mediaContents);
164
165         try {
166             mProviderService.sendMessage(message);
167             showLog(LogLevel.INFO, "Notification Sent Successfully..", false);
168         } catch (NSException e) {
169             showLog(LogLevel.ERROR,
170                     "Can't sent notification. Exception is "
171                             + e.getLocalizedMessage(), false);
172             return;
173         }
174     }
175
176     public void registerTopic() {
177         if (!mIsProviderStarted) {
178             showLog(LogLevel.ERROR, "Provider Service is not started yet",
179                     false);
180             return;
181         }
182
183         ++id;
184
185         try {
186             mProviderService.registerTopic(TOPIC_NAME + id);
187             showLog(LogLevel.INFO, "Topic registered Successfully...", false);
188         } catch (NSException e) {
189             showLog(LogLevel.ERROR, "Topic register failed...",
190                     false);
191             return;
192         }
193     }
194
195     public void unRegisterTopic() {
196         if (!mIsProviderStarted) {
197             showLog(LogLevel.ERROR, "Provider Service is not started yet",
198                     false);
199             return;
200         }
201
202         try {
203             mProviderService.unregisterTopic(TOPIC_NAME + id);
204             showLog(LogLevel.INFO, "Topic unregistered Successfully...", false);
205         } catch (NSException e) {
206             showLog(LogLevel.ERROR, "Topic unregister failed...", false);
207             return;
208         }
209
210         --id;
211     }
212
213     public void setTopic() {
214         if (!mIsProviderStarted) {
215             showLog(LogLevel.ERROR, "Provider Service is not started yet",
216                     false);
217             return;
218         }
219
220         if (!mIsProvider) {
221             showLog(LogLevel.WARNING, "Operation is not permitted", false);
222             return;
223         }
224
225         for (int i = 1; i <= id; i += 2) {
226             try {
227                 mConsumer.setTopic(TOPIC_NAME + i);
228                 showLog(LogLevel.INFO, "Set the topic " + TOPIC_NAME + i
229                         + " Successfully...", false);
230             } catch (NSException e) {
231                 showLog(LogLevel.ERROR,
232                         "Failed to set topic: = "
233                                 + TOPIC_NAME + i + ". Exception is "
234                                 + e.getLocalizedMessage(), false);
235                 return;
236             }
237         }
238     }
239
240     public void unSetTopic() {
241         if (!mIsProviderStarted) {
242             showLog(LogLevel.ERROR, "Provider Service is not started yet",
243                     false);
244             return;
245         }
246
247         if (!mIsProvider) {
248             showLog(LogLevel.WARNING, "Operation is not permitted", false);
249             return;
250         }
251
252         for (int i = 1; i <= id; i += 2) {
253             try {
254                 mConsumer.unsetTopic(TOPIC_NAME + i);
255                 showLog(LogLevel.INFO, "UnSet the topic " + TOPIC_NAME + i
256                         + " Successfully...", false);
257             } catch (NSException e) {
258                 showLog(LogLevel.ERROR,
259                         "Failed to unset topic: = "
260                                 + TOPIC_NAME + i + ". Exception is "
261                                 + e.getLocalizedMessage(), false);
262                 return;
263             }
264         }
265     }
266
267     public void getProviderTopics() {
268         if (!mIsProviderStarted) {
269             showLog(LogLevel.ERROR, "Provider Service is not started yet",
270                     false);
271             return;
272         }
273
274         try {
275             printTopicList(mProviderService.getRegisteredTopicList());
276         } catch (NSException e) {
277             showLog(LogLevel.ERROR,
278                     "Exception occurs when calling getRegisteredTopicList(). Exception: "
279                             + e.getLocalizedMessage(), false);
280             return;
281         }
282     }
283
284     public void getConsumerTopics() {
285         if (!mIsProviderStarted) {
286             showLog(LogLevel.ERROR, "Provider Service is not started yet",
287                     false);
288             return;
289         }
290
291         try {
292             printTopicList(mConsumer.getConsumerTopicList());
293         } catch (NSException e) {
294             showLog(LogLevel.ERROR,
295                     "Exception occurs when calling getConsumerTopicList(). Exception: "
296                             + e.getLocalizedMessage(), false);
297             return;
298         }
299     }
300
301     public void sendProviderSyncInfo() {
302         if (!mIsProviderStarted) {
303             showLog(LogLevel.ERROR, "Provider Service is not started yet",
304                     false);
305             return;
306         }
307
308         if (mProviderSyncInfo == null) {
309             showLog(LogLevel.ERROR, "Didn't get any sync from consumer", false);
310             return;
311         }
312
313         try {
314             mProviderService.sendSyncInfo(mProviderSyncInfo.getMessageId(),
315                     SyncType.READ);
316         } catch (NSException e) {
317             showLog(LogLevel.ERROR,
318                     "Exception occurs when calling sendSyncInfo(). Exception: "
319                             + e.getLocalizedMessage(), false);
320         }
321     }
322
323     // Consumer Service Methods
324     public void startConsumer() {
325         mProvider = null;
326         try {
327             OcPlatform.stopPresence();
328             showLog(LogLevel.INFO, "stopPresence Calleded Successfully", false);
329         } catch (OcException e1) {
330             e1.printStackTrace();
331             showLog(LogLevel.INFO, "stopPresence generated exception", false);
332         }
333         mConsumerService = ConsumerService.getInstance();
334
335         try {
336             mConsumerService.start(this);
337         } catch (NSException e) {
338             showLog(LogLevel.ERROR,
339                     "Can't start consumer service. Occurs exception: "
340                             + e.getLocalizedMessage(), false);
341             return;
342         }
343
344         mIsConsumerStarted = true;
345
346         showLog(LogLevel.INFO, "Consumer Service Started Successfully", false);
347     }
348
349     public void stopConsumer() {
350         if (!mIsConsumerStarted) {
351             showLog(LogLevel.ERROR, "Consumer Service is not started yet",
352                     false);
353             return;
354         }
355
356         try {
357             mConsumerService.stop();
358         } catch (NSException e) {
359             showLog(LogLevel.ERROR,
360                     "Can't stop consumer service. Occurs exception: "
361                             + e.getLocalizedMessage(), false);
362         }
363
364         mIsConsumerStarted = false;
365         showLog(LogLevel.INFO, "Consumer Service Stopped Successfully", false);
366
367         mProvider = null;
368         mConsumerService = null;
369     }
370
371     public void manualScan() {
372         if (!mIsConsumerStarted) {
373             showLog(LogLevel.ERROR, "Consumer Service is not started yet",
374                     false);
375             return;
376         }
377
378         try {
379             mConsumerService.rescanProvider();
380         } catch (NSException e) {
381             showLog(LogLevel.ERROR,
382                     "Can't rescan because of " + e.getLocalizedMessage(), false);
383         }
384     }
385
386     public void subscribeConsumer() {
387         if (!mIsConsumerStarted) {
388             showLog(LogLevel.ERROR, "Consumer Service is not started yet",
389                     false);
390             return;
391         }
392
393         if (mProvider == null) {
394             showLog(LogLevel.ERROR, "Can't find any provider...", false);
395             return;
396         }
397
398         try {
399             mProvider.subscribe();
400         } catch (NSException e) {
401             showLog(LogLevel.ERROR,
402                     "Can't subscribe because of " + e.getLocalizedMessage(),
403                     false);
404         }
405
406         showLog(LogLevel.INFO,
407                 "Subscribe sucessfully to the provider with ID: "
408                         + mProvider.getProviderId(), false);
409     }
410
411     public void sendConsumerSyncInfo() {
412         if (!mIsConsumerStarted) {
413             showLog(LogLevel.ERROR, "Consumer Service is not started yet",
414                     false);
415             return;
416         }
417
418         if (mProvider == null) {
419             showLog(LogLevel.ERROR, "Can't find any provider...", false);
420             return;
421         }
422
423         if (mNotification == null) {
424             showLog(LogLevel.ERROR, "Can't find any notification...", false);
425             return;
426         }
427
428         try {
429             mProvider.sendSyncInfo(mNotification.getMessageId(), SyncType.READ);
430         } catch (NSException e) {
431             showLog(LogLevel.ERROR,
432                     "Can't send syncinfo because of " + e.getLocalizedMessage(),
433                     false);
434         }
435
436         showLog(LogLevel.INFO,
437                 "Send syncinfo successfully to "
438                         + mNotification.getProviderId(), false);
439     }
440
441     public void getTopics() {
442         TopicsList topicList = getTopicList();
443
444         if (topicList != null) {
445             printTopicList(topicList);
446         }
447     }
448
449     private TopicsList getTopicList() {
450         if (!mIsConsumerStarted) {
451             showLog(LogLevel.ERROR, "Consumer Service is not started yet",
452                     false);
453             return null;
454         }
455
456         if (mProvider == null) {
457             showLog(LogLevel.ERROR, "Can't find any provider...", false);
458             return null;
459         }
460
461         try {
462             return mProvider.getTopicList();
463         } catch (NSException e) {
464             showLog(LogLevel.ERROR,
465                     "Can't get topicList because of " + e.getLocalizedMessage(),
466                     false);
467             return null;
468         }
469     }
470
471     public void updateTopics() {
472         if (mIsProvider) {
473             showLog(LogLevel.WARNING, "Operation is not permitted", false);
474             return;
475         }
476
477         TopicsList topics = getTopicList();
478
479         if (topics == null) {
480             showLog(LogLevel.ERROR, "Can't find any topics", false);
481             return;
482         }
483
484         try {
485             mProvider.updateTopicList(topics);
486         } catch (NSException e) {
487             showLog(LogLevel.ERROR,
488                     "Can't update because of " + e.getLocalizedMessage(), false);
489         }
490     }
491
492     public void showLog(LogLevel level, String log, Boolean isLogClear) {
493         switch (level) {
494             case INFO:
495                 Log.i(TAG, log);
496                 break;
497
498             case DEBUG:
499                 Log.d(TAG, log);
500                 break;
501
502             case WARNING:
503                 Log.w(TAG, log);
504                 break;
505
506             case ERROR:
507                 Log.e(TAG, log);
508                 break;
509
510             default:
511                 Log.v(TAG, log);
512                 break;
513         }
514
515         // if (isLogClear) {
516         // clearOutPut();
517         // }
518         //
519          showOutPut(log);
520     }
521
522     enum LogLevel {
523         INFO, DEBUG, WARNING, VERBOSE, ERROR
524     }
525
526     // Provider Callback
527     @Override
528     public void onMessageSynchronized(SyncInfo syncInfo) {
529         showLog("syncInfoCallback Called", false);
530         showLog(LogLevel.INFO,
531                 "onMessageSynchronized Listener Called for Message ID: "
532                         + syncInfo.getMessageId(), false);
533
534         mProviderSyncInfo = syncInfo;
535     }
536
537     @Override
538     public void onConsumerSubscribed(Consumer consumer) {
539         showLog("subRequestCallback Called", false);
540         showLog(LogLevel.INFO,
541                 "onConsumerSubscribed Listener Called with ConsumerID: "
542                         + consumer.getConsumerId(), false);
543
544         mConsumer = consumer;
545     }
546
547     // Consumer Callback
548     @Override
549     public void onSyncInfoReceived(SyncInfo sync) {
550         showLog("NSSyncInfoReceivedCallback called", false);
551         showLog(LogLevel.INFO,
552                 "onSyncInfoReceived Listener Called from Provider "
553                         + sync.getMessageId() + " Message ID: "
554                         + sync.getMessageId(), false);
555     }
556
557     @Override
558     public void onProviderStateReceived(ProviderState state) {
559         showLog("NSProviderStateCallback called", false);
560         showLog(LogLevel.INFO, "onProviderStateReceived Listener Called with "
561                 + getProviderState(state) + " ...", false);
562     }
563
564     @Override
565     public void onMessageReceived(Message message) {
566         showLog("NSMessageReceivedCallback called", false);
567         showLog(LogLevel.INFO, "onMessageReceived Listener Called...", false);
568
569         mNotification = message;
570
571         printMessage(message);
572     }
573
574     @Override
575     public void onProviderDiscovered(Provider provider) {
576         showLog("Notification Resource Discovered", false);
577         showLog(LogLevel.INFO,
578                 "onProviderDiscovered Listener Called with ProviderID: "
579                         + provider.getProviderId(), false);
580
581         mProvider = provider;
582
583         try {
584             mProvider.setListener(this, this, this);
585         } catch (NSException e) {
586             showLog(LogLevel.ERROR, "Can't set listener", false);
587         }
588     }
589
590     void printMessage(Message message) {
591         String log = "MessageID: " + message.getMessageId();
592         log += " Title = " + message.getTitle();
593         log += " Body = " + message.getContentText();
594         log += " Topic Name: " + message.getTopic();
595         log += " ProviderID = " + message.getProviderId();
596
597         showLog(LogLevel.INFO, log, false);
598     }
599
600     String getProviderState(ProviderState state) {
601         switch (state) {
602             case ALLOW:
603                 showLog("Provider changed to NS_ALLOW State. ", false);
604                 return "ALLOW";
605
606             case DENY:
607                 showLog("Provider changed to NS_DENY State. ", false);
608                 return "DENY";
609
610             case TOPIC:
611                 showLog("Provider changed to NS_TOPIC State. ", false);
612                 return "TOPIC";
613
614             case STOPPED:
615                 showLog("Provider changed to NS_STOPPED State. ", false);
616                 return "STOPPED";
617
618             default:
619                 return "UNKNOWN";
620         }
621     }
622
623     void printTopicList(TopicsList topics) {
624         Vector<Topic> topicList = topics.getTopicsList();
625
626         String log = "Registered topics: ";
627
628         for (Topic topic : topicList) {
629             log += "Topic: " + topic;
630
631             if (topic.getState() == TopicState.SUBSCRIBED) {
632                 log += " State: SUBSCRIBED";
633             } else {
634                 log += " State: UNSUBSCRIBED";
635             }
636         }
637
638         showLog(LogLevel.INFO, log, false);
639     }
640 }