replace : iotivity -> iotivity-sec
[platform/upstream/iotivity.git] / service / notification / examples / android / NotiConsumerExample / app / src / main / java / org / iotivity / service / ns / sample / consumer / MainActivity.java
1 /******************************************************************
2  * Copyright 2016 Samsung Electronics All Rights Reserved.
3  * <p>
4  * <p>
5  * <p>
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  * <p>
10  * http://www.apache.org/licenses/LICENSE-2.0
11  * <p>
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  ******************************************************************/
18
19 package org.iotivity.service.ns.sample.consumer;
20
21 import android.app.Dialog;
22 import android.content.Context;
23 import android.content.Intent;
24 import android.os.Bundle;
25 import android.os.Handler;
26 import android.os.Message;
27 import android.app.Activity;
28 import android.util.Log;
29 import android.view.View;
30 import android.widget.Button;
31 import android.widget.EditText;
32 import android.widget.TextView;
33 import android.widget.Toast;
34
35 import org.iotivity.base.ErrorCode;
36 import org.iotivity.base.OcAccountManager;
37 import org.iotivity.base.OcConnectivityType;
38 import org.iotivity.base.OcException;
39 import org.iotivity.base.OcHeaderOption;
40 import org.iotivity.base.OcPlatform;
41 import org.iotivity.base.OcRepresentation;
42 import org.iotivity.base.OcResource;
43 import org.iotivity.service.ns.common.TopicsList;
44 import org.iotivity.service.ns.common.Topic;
45
46 import java.util.Arrays;
47 import java.util.EnumSet;
48 import java.util.HashMap;
49 import java.util.List;
50 import java.util.Map;
51
52 public class MainActivity extends Activity
53         implements OcAccountManager.OnPostListener {
54     private final String        TAG                 = "NS_MAIN_ACTIVITY";
55     private final int           REQUEST_LOGIN       = 1;
56     private static final String CI_SERVER_PREFIX    = "coap+tcp://";
57     private final Context       context             = this;
58
59     public static String        deviceID            = null;
60     public static String        CIServer            = null;
61     public static String        RemoteAddress       = null;
62     public static String        MQCloudAddress      = null;
63     public static String        MQCloudTopic        = null;
64
65     private Button              btnStart;
66     private Button              btnStop;
67     private Button              btnRescan;
68     private Button              btnSubscribe;
69     private Button              btnUnsubscribe;
70     private Button              btnEnableRemoteService;
71     private Button              btnGetTopicList;
72     private Button              btnUpdateTopicList;
73     private Button              btnClearLog;
74     private static TextView     TvLog;
75     private Button              signUp, signIn, signOut;
76     private Button              subscribeMQ;
77
78     private boolean             isStarted           = false;
79
80     private ConsumerSample      mConsumerSample     = null;
81     private OcAccountManager    mAccountManager;
82     String                      mAuthCode;
83     String                      mAuthProvider;
84     String                      mRefreshtoken;
85     String                      mUserID;
86     String                      mAccessToken;
87
88     private static final int    PROVIDER_DISCOVERED = 1;
89     private static final int    STATE_CHANGED       = 2;
90     private static final int    MESSAGE_RECEIVED    = 3;
91     private static final int    SYNCINFO_RECEIVED   = 4;
92     private static final int    TOPICS_RECEIVED     = 5;
93
94     public static Handler       mHandler            = new Handler() {
95         @Override
96         public void handleMessage(Message msg) {
97             switch (msg.what) {
98                 case PROVIDER_DISCOVERED: {
99                     String providerId = (String) msg.obj;
100                     if (providerId != null) {
101                         TvLog.append(providerId + "\n");
102                     }
103                     break;
104                 }
105                 case STATE_CHANGED: {
106                     String state = (String) msg.obj;
107                     if (state != null) {
108                         TvLog.append(state + "\n");
109                     }
110                     break;
111                 }
112                 case MESSAGE_RECEIVED: {
113                     String message = (String) msg.obj;
114                     if (message != null) {
115                         TvLog.append(message + "\n");
116                     }
117                     break;
118                 }
119                 case SYNCINFO_RECEIVED: {
120                     String sync = (String) msg.obj;
121                     if (sync != null) {
122                         TvLog.append(sync + "\n");
123                     }
124                     break;
125                 }
126                 case TOPICS_RECEIVED: {
127                     String topicList = (String) msg.obj;
128                     if (topicList != null) {
129                         TvLog.append(topicList + "\n");
130                     }
131                     break;
132                 }
133                 default:
134                     break;
135             }
136         }
137     };
138
139     public void showToast(final String toast) {
140         runOnUiThread(new Runnable() {
141             @Override
142             public void run() {
143                 Toast.makeText(getApplicationContext(), toast,
144                         Toast.LENGTH_SHORT).show();
145             }
146         });
147     }
148
149     @Override
150     protected void onCreate(Bundle savedInstanceState) {
151         super.onCreate(savedInstanceState);
152         setContentView(R.layout.activity_main);
153
154         btnStart = (Button) findViewById(R.id.BtnStart);
155         btnStop = (Button) findViewById(R.id.BtnStop);
156         btnRescan = (Button) findViewById(R.id.BtnRescan);
157         btnSubscribe = (Button) findViewById(R.id.BtnSubscribe);
158         btnUnsubscribe = (Button) findViewById(R.id.BtnUnsubscribe);
159         btnEnableRemoteService = (Button) findViewById(
160                 R.id.BtnEnableRemoteService);
161         btnGetTopicList = (Button) findViewById(R.id.BtnGetTopicList);
162         btnUpdateTopicList = (Button) findViewById(R.id.BtnUpdateTopicList);
163         btnClearLog = (Button) findViewById(R.id.BtnClearLog);
164
165         signUp = (Button) findViewById(R.id.signup);
166         signIn = (Button) findViewById(R.id.signin);
167         signOut = (Button) findViewById(R.id.signout);
168         subscribeMQ = (Button) findViewById(R.id.subscribeMQService);
169         TvLog = (TextView) findViewById(R.id.TvLog);
170
171         btnStart.setOnClickListener(mClickListener);
172         btnStop.setOnClickListener(mClickListener);
173         btnRescan.setOnClickListener(mClickListener);
174         btnEnableRemoteService.setOnClickListener(mClickListener);
175         btnGetTopicList.setOnClickListener(mClickListener);
176         btnUpdateTopicList.setOnClickListener(mClickListener);
177         btnClearLog.setOnClickListener(mClickListener);
178
179         signIn.setEnabled(false);
180         signOut.setEnabled(false);
181         btnEnableRemoteService.setEnabled(false);
182
183         btnSubscribe.setOnClickListener(mClickListener);
184         btnUnsubscribe.setOnClickListener(mClickListener);
185         signUp.setOnClickListener(mClickListener);
186         signIn.setOnClickListener(mClickListener);
187         signOut.setOnClickListener(mClickListener);
188         subscribeMQ.setOnClickListener(mClickListener);
189
190         mConsumerSample = new ConsumerSample(getApplicationContext());
191         mConsumerSample.setHandler(mHandler);
192     }
193
194     @Override
195     protected void onDestroy() {
196         if (isStarted)
197             mConsumerSample.stopNotificationConsumer();
198         super.onDestroy();
199     }
200
201     Button.OnClickListener mClickListener = new View.OnClickListener() {
202         public void onClick(View v) {
203             switch (v.getId()) {
204                 case R.id.BtnStart: {
205                     if (!isStarted) {
206                         Log.i(TAG, "Start NS Consumer Service");
207
208                         TvLog.setText("Start NS-Consumer\n");
209                         mConsumerSample.startNotificationConsumer();
210                         isStarted = true;
211                     } else {
212                         Log.e(TAG, "NS Consumer Service has already started");
213                         showToast("Error : Service has already started");
214                     }
215                 }
216                     break;
217
218                 case R.id.BtnStop: {
219                     if (!isStarted) {
220                         Log.e(TAG,
221                                 "Fail to stop service. Service has not been started");
222                         showToast("Error : Service has not been started");
223                         break;
224                     }
225                     TvLog.append("Stop NS-Consumer\n");
226                     mConsumerSample.stopNotificationConsumer();
227                     isStarted = false;
228                 }
229                     break;
230                 case R.id.BtnRescan: {
231                     if (!isStarted) {
232                         Log.e(TAG,
233                                 "Fail to rescan. Service has not been started");
234                         showToast("Error : Service has not been started");
235                         break;
236                     }
237                     TvLog.append("Rescan NS-Consumer\n");
238                     mConsumerSample.rescanProvider();
239                 }
240                     break;
241                 case R.id.BtnSubscribe: {
242                     if (!isStarted) {
243                         Log.e(TAG,
244                                 "Fail to Subscribe. Service has not been started");
245                         showToast("Error : Service has not been started");
246                         break;
247                     }
248                     TvLog.append("Subscribe NS-Consumer\n");
249                     mConsumerSample.subscribe();
250                 }
251                 break;
252                 case R.id.BtnUnsubscribe: {
253                     if (!isStarted) {
254                         Log.e(TAG,
255                                 "Fail to Unsubscribe. Service has not been started");
256                         showToast("Error : Service has not been started");
257                         break;
258                     }
259                     TvLog.append("Unsubscribe NS-Consumer\n");
260                     mConsumerSample.unsubscribe();
261                 }
262                 break;
263                 case R.id.BtnEnableRemoteService: {
264                     if (!isStarted) {
265                         Log.e(TAG,
266                                 "Fail to Enable RemoteService. Service has not been started");
267                         showToast("Error : Service has not been started");
268                         break;
269                     }
270                     TvLog.append("EnableRemoteService NS-Consumer\n");
271                     mConsumerSample.enableRemoteService(RemoteAddress);
272                 }
273                     break;
274                 case R.id.BtnGetTopicList: {
275                     if (!isStarted) {
276                         Log.e(TAG,
277                                 "Fail to GetTopicList. Service has not been started");
278                         showToast("Error : Service has not been started");
279                         break;
280                     }
281                     TvLog.append("GetTopicList NS-Consumer\n");
282                     mConsumerSample.getTopicsList();
283                 }
284                     break;
285                 case R.id.BtnUpdateTopicList: {
286                     if (!isStarted) {
287                         Log.e(TAG,
288                                 "Fail to UpdateTopicList. Service has not been started");
289                         showToast("Error : Service has not been started");
290                         break;
291                     }
292                     if (mConsumerSample.getAcceptor()) {
293                         Log.e(TAG,
294                                 "Operation Not Allowed. ProviderService Acceptor is not Consumer");
295                         showToast(
296                                 "Operation Not Allowed. ProviderService Acceptor is not Consumer");
297                         break;
298                     }
299                     TvLog.append("UpdateTopicList NS-Consumer\n");
300
301                     TopicsList topicList = new TopicsList();
302                     topicList.addTopic("OCF_TOPIC1",
303                             Topic.TopicState.SUBSCRIBED);
304                     topicList.addTopic("OCF_TOPIC2",
305                             Topic.TopicState.SUBSCRIBED);
306                     topicList.addTopic("OCF_TOPIC3",
307                             Topic.TopicState.UNSUBSCRIBED);
308
309                     mConsumerSample.updateTopicList(topicList);
310                 }
311                     break;
312                 case R.id.BtnClearLog: {
313                     TvLog.setText("");
314                 }
315                     break;
316                 case R.id.signup: {
317                     if (isStarted == false) {
318                         Log.e(TAG, "Fail to Sign Up");
319                         showToast("Start ConsumerService First");
320                         break;
321                     }
322                     TvLog.append("Initiating SignUp\n");
323                     signUp();
324                 }
325                     break;
326                 case R.id.signin: {
327                     if (isStarted == false) {
328                         Log.e(TAG, "Fail to Sign In");
329                         showToast("Start ConsumerService First");
330                         break;
331                     }
332                     TvLog.append("Initiating SignIn\n");
333                     signIn();
334                 }
335                     break;
336                 case R.id.signout: {
337                     if (isStarted == false) {
338                         Log.e(TAG, "Fail to Sign out");
339                         showToast("Start ConsumerService First");
340                         break;
341                     }
342                     TvLog.append("Initiating SignOut\n");
343                     signOut();
344                 }
345                     break;
346                 case R.id.subscribeMQService: {
347                     if (isStarted == false) {
348                         Log.e(TAG, "Fail to SubscribeMQService");
349                         showToast("Start ProviderService First");
350                         break;
351                     }
352                     final Dialog dialog = new Dialog(context);
353                     dialog.setContentView(R.layout.dialog_mq);
354                     dialog.setTitle("MQ Cloud Service Details");
355
356                     final EditText ip = (EditText) dialog
357                             .findViewById(R.id.EditTextIp);
358                     final EditText mqTopic = (EditText) dialog
359                             .findViewById(R.id.EditTextMqTopic);
360                     if (MQCloudAddress != null && MQCloudTopic != null) {
361                         ip.setText(MQCloudAddress);
362                         mqTopic.setText(MQCloudTopic);
363                     }
364
365                     Button dialogButton = (Button) dialog
366                             .findViewById(R.id.mqButtonOK);
367
368                     dialogButton.setOnClickListener(new View.OnClickListener() {
369                         @Override
370                         public void onClick(View v) {
371                             dialog.dismiss();
372                             MQCloudAddress = ip.getText().toString();
373                             MQCloudTopic = mqTopic.getText().toString();
374                             mConsumerSample.subscribeMQService(
375                                     MQCloudAddress, MQCloudTopic);
376                             TvLog.append("SubscribeMQService success\n");
377                         }
378                     });
379                     dialog.show();
380                 }
381                     break;
382             }
383         }
384     };
385
386     public void logMessage(final String text) {
387         runOnUiThread(new Runnable() {
388             public void run() {
389                 Message msg = new Message();
390                 msg.obj = text;
391                 TvLog.append(text + "\n");
392             }
393         });
394         Log.i(TAG, text);
395     }
396
397     OcAccountManager.OnPostListener onSignUp  = new OcAccountManager.OnPostListener() {
398         @Override
399         public synchronized void onPostCompleted(List<OcHeaderOption> list,
400                 OcRepresentation ocRepresentation) {
401             logMessage("signUp was successful");
402             runOnUiThread(new Runnable() {
403                 public void run() {
404                     signIn.setEnabled(true);
405                     signUp.setEnabled(false);
406                 }
407             });
408             try {
409                 mUserID = ocRepresentation.getValue("uid");
410                 mAccessToken = ocRepresentation.getValue("accesstoken");
411                 mRefreshtoken = ocRepresentation.getValue("refreshtoken");
412
413                 logMessage("\tuserID: " + mUserID);
414                 logMessage("\taccessToken: " + mAccessToken);
415                 logMessage("\trefreshToken: " + mRefreshtoken);
416
417                 if (ocRepresentation.hasAttribute("expiresin")) {
418                     int expiresIn = ocRepresentation.getValue("expiresin");
419                     logMessage("\texpiresIn: " + expiresIn);
420                 }
421             } catch (OcException e) {
422                 Log.e(TAG, e.toString());
423             }
424         }
425
426         @Override
427         public synchronized void onPostFailed(Throwable throwable) {
428             logMessage("Failed to signUp");
429             if (throwable instanceof OcException) {
430                 OcException ocEx = (OcException) throwable;
431                 Log.e(TAG, ocEx.toString());
432                 ErrorCode errCode = ocEx.getErrorCode();
433                 logMessage("Error code: " + errCode);
434             }
435         }
436     };
437
438     OcAccountManager.OnPostListener onSignIn  = new OcAccountManager.OnPostListener() {
439         @Override
440         public synchronized void onPostCompleted(List<OcHeaderOption> list,
441                 OcRepresentation ocRepresentation) {
442             logMessage("signIn was successful");
443             runOnUiThread(new Runnable() {
444                 public void run() {
445                     signIn.setEnabled(false);
446                     signOut.setEnabled(true);
447                     btnEnableRemoteService.setEnabled(true);
448                 }
449             });
450
451         }
452
453         @Override
454         public synchronized void onPostFailed(Throwable throwable) {
455             logMessage("Failed to signIn");
456             if (throwable instanceof OcException) {
457                 OcException ocEx = (OcException) throwable;
458                 Log.e(TAG, ocEx.toString());
459                 ErrorCode errCode = ocEx.getErrorCode();
460                 logMessage("Error code: " + errCode);
461                 if (ErrorCode.UNAUTHORIZED_REQ != errCode) {
462                     refreshToken();
463                 }
464             }
465         }
466     };
467
468     OcAccountManager.OnPostListener onSignOut = new OcAccountManager.OnPostListener() {
469         @Override
470         public synchronized void onPostCompleted(List<OcHeaderOption> list,
471                 OcRepresentation ocRepresentation) {
472             logMessage("signOut was successful");
473             runOnUiThread(new Runnable() {
474                 public void run() {
475                     signIn.setEnabled(true);
476                     signOut.setEnabled(false);
477                     btnEnableRemoteService.setEnabled(false);
478                 }
479             });
480
481         }
482
483         @Override
484         public synchronized void onPostFailed(Throwable throwable) {
485             logMessage("Failed to signOut");
486             if (throwable instanceof OcException) {
487                 OcException ocEx = (OcException) throwable;
488                 Log.e(TAG, ocEx.toString());
489                 ErrorCode errCode = ocEx.getErrorCode();
490                 logMessage("Error code: " + errCode);
491                 if (ErrorCode.UNAUTHORIZED_REQ != errCode) {
492                     refreshToken();
493                 }
494             }
495         }
496     };
497
498
499     @Override
500     public void onPostCompleted(List<OcHeaderOption> ocHeaderOptions,
501             OcRepresentation ocRepresentation) {
502
503     }
504
505     @Override
506     public void onPostFailed(Throwable throwable) {
507
508     }
509
510     private void signIn() {
511         try {
512             if (mAccountManager == null) {
513                 mAccountManager = OcPlatform.constructAccountManagerObject(
514                         CIServer,
515                         EnumSet.of(OcConnectivityType.CT_ADAPTER_TCP));
516             }
517
518             mAccountManager.signIn(mUserID, mAccessToken, onSignIn);
519         } catch (OcException e) {
520             e.printStackTrace();
521         }
522     }
523
524     private void signOut() {
525         try {
526             logMessage("signOut");
527             if (mAccountManager == null) {
528                 try {
529                     mAccountManager = OcPlatform.constructAccountManagerObject(
530                             CIServer,
531                             EnumSet.of(OcConnectivityType.CT_ADAPTER_TCP));
532                 } catch (OcException e) {
533                     e.printStackTrace();
534                 }
535             }
536             mAccountManager.signOut(mAccessToken, onSignOut);
537             signIn.setEnabled(false);
538             signUp.setEnabled(true);
539             btnEnableRemoteService.setEnabled(false);
540             logMessage("signOut Successful");
541         } catch (OcException e) {
542             e.printStackTrace();
543         }
544     }
545
546     private void signUp() {
547         Intent intentLogin = new Intent(this, LoginActivity.class);
548         startActivityForResult(intentLogin, REQUEST_LOGIN);
549     }
550
551     @Override
552     public void onActivityResult(int requestCode, int resultCode, Intent data) {
553         super.onActivityResult(requestCode, resultCode, data);
554         if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_LOGIN) {
555             mAuthCode = data.getStringExtra("authCode");
556             mAuthProvider = data.getStringExtra("authProvider");
557             logMessage("authCode: " + mAuthCode);
558             logMessage("authProvider: " + mAuthProvider);
559
560             final Dialog dialog = new Dialog(context);
561             dialog.setContentView(R.layout.dialog_entry);
562             dialog.setTitle("SignUp Acccount IP Address");
563             final EditText ip = (EditText) dialog
564                     .findViewById(R.id.EditTextEntry);
565             if (RemoteAddress != null) {
566                 ip.setText(RemoteAddress);
567             }
568             Button dialogButton = (Button) dialog
569                     .findViewById(R.id.entryButtonOK);
570             dialogButton.setOnClickListener(new View.OnClickListener() {
571                 @Override
572                 public void onClick(View v) {
573                     dialog.dismiss();
574                     RemoteAddress = ip.getText().toString();
575                     CIServer = CI_SERVER_PREFIX + RemoteAddress;
576                     logMessage("server address for signup is: \n" + CIServer);
577                     try {
578                         mAccountManager = OcPlatform
579                                 .constructAccountManagerObject(CIServer, EnumSet
580                                         .of(OcConnectivityType.CT_ADAPTER_TCP));
581                         logMessage("Calling signup API");
582
583                         if (mAuthProvider.equals("samsung")
584                                 || mAuthProvider.equals("samsung-us")) {
585                             logMessage("Auth provider is samsung");
586                             Map<String, String> options = new HashMap<>();
587                             options.put("auth_server_url",
588                                     "us-auth2.samsungosp.com");
589                             options.put("api_server_url",
590                                     "us-auth2.samsungosp.com");
591                             mAccountManager.signUp(mAuthProvider, mAuthCode,
592                                     options, onSignUp);
593                         } else {
594                             mAccountManager.signUp(mAuthProvider, mAuthCode,
595                                     onSignUp);
596                         }
597                     } catch (OcException e) {
598                         e.printStackTrace();
599                     }
600                 }
601             });
602             dialog.show();
603         }
604     }
605
606     OcResource.OnPostListener onRefreshTokenPost = new OcResource.OnPostListener() {
607         @Override
608         public void onPostCompleted(List<OcHeaderOption> list,
609                 OcRepresentation ocRepresentation) {
610             logMessage("RefreshToken Completed.");
611             try {
612                 mAccessToken = ocRepresentation.getValue("accesstoken");
613                 mRefreshtoken = ocRepresentation.getValue("refreshtoken");
614             } catch (OcException e) {
615                 e.printStackTrace();
616             }
617             signIn();
618         }
619
620         @Override
621         public void onPostFailed(Throwable throwable) {
622             logMessage("RefreshToken failed.");
623             Log.d(TAG, "onRefreshTokenPost failed..");
624         }
625     };
626
627     public void refreshToken() {
628
629         if (deviceID == null) {
630             final Dialog dialog = new Dialog(context);
631             dialog.setContentView(R.layout.dialog_entry);
632             dialog.setTitle("Enter Device Id");
633             dialog.setCanceledOnTouchOutside(false);
634             final EditText id = (EditText) dialog
635                     .findViewById(R.id.EditTextEntry);
636
637             Button dialogButton = (Button) dialog
638                     .findViewById(R.id.entryButtonOK);
639             dialogButton.setOnClickListener(new View.OnClickListener() {
640                 @Override
641                 public void onClick(View v) {
642                     dialog.dismiss();
643                     deviceID = id.getText().toString();
644                 }
645             });
646             dialog.show();
647         }
648         try {
649             OcResource authResource = OcPlatform.constructResourceObject(
650                     CIServer, "/.well-known/ocf/account/tokenrefresh",
651                     EnumSet.of(OcConnectivityType.CT_ADAPTER_TCP,
652                             OcConnectivityType.CT_IP_USE_V4),
653                     false, Arrays.asList("oic.wk.account"),
654                     Arrays.asList(OcPlatform.DEFAULT_INTERFACE));
655             OcRepresentation rep = new OcRepresentation();
656
657             showToast("RefreshToken in progress..");
658             logMessage("RefreshToken in progress..");
659             rep.setValue("di", deviceID);
660             rep.setValue("granttype", "refresh_token");
661             rep.setValue("refreshtoken", mRefreshtoken);
662             rep.setValue("uid", mUserID);
663             authResource.post(rep, new HashMap<String, String>(),
664                     onRefreshTokenPost);
665         } catch (OcException e) {
666             e.printStackTrace();
667         }
668
669         Log.d(TAG, "No error while executing login");
670     }
671 }