2a919c3b2e4270c0eeade165e80c9e1b52bda7f0
[platform/upstream/iotivity.git] / android / examples / simplebase / src / main / java / org / iotivity / base / examples / CloudFragment.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.base.examples;
24
25 import android.app.Activity;
26 import android.app.AlertDialog;
27 import android.app.Fragment;
28 import android.content.Context;
29 import android.content.DialogInterface;
30 import android.content.Intent;
31 import android.os.Bundle;
32 import android.util.Log;
33 import android.view.LayoutInflater;
34 import android.view.View;
35 import android.view.ViewGroup;
36 import android.widget.Button;
37 import android.widget.CompoundButton;
38 import android.widget.EditText;
39 import android.widget.LinearLayout;
40 import android.widget.ScrollView;
41 import android.widget.Switch;
42 import android.widget.TextView;
43 import android.widget.Toast;
44
45 import org.iotivity.base.ModeType;
46 import org.iotivity.base.OcAccountManager;
47 import org.iotivity.base.OcConnectivityType;
48 import org.iotivity.base.OcException;
49 import org.iotivity.base.OcHeaderOption;
50 import org.iotivity.base.OcPlatform;
51 import org.iotivity.base.OcPresenceHandle;
52 import org.iotivity.base.OcRepresentation;
53 import org.iotivity.base.OcResource;
54 import org.iotivity.base.OcResourceHandle;
55 import org.iotivity.base.PlatformConfig;
56 import org.iotivity.base.QualityOfService;
57 import org.iotivity.base.ResourceProperty;
58 import org.iotivity.base.ServiceType;
59
60 import java.util.ArrayList;
61 import java.util.EnumSet;
62 import java.util.LinkedList;
63 import java.util.List;
64 import java.util.regex.Pattern;
65
66 /**
67  * This class is for messaging between the cloud server and the client.
68  * It can handle cloud API manually.
69  */
70 public class CloudFragment extends Fragment implements
71         View.OnClickListener, CompoundButton.OnCheckedChangeListener,
72         OcAccountManager.OnPostListener, OcAccountManager.OnGetListener,
73         OcAccountManager.OnDeleteListener, OcResource.OnObserveListener,
74         OcResource.OnMQTopicFoundListener, OcResource.OnMQTopicCreatedListener,
75         OcResource.OnMQTopicSubscribeListener {
76
77     private static final String TAG = "OIC_SIMPLE_CLOUD";
78     private final String EOL = System.getProperties().getProperty("line.separator");
79     private final Pattern ADDRESS_PORT
80             = Pattern.compile(
81             "((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])" +
82                     "\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)" +
83                     "\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)" +
84                     "\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9])" +
85                     "\\:([0-9]{1,5}))");
86
87     private Activity mActivity;
88     private Context mContext;
89
90     private QualityOfService mQos = QualityOfService.LOW;
91
92     private LinearLayout mAccountLayout;
93     private LinearLayout mRDLayout;
94     private LinearLayout mMQLayout;
95
96     private Switch mAccountSwitch;
97     private Switch mRDSwitch;
98     private Switch mMQSwitch;
99
100     private TextView mAccountText;
101     private TextView mRDText;
102     private TextView mMQText;
103     private ScrollView mScrollView;
104     private TextView mActionLog;
105     private TextView mResultLog;
106
107     private Button mSetIPButton;
108     private Button mSignUpButton;
109     private Button mSignInButton;
110     private Button mSignOutButton;
111     private Button mInviteButton;
112     private Button mRdPubButton;
113     private Button mRdDelButton;
114     private Button mDevicePresenceButton;
115     private Button mMqBrokerButton;
116     private Button mCreateTopicButton;
117     private Button mSubTopicButton;
118     private Button mUnsubTopicButton;
119     private Button mPubToicButton;
120
121     private OcAccountManager mAccountManager;
122     private String mAccesstoken;
123     private String mRefreshtoken;
124     private String mUserUuid;
125     private String mAuthCode;
126     private int mRequestCode;
127     private final int REQUEST_LOGIN = 1;
128
129     private OcResource MQbrokerResource = null;
130     private OcResource currentTopicResource = null;
131     private boolean switchingFlag = true;
132     private int subFlag = -1;
133     private int roomNum = 1;
134     private String defaultTopicFullName = Common.MQ_DEFAULT_TOPIC_URI;
135     private int cancelSubScribe = 0xffffff;
136
137     private OcResourceHandle localLightResourceHandle = null;
138     private List<OcResourceHandle> mResourceHandleList = new LinkedList<>();
139     private OcPresenceHandle mOcPresenceHandle;
140     //variables related observer
141     private int maxSequenceNumber = 0xFFFFFF;
142
143     @Override
144     public void onCreate(Bundle savedInstanceState) {
145         super.onCreate(savedInstanceState);
146
147         mActivity = getActivity();
148         mContext = mActivity.getBaseContext();
149         initOcPlatform(ModeType.CLIENT_SERVER);
150     }
151
152     private void initOcPlatform(ModeType type) {
153         PlatformConfig cfg = new PlatformConfig(mActivity, mContext,
154                 ServiceType.IN_PROC,
155                 type,
156                 Common.IP_ADDRESS,
157                 Common.IP_PORT,
158                 mQos);
159         OcPlatform.Configure(cfg);
160     }
161
162     private void signUp() {
163         mRequestCode = 0;
164         try {
165             mAccountManager = OcPlatform.constructAccountManagerObject(
166                     Common.HOST,
167                     EnumSet.of(OcConnectivityType.CT_ADAPTER_TCP));
168         } catch (OcException e) {
169             e.printStackTrace();
170         }
171
172         Intent intentLogin = new Intent(mContext, LoginActivity.class);
173         startActivityForResult(intentLogin, REQUEST_LOGIN);
174     }
175
176     private void signIn() {
177         mRequestCode = 1;
178         try {
179             mAccountManager.signIn(mUserUuid, mAccesstoken, this);
180         } catch (OcException e) {
181             e.printStackTrace();
182         }
183     }
184
185     private void signOut() {
186         mRequestCode = 2;
187         try {
188             mAccountManager.signOut(this);
189         } catch (OcException e) {
190             e.printStackTrace();
191         }
192     }
193
194     private void refreshAccessToken() {
195         mRequestCode = 3;
196         try {
197             mAccountManager.refreshAccessToken(mUserUuid, mRefreshtoken, this);
198         } catch (OcException e) {
199             e.printStackTrace();
200         }
201     }
202
203     private void inviteUser() {
204         mRequestCode = 4;
205         showInviteUser();
206     }
207
208     // FOR WEB-VIEW
209     @Override
210     public void onActivityResult(int requestCode, int resultCode, Intent data) {
211         super.onActivityResult(requestCode, resultCode, data);
212         if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_LOGIN) {
213             mAuthCode = data.getStringExtra("authCode");
214             msg("\tauthCode: " + mAuthCode);
215
216             try {
217                 msg("Sign Up");
218                 mAccountManager.signUp("github", mAuthCode, this);
219             } catch (OcException e) {
220                 e.printStackTrace();
221             }
222         }
223     }
224
225     @Override
226     public void onPostCompleted(List<OcHeaderOption> list, OcRepresentation ocRepresentation) {
227         try {
228             if (mRequestCode == 0) {
229                 msg("\tSign Up Success");
230                 if (ocRepresentation.hasAttribute("uid")) {
231                     mUserUuid = ocRepresentation.getValue("uid");
232                     msg("\tuserID: " + mUserUuid);
233                 }
234                 if (ocRepresentation.hasAttribute("accesstoken")) {
235                     mAccesstoken = ocRepresentation.getValue("accesstoken");
236                     msg("\taccessToken: " + mAccesstoken);
237                 }
238                 if (ocRepresentation.hasAttribute("refreshtoken")) {
239                     mRefreshtoken = ocRepresentation.getValue("refreshtoken");
240                     msg("\trefreshtoken: " + mRefreshtoken);
241                 }
242             } else if (mRequestCode == 1) {
243                 msg("\tSign In Success");
244             } else if (mRequestCode == 2) {
245                 msg("\tSign Out Success");
246             } else if (mRequestCode == 3) {
247                 msg("\tRefresh AccessToken Success");
248             } else if (mRequestCode == 4) {
249                 msg("\tDelete Device Success");
250             }
251         } catch (OcException e) {
252             e.printStackTrace();
253         }
254     }
255
256     @Override
257     public void onPostFailed(Throwable throwable) {
258         msg("onPostFailed");
259         if (throwable instanceof OcException) {
260             OcException ocEx = (OcException) throwable;
261             Log.e(TAG, ocEx.toString());
262         }
263     }
264
265     @Override
266     public void onGetCompleted(List<OcHeaderOption> list, OcRepresentation ocRepresentation) {
267
268     }
269
270     @Override
271     public void onGetFailed(Throwable throwable) {
272
273     }
274
275     @Override
276     public void onDeleteCompleted(List<OcHeaderOption> list) {
277
278     }
279
280     @Override
281     public void onDeleteFailed(Throwable throwable) {
282
283     }
284
285     // ******************************************************************************
286     // End of the Account Manager specific code
287     // ******************************************************************************
288
289     OcPlatform.OnPublishResourceListener resourcePublishListener =
290             new OcPlatform.OnPublishResourceListener() {
291                 @Override
292                 public void onPublishResourceCompleted(OcRepresentation ocRepresentation) {
293                     msg("onPublishResourceCompleted");
294
295                     for (OcRepresentation child : ocRepresentation.getChildren()) {
296                         try {
297                             msg("\tPublished Resource URI : " + child.getValue("href"));
298                         } catch (OcException e) {
299                             e.printStackTrace();
300                         }
301                     }
302                 }
303
304                 @Override
305                 public void onPublishResourceFailed(Throwable throwable) {
306                     msg("onPublishResourceFailed has failed");
307                 }
308             };
309
310     OcPlatform.OnDeleteResourceListener resourceDeleteListener =
311             new OcPlatform.OnDeleteResourceListener() {
312                 @Override
313                 public void onDeleteResourceCompleted(int resultCode) {
314                     msg("onDeleteResourceCompleted, result is " + resultCode);
315                 }
316             };
317
318     private void createResource() {
319         if (localLightResourceHandle == null) {
320             try {
321                 localLightResourceHandle = OcPlatform.registerResource(
322                         Common.RESOURCE_URI,            //resource URI
323                         Common.RESOURCE_TYPE,           //resource type name
324                         Common.RESOURCE_INTERFACE,      //using default interface
325                         null,                           //use default entity handler
326                         EnumSet.of(ResourceProperty.DISCOVERABLE)
327                 );
328                 mResourceHandleList.add(localLightResourceHandle);
329                 msg("Create Local Resource is success.");
330             } catch (OcException e) {
331                 Log.e(TAG, e.toString());
332             }
333         }
334     }
335
336     private void publishResourceToRD() {
337         // Create Local Resource.
338         createResource();
339
340         try {
341             // Publish Virtual Resource to Resource-Directory.
342             Log.d(TAG, "Publish Virtual Resource to Resource-Directory.");
343             OcPlatform.publishResourceToRD(
344                     Common.HOST, EnumSet.of(OcConnectivityType.CT_ADAPTER_TCP),
345                     resourcePublishListener
346             );
347
348             // Publish Local Resource to Resource-Directory.
349             Log.d(TAG, "Publish Local Resource to Resource-Directory.");
350             OcPlatform.publishResourceToRD(
351                     Common.HOST, EnumSet.of(OcConnectivityType.CT_ADAPTER_TCP), mResourceHandleList,
352                     resourcePublishListener
353             );
354         } catch (OcException e) {
355             Log.e(TAG, e.toString());
356         }
357     }
358
359     private void deleteResourceFromRD() {
360         try {
361             // Delete Resource from Resource-Directory.
362             Log.d(TAG, "Delete Resource from Resource-Directory.");
363             OcPlatform.deleteResourceFromRD(
364                     Common.HOST, EnumSet.of(OcConnectivityType.CT_ADAPTER_TCP),
365                     resourceDeleteListener
366             );
367         } catch (OcException e) {
368             Log.e(TAG, e.toString());
369         }
370     }
371
372     private void subscribeDevicePresence() {
373         try {
374             List<String> di = new ArrayList<>();
375             mOcPresenceHandle = OcPlatform.subscribeDevicePresence(
376                     Common.HOST, di, EnumSet.of(OcConnectivityType.CT_ADAPTER_TCP), this);
377         } catch (OcException e) {
378             e.printStackTrace();
379         }
380     }
381
382     @Override
383     public void onObserveCompleted(List<OcHeaderOption> list,
384                                    OcRepresentation ocRepresentation, int sequenceNumber) {
385         if (sequenceNumber != maxSequenceNumber + 1) {
386             msg("OBSERVE Result:");
387             msg("\tSequenceNumber:" + sequenceNumber);
388             try {
389                 if (ocRepresentation.hasAttribute("prslist")) {
390                     OcRepresentation[] prslist = ocRepresentation.getValue("prslist");
391                     if (prslist != null) {
392                         msg("\tDevice Presence");
393                         for (OcRepresentation prs : prslist) {
394                             msg("\t\tDevice ID : " + prs.getValue("di"));
395                             msg("\t\tState : " + prs.getValue("state"));
396                         }
397                     }
398                 }
399             } catch (OcException e) {
400                 e.printStackTrace();
401             }
402         }
403     }
404
405     @Override
406     public void onObserveFailed(Throwable throwable) {
407
408     }
409
410     // ******************************************************************************
411     // End of the Resource Directory specific code
412     // ******************************************************************************
413
414     void getMQBroker() {
415         List<String> resourceTypeList = new ArrayList<String>();
416         List<String> resourceInterfaceList = new ArrayList<String>();
417         resourceInterfaceList.add(Common.RESOURCE_INTERFACE);
418         resourceTypeList.add("ocf.wk.ps");
419         try {
420             MQbrokerResource = OcPlatform.constructResourceObject(
421                     "coap+tcp://" + Common.TCP_ADDRESS + ":" + Common.TCP_PORT,
422                     Common.MQ_BROKER_URI,
423                     EnumSet.of(OcConnectivityType.CT_ADAPTER_TCP, OcConnectivityType.CT_IP_USE_V4),
424                     false,
425                     resourceTypeList, resourceInterfaceList);
426
427             msg("found MQ broker : " + MQbrokerResource.getHost());
428
429             discoveryMQTopics();
430
431         } catch (OcException e) {
432             e.printStackTrace();
433         }
434     }
435
436     void discoveryMQTopics() {
437         try {
438             if (null != MQbrokerResource) {
439                 MQbrokerResource.discoveryMQTopics(
440                         new HashMap<String, String>(),
441                         this, QualityOfService.LOW);
442             }
443
444         } catch (OcException e) {
445             e.printStackTrace();
446         }
447     }
448
449     @Override
450     synchronized public void onTopicDiscoveried(OcResource ocResource) {
451         synchronized (this) {
452             String resourceUri = ocResource.getUri();
453
454             Log.d(TAG, "onTopicDiscoveried : " + resourceUri + " found");
455             msg("onTopicDiscoveried : " + resourceUri + " found");
456         }
457     }
458
459     @Override
460     public void onDiscoveryTopicFailed(Throwable ex, String uri) {
461         Log.e(TAG, "onFindTopicFailed : ", ex);
462
463         if (ex instanceof OcException) {
464             OcException ocEx = (OcException) ex;
465             ErrorCode errCode = ocEx.getErrorCode();
466             Log.d(TAG, "onFindTopicFailed Code: " + errCode);
467             Log.d(TAG, "onFindTopicFailed Code: " + errCode.ordinal());
468             Log.d(TAG, "onFindTopicFailed uri: " + uri);
469
470         } else {
471             Log.e(TAG, ex.getMessage());
472         }
473     }
474
475     void createMQTopic() {
476         try {
477             if (null != MQbrokerResource) {
478                 Map<String, String> queryParameters = new HashMap<String, String>();
479                 queryParameters.put("rt", "light");
480                 MQbrokerResource.createMQTopic(
481                         new OcRepresentation(),
482                         defaultTopicFullName,
483                         queryParameters,
484                         this,
485                         QualityOfService.LOW);
486             }
487         } catch (OcException e) {
488             e.printStackTrace();
489         }
490     }
491
492     @Override
493     synchronized public void onTopicResourceCreated(OcResource ocResource) {
494         synchronized (this) {
495             Log.d(TAG, "onTopicResourceCreated");
496             String resourceUri = ocResource.getUri();
497             currentTopicResource = ocResource;
498             Log.d(TAG, "onTopicResourceCreated : " + resourceUri + " found");
499
500             msg("onTopicCreated : " + currentTopicResource.getUri());
501         }
502     }
503
504     @Override
505     public void onCreateTopicFailed(Throwable ex, String uri) {
506         Log.e(TAG, "onCreateTopicFailed : ", ex);
507
508         if (ex instanceof OcException) {
509             OcException ocEx = (OcException) ex;
510             ErrorCode errCode = ocEx.getErrorCode();
511             Log.d(TAG, "onCreateTopicFailed error Code: " + errCode);
512             Log.d(TAG, "onCreateTopicFailed error Code: " + errCode.ordinal());
513             Log.d(TAG, "onCreateTopicFailed error uri: " + uri);
514
515             // retry to create after increase room number
516             defaultTopicFullName = Common.MQ_DEFAULT_TOPIC_URI + (roomNum++);
517             createMQTopic();
518         } else {
519             Log.e(TAG, ex.getMessage());
520         }
521     }
522
523     void subscribeMQTopic() {
524         Map<String, String> queryParameters = new HashMap<String, String>();
525         queryParameters.put("rt", "light");
526
527         try {
528             if (null != currentTopicResource) {
529                 currentTopicResource.subscribeMQTopic(
530                         queryParameters,
531                         this,
532                         QualityOfService.LOW);
533             }
534
535         } catch (OcException e) {
536             e.printStackTrace();
537         }
538     }
539
540     @Override
541     synchronized public void onSubScribeCompleted(List<OcHeaderOption> headerOptionList,
542                                                   OcRepresentation ocRepresentation,
543                                                   int sequenceNumber) {
544         synchronized (this) {
545             String resourceUri = ocRepresentation.getUri();
546             Log.d(TAG, "onSubScribeCompleted sequenceNumber : " + sequenceNumber);
547
548             try {
549                 OcRepresentation val = ocRepresentation.getValue("message");
550
551                 if (sequenceNumber == 0) {
552                     Log.d(TAG, "onSubScribeCompleted : " + resourceUri);
553                     subFlag = 0;
554                 } else {
555                     subFlag = 1;
556                 }
557
558                 if (subFlag == 0) {
559                     msg("onSubScribeCompleted : " + resourceUri);
560                 } else {
561                     Log.d(TAG, "onSubScribeCompleted : " + resourceUri);
562                     Log.d(TAG, "onSubScribeCompleted : " + val.getValue("blue"));
563                     Log.d(TAG, "onSubScribeCompleted : " + val.getValue("red"));
564
565                     msg("onSubScribeCompleted : " + resourceUri + ", blue light is "
566                             + val.getValue("blue").toString());
567                     msg("onSubScribeCompleted : " + resourceUri + ", red light is "
568                             + val.getValue("red").toString());
569                 }
570             } catch (OcException e) {
571                 e.printStackTrace();
572             }
573         }
574     }
575
576     @Override
577     synchronized public void onUnsubScribeCompleted(OcRepresentation ocRepresentation,
578                                                     int sequenceNumber) {
579         synchronized (this) {
580             String resourceUri = ocRepresentation.getUri();
581             Log.d(TAG, "onUnsubScribeCompleted sequenceNumber : " + sequenceNumber);
582
583             if (sequenceNumber == cancelSubScribe + 1) {
584                 Log.d(TAG, "onUnsubScribeCompleted : " + resourceUri);
585                 msg("onUnsubScribeCompleted : " + resourceUri);
586             }
587         }
588     }
589
590     @Override
591     public void onSubScribeFailed(Throwable ex) {
592         Log.d(TAG, "onSubScribeFailed : ", ex);
593
594         if (ex instanceof OcException) {
595             OcException ocEx = (OcException) ex;
596             ErrorCode errCode = ocEx.getErrorCode();
597             Log.d(TAG, "onSubScribeFailed error Code: " + errCode);
598             Log.d(TAG, "onSubScribeFailed error Code: " + errCode.ordinal());
599
600
601         } else {
602             Log.e(TAG, ex.getMessage());
603         }
604     }
605
606
607     void unsubscribeMQTopic() {
608
609         try {
610             if (null != currentTopicResource) {
611                 currentTopicResource.unsubscribeMQTopic(QualityOfService.LOW);
612             }
613
614         } catch (OcException e) {
615             e.printStackTrace();
616         }
617     }
618
619     void publishMQTopic() {
620
621         try {
622             OcRepresentation rep = new OcRepresentation();
623             OcRepresentation msg = new OcRepresentation();
624
625             if (switchingFlag) {
626                 msg.setValue("blue", "on");
627                 msg.setValue("red", "off");
628                 switchingFlag = false;
629             } else {
630                 msg.setValue("blue", "off");
631                 msg.setValue("red", "on");
632                 switchingFlag = true;
633             }
634             rep.setValue("message", msg);
635
636             if (null != currentTopicResource) {
637                 currentTopicResource.publishMQTopic(rep,
638                         new HashMap<String, String>(),
639                         mqPublishListener,
640                         QualityOfService.LOW);
641             }
642
643         } catch (OcException e) {
644             e.printStackTrace();
645         }
646     }
647
648     OcResource.OnPostListener mqPublishListener =
649             new OcResource.OnPostListener() {
650                 @Override
651                 public void onPostCompleted(List<OcHeaderOption> list,
652                                             OcRepresentation ocRepresentation) {
653                     Log.i(TAG, "onPublish completed");
654                     msg("onPublish completed");
655                 }
656
657                 @Override
658                 public void onPostFailed(Throwable throwable) {
659                     Log.e(TAG, "onPublish failed");
660                     msg("onPublish failed");
661                 }
662             };
663
664     void requestMQPublish() {
665
666         try {
667             if (null != currentTopicResource) {
668                 currentTopicResource.requestMQPublish(
669                         new HashMap<String, String>(),
670                         mqReqPubListener,
671                         QualityOfService.LOW);
672             }
673         } catch (OcException e) {
674             e.printStackTrace();
675         }
676     }
677
678     OcResource.OnPostListener mqReqPubListener =
679             new OcResource.OnPostListener() {
680                 @Override
681                 public void onPostCompleted(List<OcHeaderOption> list,
682                                             OcRepresentation ocRepresentation) {
683                     Log.i(TAG, "onRequestPublish completed");
684                     msg("onPublish completed");
685                 }
686
687                 @Override
688                 public void onPostFailed(Throwable throwable) {
689                     Log.e(TAG, "onRequestPublish failed");
690                     msg("onRequestPublish failed");
691                 }
692             };
693
694
695     // ******************************************************************************
696     // End of the Message Queue specific code
697     // ******************************************************************************
698
699     private void showTCPInput() {
700
701         LayoutInflater layoutInflater = LayoutInflater.from(mContext);
702         View inputView = layoutInflater.inflate(R.layout.tcp_input, null);
703         AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(mActivity);
704         alertDialogBuilder.setView(inputView);
705
706         final EditText editText = (EditText) inputView.getRootView().findViewById(R.id.inputText);
707         StringBuilder sb = new StringBuilder();
708         sb.append(Common.TCP_ADDRESS);
709         sb.append(Common.PORT_SEPARATOR);
710         sb.append(Common.TCP_PORT);
711         editText.setText(sb.toString());
712         alertDialogBuilder
713                 .setCancelable(true)
714                 .setPositiveButton("OK", new DialogInterface.OnClickListener() {
715                     public void onClick(DialogInterface dialog, int id) {
716                         if (editText.getText().length() != 0) {
717                             final String hosts = editText.getText().toString();
718                             boolean isValid = ADDRESS_PORT.matcher(hosts).matches();
719                             if (isValid) {
720                                 final String host[] = hosts.split(Common.PORT_SEPARATOR);
721                                 Common.TCP_ADDRESS = host[0];
722                                 Common.TCP_PORT = host[1];
723
724                                 StringBuilder sb = new StringBuilder();
725                                 sb.append(Common.COAP_TCP);
726                                 sb.append(Common.TCP_ADDRESS);
727                                 sb.append(Common.PORT_SEPARATOR);
728                                 sb.append(Common.TCP_PORT);
729                                 Common.HOST = sb.toString();
730                             } else {
731                                 Toast.makeText(mContext, "Invalid IP", Toast.LENGTH_SHORT).show();
732                                 showTCPInput();
733                             }
734                         }
735                     }
736                 })
737                 .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
738                     public void onClick(DialogInterface dialog, int id) {
739                         dialog.cancel();
740                     }
741                 });
742
743         AlertDialog alert = alertDialogBuilder.create();
744         alert.show();
745     }
746
747     private void showInviteUser() {
748
749         LayoutInflater layoutInflater = LayoutInflater.from(mContext);
750         View inputView = layoutInflater.inflate(R.layout.tcp_input, null);
751         AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(mActivity);
752         alertDialogBuilder.setView(inputView);
753
754         final TextView textView = (TextView) inputView.getRootView().findViewById(R.id.inputView);
755         textView.setText("Please enter user id to invite.");
756         final EditText editText = (EditText) inputView.getRootView().findViewById(R.id.inputText);
757
758         alertDialogBuilder
759                 .setCancelable(true)
760                 .setPositiveButton("OK", new DialogInterface.OnClickListener() {
761                     public void onClick(DialogInterface dialog, int id) {
762                         if (editText.getText().length() != 0) {
763                             final String userID = editText.getText().toString();
764                             msg("User ID: " + userID);
765                         }
766                     }
767                 })
768                 .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
769                     public void onClick(DialogInterface dialog, int id) {
770                         dialog.cancel();
771                     }
772                 });
773
774         AlertDialog alert = alertDialogBuilder.create();
775         alert.show();
776     }
777
778     private void showInviteMsg(String userID) {
779
780         AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(mActivity);
781         alertDialogBuilder.setTitle("Invitation");
782         StringBuilder sb = new StringBuilder();
783         sb.append("Invited from ");
784         sb.append(userID);
785         sb.append(EOL);
786         sb.append("Accept?");
787         alertDialogBuilder.setMessage(sb.toString());
788
789         alertDialogBuilder
790                 .setCancelable(true)
791                 .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
792                     public void onClick(DialogInterface dialog, int id) {
793                         msg("OK");
794                     }
795                 })
796                 .setNegativeButton("No", new DialogInterface.OnClickListener() {
797                     public void onClick(DialogInterface dialog, int id) {
798                         dialog.cancel();
799                     }
800                 });
801
802         AlertDialog alert = alertDialogBuilder.create();
803         alert.show();
804     }
805
806     private void msg(final String text) {
807         mActivity.runOnUiThread(new Runnable() {
808             public void run() {
809                 mResultLog.append(EOL);
810                 mResultLog.append(text);
811                 mScrollView.fullScroll(View.FOCUS_DOWN);
812             }
813         });
814         Log.i(TAG, text);
815     }
816
817     @Override
818     public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
819
820         int visible;
821         if (isChecked) {
822             visible = View.VISIBLE;
823         } else {
824             visible = View.GONE;
825         }
826
827         switch (buttonView.getId()) {
828             case R.id.account_switch:
829                 mAccountLayout.setVisibility(visible);
830                 break;
831             case R.id.rd_switch:
832                 mRDLayout.setVisibility(visible);
833                 break;
834             case R.id.mq_switch:
835                 mMQLayout.setVisibility(visible);
836                 break;
837         }
838     }
839
840     @Override
841     public void onClick(View view) {
842         mActionLog.setText("[Action Log]" + EOL);
843         switch (view.getId()) {
844             // Account
845             case R.id.setip_button:
846                 mActionLog.append("Set IP" + EOL);
847                 showTCPInput();
848                 break;
849             case R.id.signup_button:
850                 mActionLog.append("Sign Up" + EOL);
851                 signUp();
852                 break;
853             case R.id.signin_button:
854                 mActionLog.append("Sign In" + EOL);
855                 signIn();
856                 break;
857             case R.id.signout_button:
858                 mActionLog.append("Sign Out" + EOL);
859                 signOut();
860                 break;
861             case R.id.invite_button:
862                 mActionLog.append("Refresh Access Token" + EOL);
863                 refreshAccessToken();
864                 break;
865
866             // RD
867             case R.id.rdpub_button:
868                 mActionLog.append("Publish Resource To RD" + EOL);
869                 publishResourceToRD();
870                 break;
871             case R.id.rddel_button:
872                 mActionLog.append("Delete Resource From RD" + EOL);
873                 deleteResourceFromRD();
874                 break;
875             case R.id.rddp_button:
876                 mActionLog.append("Subscribe Device Presence" + EOL);
877                 subscribeDevicePresence();
878                 break;
879
880             // MQ
881             case R.id.mqget_button:
882                 mActionLog.append("Get MQ Broker" + EOL);
883                 getMQBroker();
884                 break;
885             case R.id.mqcreate_button:
886                 mActionLog.append("Create MQ Topic" + EOL);
887                 createMQTopic();
888                 break;
889             case R.id.mqsub_button:
890                 mActionLog.append("Subscribe MQ Topic" + EOL);
891                 subscribeMQTopic();
892                 break;
893             case R.id.mqunsub_button:
894                 mActionLog.append("Un-subscribe MQ Topic" + EOL);
895                 unsubscribeMQTopic();
896                 break;
897             case R.id.mqpub_button:
898                 mActionLog.append("Publish MQ Topic" + EOL);
899                 publishMQTopic();
900                 break;
901         }
902     }
903
904     @Override
905     public View onCreateView(LayoutInflater inflater, ViewGroup container,
906                              Bundle savedInstanceState) {
907         View rootView = inflater.inflate(R.layout.fragment_cloud, container, false);
908
909         mAccountLayout = (LinearLayout) rootView.findViewById(R.id.account_layout);
910         mRDLayout = (LinearLayout) rootView.findViewById(R.id.rd_layout);
911         mMQLayout = (LinearLayout) rootView.findViewById(R.id.mq_layout);
912
913         mAccountSwitch = (Switch) rootView.findViewById(R.id.account_switch);
914         mRDSwitch = (Switch) rootView.findViewById(R.id.rd_switch);
915         mMQSwitch = (Switch) rootView.findViewById(R.id.mq_switch);
916         mAccountSwitch.setOnCheckedChangeListener(this);
917         mRDSwitch.setOnCheckedChangeListener(this);
918         mMQSwitch.setOnCheckedChangeListener(this);
919
920         mAccountText = (TextView) rootView.findViewById(R.id.account_view);
921         mRDText = (TextView) rootView.findViewById(R.id.rd_view);
922         mMQText = (TextView) rootView.findViewById(R.id.mq_view);
923         mScrollView = (ScrollView) rootView.findViewById(R.id.scroll_view);
924         mActionLog = (TextView) rootView.findViewById(R.id.action_log_view);
925         mResultLog = (TextView) rootView.findViewById(R.id.result_log_view);
926
927         mSetIPButton = (Button) rootView.findViewById(R.id.setip_button);
928         mSignUpButton = (Button) rootView.findViewById(R.id.signup_button);
929         mSignInButton = (Button) rootView.findViewById(R.id.signin_button);
930         mSignOutButton = (Button) rootView.findViewById(R.id.signout_button);
931         mInviteButton = (Button) rootView.findViewById(R.id.invite_button);
932         mSetIPButton.setOnClickListener(this);
933         mSignUpButton.setOnClickListener(this);
934         mSignInButton.setOnClickListener(this);
935         mSignOutButton.setOnClickListener(this);
936         mInviteButton.setOnClickListener(this);
937
938         mRdPubButton = (Button) rootView.findViewById(R.id.rdpub_button);
939         mRdDelButton = (Button) rootView.findViewById(R.id.rddel_button);
940         mDevicePresenceButton = (Button) rootView.findViewById(R.id.rddp_button);
941         mRdPubButton.setOnClickListener(this);
942         mRdDelButton.setOnClickListener(this);
943         mDevicePresenceButton.setOnClickListener(this);
944
945         mMqBrokerButton = (Button) rootView.findViewById(R.id.mqget_button);
946         mCreateTopicButton = (Button) rootView.findViewById(R.id.mqcreate_button);
947         mSubTopicButton = (Button) rootView.findViewById(R.id.mqsub_button);
948         mUnsubTopicButton = (Button) rootView.findViewById(R.id.mqunsub_button);
949         mPubToicButton = (Button) rootView.findViewById(R.id.mqpub_button);
950         mMqBrokerButton.setOnClickListener(this);
951         mCreateTopicButton.setOnClickListener(this);
952         mSubTopicButton.setOnClickListener(this);
953         mUnsubTopicButton.setOnClickListener(this);
954         mPubToicButton.setOnClickListener(this);
955
956         return rootView;
957     }
958
959     @Override
960     public void onResume() {
961         super.onResume();
962     }
963
964     @Override
965     public void onDestroy() {
966         super.onDestroy();
967     }
968
969 }
970