replace : iotivity -> iotivity-sec
[platform/upstream/iotivity.git] / service / easy-setup / sampleapp / mediator / android-samsung / EasySetup / app / src / main / java / org / iotivity / service / easysetup / EasysetupActivity.java
1 /**
2  * ***************************************************************
3  * <p/>
4  * Copyright 2016 Samsung Electronics All Rights Reserved.
5  * <p/>
6  * <p/>
7  * <p/>
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  * <p/>
12  * http://www.apache.org/licenses/LICENSE-2.0
13  * <p/>
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  * <p/>
20  * ****************************************************************
21  */
22
23 package org.iotivity.service.easysetup;
24
25 import android.app.Activity;
26 import android.content.Context;
27 import android.content.Intent;
28 import android.content.SharedPreferences;
29 import android.os.Bundle;
30 import android.preference.PreferenceManager;
31 import android.util.Log;
32 import android.view.View;
33 import android.widget.ArrayAdapter;
34 import android.widget.Button;
35 import android.widget.EditText;
36 import android.widget.LinearLayout;
37 import android.widget.RadioButton;
38 import android.widget.RadioGroup;
39 import android.widget.Spinner;
40 import android.widget.TextView;
41 import android.widget.Toast;
42 import android.widget.ToggleButton;
43
44 import org.iotivity.base.ErrorCode;
45 import org.iotivity.base.ModeType;
46 import org.iotivity.base.OcConnectivityType;
47 import org.iotivity.base.OcException;
48 import org.iotivity.base.OcHeaderOption;
49 import org.iotivity.base.ObserveType;
50 import org.iotivity.base.OcPlatform;
51 import org.iotivity.base.OcPresenceStatus;
52 import org.iotivity.base.OcProvisioning;
53 import org.iotivity.base.OcRepresentation;
54 import org.iotivity.base.OcResource;
55 import org.iotivity.base.PlatformConfig;
56 import org.iotivity.base.QualityOfService;
57 import org.iotivity.base.ServiceType;
58 import org.iotivity.base.OcAccountManager;
59 import org.iotivity.service.easysetup.mediator.ESConstants;
60 import org.iotivity.service.easysetup.mediator.CloudProp;
61 import org.iotivity.service.easysetup.mediator.CloudPropProvisioningCallback;
62 import org.iotivity.service.easysetup.mediator.CloudPropProvisioningStatus;
63 import org.iotivity.service.easysetup.mediator.DevicePropProvisioningCallback;
64 import org.iotivity.service.easysetup.mediator.DevicePropProvisioningStatus;
65 import org.iotivity.service.easysetup.mediator.ESException;
66 import org.iotivity.service.easysetup.mediator.EasySetup;
67 import org.iotivity.service.easysetup.mediator.GetConfigurationCallback;
68 import org.iotivity.service.easysetup.mediator.GetConfigurationStatus;
69 import org.iotivity.service.easysetup.mediator.RemoteEnrollee;
70 import org.iotivity.service.easysetup.mediator.SecurityProvisioningCallback;
71 import org.iotivity.service.easysetup.mediator.SecurityProvisioningStatus;
72 import org.iotivity.service.easysetup.mediator.enums.ESCloudProvState;
73 import org.iotivity.service.easysetup.mediator.enums.ESResult;
74 import org.iotivity.service.easysetup.mediator.enums.WIFI_AUTHTYPE;
75 import org.iotivity.service.easysetup.mediator.enums.WIFI_ENCTYPE;
76 import org.iotivity.service.easysetup.mediator.enums.WIFI_FREQ;
77 import org.iotivity.service.easysetup.mediator.enums.WIFI_MODE;
78 import org.iotivity.service.easysetup.mediator.samsung.SCDeviceProp;
79 import org.iotivity.service.easysetup.mediator.samsung.SCEnrolleeConf;
80
81 import java.io.File;
82 import java.io.FileNotFoundException;
83 import java.io.FileOutputStream;
84 import java.io.IOException;
85 import java.io.InputStream;
86 import java.io.OutputStream;
87 import java.util.ArrayList;
88 import java.util.Arrays;
89 import java.util.EnumSet;
90 import java.util.HashMap;
91 import java.util.List;
92
93
94 public class EasysetupActivity extends Activity
95                                 implements OcPlatform.OnPresenceListener,
96                                            OcResource.OnObserveListener{
97     private static final String TAG = "Easysetup Mediator: ";
98     PlatformConfig cfg;
99     OcAccountManager m_accountManager = null;
100     final String deviceID = "9E09F4FE-978A-4BC3-B356-1F93BCA37829";
101     final String samsungCIServer = "coap+tcp://52.69.149.85:5683";
102
103     private static final int BUFFER_SIZE = 1024;
104
105     private String filePath = "";
106     public static final String OIC_CLIENT_JSON_DB_FILE =  "oic_svr_db_client.dat";
107     public static final String OIC_SQL_DB_FILE =  "PDM.db";
108
109     private boolean isFirstTime = true;
110     String mEnrolleeDeviceID;
111     String mAuthCode;
112     String mAuthProvider;
113     String mRefreshtoken;
114     String mUserID;
115     String mAccessToken;
116     String mEnrolleeAuthCode;
117
118     ToggleButton mSecurityMode;
119
120     RadioGroup mEasysetupProcess;
121     RadioButton mConfigureSecProcess;
122     RadioButton mGetConfigurationProcess;
123     RadioButton mProvisionDevPropProcess;
124     RadioButton mProvisionCloudPropProcess;
125
126     Button mDiscoverResource;
127     Button mStartGetConfiguration;
128     Button mStartConfigureSec;
129     Button mStartProvisionDevProp;
130     Button mStartProvisionCloudProp;
131
132     TextView mGetconfigurationStateText;
133     TextView mDevNameText;
134     TextView mModelNumberText;
135     TextView mDevTypeText;
136     TextView mDevSubTypeText;
137     TextView mWifiModeText;
138     TextView mWifiFreqText;
139     TextView mCloudAccessableText;
140     TextView mSecStateText;
141     TextView mSecDevIDText;
142     TextView mProvisionDevPropState;
143     TextView mProvisionCloudPropState;
144
145     EditText mEnrollerSsidText;
146     EditText mEnrollerPWText;
147     EditText mInputLanguageText;
148     EditText mInputCountryText;
149     EditText mInputLocationText;
150     EditText mDiscoveryChannelText;
151     EditText mAddrText;
152     EditText mZipCodeText;
153     EditText mBuildingText;
154     EditText mAuthCodeText;
155     EditText mAuthProviderText;
156     EditText mCIServerText;
157
158     LinearLayout mGetConfigurationInfo;
159     LinearLayout mConfigureSecInfo;
160     LinearLayout mProvisionDevPropInfo;
161     LinearLayout mProvisionCloudPropInfo;
162
163     Spinner mAuthType;
164     Spinner mEncType;
165
166     EasySetup mEasySetup;
167     RemoteEnrollee mRemoteEnrollee;
168
169     Activity mActivity;
170     Context mContext;
171
172     @Override
173     protected void onCreate(Bundle savedInstanceState) {
174         super.onCreate(savedInstanceState);
175         setContentView(R.layout.easysetup_main);
176
177         mActivity = EasysetupActivity.this;
178         mContext = mActivity.getBaseContext();
179
180         mSecurityMode = (ToggleButton) findViewById(R.id.btn_Security);
181
182         mEasysetupProcess = (RadioGroup) findViewById(R.id.rg_EasysetupProcess);
183
184         mConfigureSecProcess = (RadioButton) findViewById(R.id.btn_configurSec);
185         mGetConfigurationProcess = (RadioButton) findViewById(R.id.btn_getConfiguration);
186         mProvisionDevPropProcess = (RadioButton) findViewById(R.id.btn_provisionDevConf);
187         mProvisionCloudPropProcess =
188                 (RadioButton) findViewById(R.id.btn_provisionCloudConf);
189
190         mDiscoverResource = (Button) findViewById(R.id.btn_discoverResource);
191         mStartGetConfiguration =
192                 (Button) findViewById(R.id.btn_startGetConfiguration);
193         mStartConfigureSec = (Button) findViewById(R.id.btn_startConfigureSec);
194         mStartProvisionDevProp = (Button) findViewById(R.id.btn_startProvisionDevConf);
195         mStartProvisionCloudProp = (Button) findViewById(R.id.btn_startProvisionCloudConf);
196
197         mGetconfigurationStateText =
198                 (TextView) findViewById(R.id.txt_getConfigurationState);
199         mDevNameText = (TextView) findViewById(R.id.txt_devName);
200         mModelNumberText = (TextView) findViewById(R.id.txt_modelNumber);
201         mDevTypeText = (TextView) findViewById(R.id.txt_devType);
202         mDevSubTypeText = (TextView) findViewById(R.id.txt_devSubType);
203         mWifiModeText = (TextView) findViewById(R.id.txt_wifiMode);
204         mWifiFreqText = (TextView) findViewById(R.id.txt_wifiFreq);
205         mCloudAccessableText = (TextView) findViewById(R.id.txt_cloudAccessable);
206         mSecStateText = (TextView) findViewById(R.id.txt_secState);
207         mSecDevIDText = (TextView) findViewById(R.id.txt_secDevID);
208         mProvisionDevPropState = (TextView) findViewById(R.id.txt_provisionDevConfState);
209         mProvisionCloudPropState =
210                 (TextView) findViewById(R.id.txt_provisionCloudConfState);
211
212         mEnrollerSsidText = (EditText) findViewById(R.id.editText_EnrollerSSID);
213         mEnrollerPWText = (EditText) findViewById(R.id.editText_EnrollerPW);
214         mInputLanguageText = (EditText) findViewById(R.id.editText_Language);
215         mInputCountryText = (EditText) findViewById(R.id.editText_Country);
216         mInputLocationText = (EditText) findViewById(R.id.editText_Location);
217         mDiscoveryChannelText = (EditText) findViewById(R.id.editText_DiscoveryChannel);
218         mAddrText = (EditText) findViewById(R.id.editText_LocationAddr);
219         mZipCodeText = (EditText) findViewById(R.id.editText_LocationZip);
220         mBuildingText = (EditText) findViewById(R.id.editText_LocationBuilding);
221         mAuthCodeText = (EditText) findViewById(R.id.editText_authcode);
222         mAuthProviderText = (EditText) findViewById(R.id.editText_authprovider);
223         mCIServerText = (EditText) findViewById(R.id.editText_ciserver);
224
225         mGetConfigurationInfo =
226                 (LinearLayout) findViewById(R.id.layout_GetConfiguration);
227         mConfigureSecInfo = (LinearLayout) findViewById(R.id.layout_ConfigurSec);
228         mProvisionDevPropInfo = (LinearLayout) findViewById(R.id.layout_ProvisionDevConf);
229         mProvisionCloudPropInfo = (LinearLayout) findViewById(R.id.layout_ProvisionCloudConf);
230
231         mAuthType = (Spinner) findViewById(R.id.spinner_authType);
232         mEncType = (Spinner) findViewById(R.id.spinner_encType);
233
234         mEasysetupProcess.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
235             @Override
236             public void onCheckedChanged(RadioGroup group, int checkedId) {
237                 mGetConfigurationInfo.setVisibility(View.GONE);
238                 mConfigureSecInfo.setVisibility(View.GONE);
239                 mProvisionDevPropInfo.setVisibility(View.GONE);
240                 mProvisionCloudPropInfo.setVisibility(View.GONE);
241
242                 switch (checkedId) {
243                     case R.id.btn_configurSec:
244                         mConfigureSecInfo.setVisibility(View.VISIBLE);
245                         break;
246
247                     case R.id.btn_getConfiguration:
248                         mGetConfigurationInfo.setVisibility(View.VISIBLE);
249                         break;
250
251                     case R.id.btn_provisionDevConf:
252                         mProvisionDevPropInfo.setVisibility(View.VISIBLE);
253                         break;
254
255                     case R.id.btn_provisionCloudConf:
256                         Log.d(TAG, "Starting login activity");
257                         Intent intent = new Intent(EasysetupActivity.this, LoginActivity.class);
258                         startActivityForResult(intent, 2);
259                         mProvisionCloudPropInfo.setVisibility(View.VISIBLE);
260                         break;
261                 }
262             }
263         });
264
265         ArrayAdapter<CharSequence> adAuthType, adEnctype;
266
267         adAuthType = ArrayAdapter.createFromResource(this, R.array.auth_type,
268                 android.R.layout.simple_spinner_item);
269         adAuthType.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
270
271         adEnctype = ArrayAdapter.createFromResource(this, R.array.enc_type,
272                 android.R.layout.simple_spinner_item);
273         adEnctype.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
274
275         mAuthType.setAdapter(adAuthType);
276         mAuthType.setSelection(0);
277
278         mEncType.setAdapter(adEnctype);
279         mEncType.setSelection(0);
280
281         addListenerForDiscoverEnrollee();
282         addListenerForStartConfigureSec();
283         addListenerForStartGetConfiguration();
284         addListenerForStartProvisionDevProp();
285         addListenerForStartProvisionCloudProp();
286
287         mSecurityMode.setClickable(false);
288         mConfigureSecProcess.setEnabled(false);
289         mGetConfigurationProcess.setEnabled(false);
290         mProvisionDevPropProcess.setEnabled(false);
291         mProvisionCloudPropProcess.setEnabled(false);
292
293         mEasySetup = EasySetup.getInstance(getApplicationContext());
294
295         initOICStack();
296
297         try {
298             m_accountManager = OcPlatform.constructAccountManagerObject(
299                     samsungCIServer,
300                     EnumSet.of(OcConnectivityType.CT_ADAPTER_TCP));
301
302             Log.e(TAG, "constructAccountManagerObject is successful");
303         } catch (OcException e) {
304             Log.e(TAG, e.toString());
305             Log.e(TAG,"Failed to constructAccountManagerObject");
306         }
307         SharedPreferences settings =
308                                 getApplicationContext().getSharedPreferences("IoTivityCloud", 0);
309         mAccessToken = settings.getString("accesstoken", null);
310         mRefreshtoken = settings.getString("refreshtoken", null);
311         mUserID = settings.getString("uid", null);
312
313         if(mRefreshtoken == null)
314         {
315             Log.d(TAG, "Can not find refresh token");
316         }
317
318         if(mAccessToken == null && mRefreshtoken == null)
319         {
320             /* Samsung account */
321             Log.d(TAG, "Starting login activity");
322
323             Intent intent = new Intent(EasysetupActivity.this, LoginActivity.class);
324             startActivityForResult(intent, 1);
325         }
326         else if(mAccessToken != null)
327         {
328             SignInDevice();
329         }
330     }
331
332     private void initOICStack() {
333         filePath = getFilesDir().getPath() + "/";
334
335         SharedPreferences wmbPreference = PreferenceManager.getDefaultSharedPreferences
336                 (getApplicationContext());
337         boolean isFirstRun = wmbPreference.getBoolean("FIRSTRUN", true);
338         if (isFirstRun) {
339             if(!copyJsonFromAsset())
340             {
341                 Log.e(TAG, "initOICStack error: " + "copyJsonFromAsset()");
342                 Toast.makeText(this,"Can't Copy DB file from asset, please retry start SampleApp.",
343                     Toast.LENGTH_LONG).show();
344                 return;
345             }
346             SharedPreferences.Editor editor = wmbPreference.edit();
347             editor.putBoolean("FIRSTRUN", false);
348             editor.commit();
349         }
350
351         cfg = new PlatformConfig(
352                 this,
353                 ServiceType.IN_PROC,
354                 ModeType.CLIENT_SERVER,
355                 "0.0.0.0", // bind to all available interfaces
356                 0,
357                 QualityOfService.LOW, filePath + OIC_CLIENT_JSON_DB_FILE);
358         try {
359             /*
360              * Initialize DataBase
361              */
362
363             OcPlatform.Configure(cfg);
364
365             String sqlDbPath = getFilesDir().getAbsolutePath().replace("files", "databases") +
366                     File.separator;
367             File file = new File(sqlDbPath);
368             //check files directory exists
369             if (!(file.isDirectory())) {
370                 file.mkdirs();
371                 Log.d(TAG, "Sql db directory created at " + sqlDbPath);
372             }
373             Log.d(TAG, "Sql db directory exists at " + sqlDbPath);
374
375             //SQLiteDatabase.openOrCreateDatabase(sqlDbPath+ OIC_SQL_DB_FILE, null);
376             OcProvisioning.provisionInit(sqlDbPath + OIC_SQL_DB_FILE);
377             mSecurityMode.setChecked(true);
378         } catch (OcException e) {
379             logMessage(TAG + "provisionInit error: " + e.getMessage());
380             Log.e(TAG, e.getMessage());
381             Toast.makeText(this,"provisionInit error: " + e.getMessage(),
382                     Toast.LENGTH_LONG).show();
383             mSecurityMode.setChecked(false);
384             return;
385         } catch (UnsatisfiedLinkError e) {
386
387             // Note : Easy setup is built with SECURED = 0, but user still selects Security feature
388             // while running the Mediator App it couldn't find "libocprovision.so".
389             // As per the programmer guide, security feature should be invoked only if build is done with SECURED = 1.
390             mSecurityMode.setChecked(false);
391             Log.e(TAG, " Easy setup is built with secured  = 0, but executed with security feature");
392             Toast.makeText(this,"Security is not enabled [Easy setup is built with SECURED = 0]",
393                     Toast.LENGTH_LONG).show();
394             return;
395         }
396     }
397
398     OcPlatform.OnResourceFoundListener listener =
399             new OcPlatform.OnResourceFoundListener() {
400                 @Override
401                 public void onFindResourceFailed(Throwable throwable, String s) {
402                     Log.e(TAG, "Failed found resource, ecode: " + s);
403                 }
404                 @Override
405                 public void onResourceFound(OcResource ocResource) {
406                     synchronized (mActivity) {
407                         if(isFirstTime){
408                             if (null == ocResource) {
409                                 Log.e(TAG, "Found resource is invalid");
410                                 return;
411                             }
412
413                             if(ocResource.getHost().contains("coap+tcp")) {
414                                 Log.d(TAG, "Recv Found resource event  from tcp port," +
415                                     "ignoring URI : " + ocResource.getUri());
416                                 runOnUiThread(new Runnable() {
417                                     @Override
418                                     public void run() {
419                                         mDiscoverResource.setEnabled(true);
420                                     }
421                                 });
422                                 return;
423                             }
424
425                             // Get the resource URI
426                             String resourceUri = ocResource.getUri();
427                             // Get the resource host address
428                             String hostAddress = ocResource.getHost();
429                             Log.d(TAG,"URI of the resource: " + resourceUri);
430                             Log.d(TAG,"Host address of the resource: " + hostAddress);
431
432                             runOnUiThread(new Runnable() {
433                                 @Override
434                                 public void run() {
435                                     mDiscoverResource.setText("Found");
436                                     if(mSecurityMode.isChecked()) {
437                                     mConfigureSecProcess.setEnabled(true);
438                                     }
439                                     mGetConfigurationProcess.setEnabled(true);
440                                     mProvisionDevPropProcess.setEnabled(true);
441                                     mProvisionCloudPropProcess.setEnabled(true);
442                                 }
443                             });
444                             isFirstTime = false;
445                             mRemoteEnrollee = mEasySetup.createRemoteEnrollee(ocResource);
446                             mEnrolleeDeviceID = ocResource.getServerId();
447                         }
448                     }
449                 }
450             };
451
452     private void addListenerForDiscoverEnrollee() {
453         mDiscoverResource.setOnClickListener(new View.OnClickListener() {
454             @Override
455             public void onClick(View v) {
456                 Thread thread = new Thread() {
457                     boolean result = true;
458                     @Override
459                     public void run() {
460                         runOnUiThread(new Runnable() {
461                             @Override
462                             public void run() {
463                                 mDiscoverResource.setEnabled(false);
464                             }
465                         });
466
467                         try {
468                             String requestUri = OcPlatform.WELL_KNOWN_QUERY + "?rt=" + ESConstants.OC_RSRVD_ES_RES_TYPE_EASYSETUP;
469                             OcPlatform.findResource("",
470                                     requestUri,
471                                     EnumSet.of(OcConnectivityType.CT_DEFAULT),
472                                     listener
473                             );
474                         }
475                         catch (OcException e) {
476                             e.printStackTrace();
477                             result = false;
478                             runOnUiThread(new Runnable() {
479                                 @Override
480                                 public void run() {
481                                     mDiscoverResource.setEnabled(true);
482                                 }
483                             });
484                         }
485                     }
486                 };
487
488                 thread.start();
489             }
490         });
491     }
492
493     private void addListenerForStartConfigureSec() {
494         mStartConfigureSec.setOnClickListener(new View.OnClickListener() {
495             @Override
496             public void onClick(View v) {
497                 Thread thread = new Thread() {
498                     @Override
499                     public void run() {
500                         runOnUiThread(new Runnable() {
501                             @Override
502                             public void run() {
503                                 mStartConfigureSec.setEnabled(false);
504                             }
505                         });
506
507                         try {
508                             mRemoteEnrollee.provisionSecurity(new SecurityProvisioningCallback() {
509                                 @Override
510                                 public void onProgress(final SecurityProvisioningStatus securityProvisioningStatus) {
511                                     if(securityProvisioningStatus.getESResult() == ESResult.ES_OK) {
512                                         runOnUiThread(new Runnable() {
513                                             @Override
514                                             public void run() {
515                                                 mSecStateText.setText("Success");
516                                                 mSecDevIDText.setText(securityProvisioningStatus.getDevUUID());
517                                             }
518                                         });
519                                     }
520                                     else if(securityProvisioningStatus.getESResult()
521                                             == ESResult.ES_SECURE_RESOURCE_DISCOVERY_FAILURE) {
522                                         runOnUiThread(new Runnable() {
523                                             @Override
524                                             public void run() {
525                                                 mSecStateText.setText("Not found Secure Resource");
526                                                 mStartConfigureSec.setEnabled(true);
527                                             }
528                                         });
529                                     }
530                                     else if(securityProvisioningStatus.getESResult()
531                                             == ESResult.ES_OWNERSHIP_TRANSFER_FAILURE) {
532                                         runOnUiThread(new Runnable() {
533                                             @Override
534                                             public void run() {
535                                                 mSecStateText.setText("Ownership transfer failed");
536                                                 mStartConfigureSec.setEnabled(true);
537                                             }
538                                         });
539                                     }
540                                     else {
541                                         runOnUiThread(new Runnable() {
542                                             @Override
543                                             public void run() {
544                                                 mSecStateText.setText("Failed");
545                                                 mStartConfigureSec.setEnabled(true);
546                                             }
547                                         });
548                                     }
549                                 }
550                             });
551                         } catch (ESException e) {
552                             e.printStackTrace();
553                             runOnUiThread(new Runnable() {
554                                 @Override
555                                 public void run() {
556                                     mStartConfigureSec.setEnabled(true);
557                                 }
558                             });
559                         }
560                     }
561                 };
562
563                 thread.start();
564             }
565         });
566     }
567
568     private void addListenerForStartGetConfiguration(){
569         mStartGetConfiguration.setOnClickListener(new View.OnClickListener() {
570             @Override
571             public void onClick(View v) {
572                 Thread thread = new Thread() {
573                     @Override
574                     public void run() {
575                         runOnUiThread(new Runnable() {
576                             @Override
577                             public void run() {
578                                 mGetconfigurationStateText.setText("Process");
579                                 mStartGetConfiguration.setEnabled(false);
580                             }
581                         });
582
583                         try {
584                             mRemoteEnrollee.getConfiguration(new GetConfigurationCallback() {
585                                 @Override
586                                 public void onProgress(GetConfigurationStatus getConfigurationStatus) {
587                                     if(getConfigurationStatus.getESResult() == ESResult.ES_OK) {
588
589                                         final SCEnrolleeConf scEnrolleeConf =
590                                         new SCEnrolleeConf(getConfigurationStatus.getEnrolleeConf());
591
592                                         runOnUiThread(new Runnable() {
593                                             @Override
594                                             public void run() {
595                                                 mGetconfigurationStateText.setText("Success");
596                                                 mDevNameText.setText(scEnrolleeConf.getDeviceName());
597                                                 mModelNumberText.setText(scEnrolleeConf.getModelNumber());
598                                                 mDevTypeText.setText(scEnrolleeConf.getDeviceType());
599                                                 mDevSubTypeText.setText(scEnrolleeConf.getDeviceSubType());
600                                                 setWifiModes(scEnrolleeConf.getWiFiModes());
601                                                 setWifiFreq(scEnrolleeConf.getWiFiFreq());
602
603                                                 if(scEnrolleeConf.isCloudAccessible()) {
604                                                     mCloudAccessableText.setText("TRUE");
605                                                 }
606                                                 else {
607                                                     mCloudAccessableText.setText("FALSE");
608                                                 }
609                                             }
610                                         });
611                                     }
612                                     else if(getConfigurationStatus.getESResult() == ESResult.ES_COMMUNICATION_ERROR)
613                                     {
614                                         runOnUiThread(new Runnable() {
615                                             @Override
616                                             public void run() {
617                                                 mGetconfigurationStateText.setText("Communication Error");
618                                                 mStartGetConfiguration.setEnabled(true);
619                                             }
620                                         });
621                                     }
622                                     else {
623                                         runOnUiThread(new Runnable() {
624                                             @Override
625                                             public void run() {
626                                                 mGetconfigurationStateText.setText("Failed");
627                                                 mStartGetConfiguration.setEnabled(true);
628                                             }
629                                         });
630                                     }
631                                 }
632                             });
633                         } catch (ESException e) {
634                             e.printStackTrace();
635                             runOnUiThread(new Runnable() {
636                                 @Override
637                                 public void run() {
638                                     mGetconfigurationStateText.setText("Failed");
639                                     mStartGetConfiguration.setEnabled(true);
640                                 }
641                             });
642                         }
643                     }
644                 };
645
646                 thread.start();
647             }
648         });
649     }
650
651     private void addListenerForStartProvisionDevProp() {
652         mStartProvisionDevProp.setOnClickListener(new View.OnClickListener() {
653             @Override
654             public void onClick(View v) {
655                 Thread thread = new Thread() {
656                     @Override
657                     public void run() {
658                         try {
659                             runOnUiThread(new Runnable() {
660                                 @Override
661                                 public void run() {
662                                     mProvisionDevPropState.setText("Progress");
663                                     mStartProvisionDevProp.setEnabled(false);
664                                 }
665                             });
666
667                             String enrollerSSID = mEnrollerSsidText.getText().toString();
668                             String enrollerPW = mEnrollerPWText.getText().toString();
669                             String discoveryChannel = mDiscoveryChannelText.getText().toString();
670                             String addr = mAddrText.getText().toString();
671                             String zipcode = mZipCodeText.getText().toString();
672                             String building = mBuildingText.getText().toString();
673                             WIFI_AUTHTYPE authType =
674                                     WIFI_AUTHTYPE.fromInt(mAuthType.getSelectedItemPosition());
675                             WIFI_ENCTYPE encType =
676                                     WIFI_ENCTYPE.fromInt(mEncType.getSelectedItemPosition());
677                             String inputLanguage = mInputLanguageText.getText().toString();
678                             String inputCountry = mInputCountryText.getText().toString();
679                             String inputLocation = mInputLocationText.getText().toString();
680
681                             ArrayList<String> locations = new ArrayList<String>();
682                             locations.add(addr);
683                             locations.add(zipcode);
684                             locations.add(building);
685
686                             SCDeviceProp scDevProp = new SCDeviceProp();
687                             scDevProp.setWiFiProp(enrollerSSID, enrollerPW, authType, encType);
688                             scDevProp.setDevConfProp(inputLanguage, inputCountry, inputLocation);
689                             scDevProp.setDiscoveryChannel(Integer.parseInt(discoveryChannel));
690                             scDevProp.setSCLocation(locations);
691
692                             mRemoteEnrollee.provisionDeviceProperties(scDevProp, new DevicePropProvisioningCallback() {
693                                 @Override
694                                 public void onProgress(DevicePropProvisioningStatus devPropProvisioningStatus) {
695                                     final ESResult result = devPropProvisioningStatus.getESResult();
696                                     runOnUiThread(new Runnable() {
697                                         @Override
698                                         public void run() {
699                                             if(result.equals(ESResult.ES_OK)) {
700                                                 mProvisionDevPropState.setText("Success");
701                                             }
702                                             else if(result.equals(ESResult.ES_ERROR)) {
703                                                 mProvisionDevPropState.setText("Failed");
704                                             }
705                                             else if(result.equals(ESResult.ES_COMMUNICATION_ERROR)) {
706                                                 mProvisionDevPropState.setText("Communication Error");
707                                             }
708                                             mStartProvisionDevProp.setEnabled(true);
709                                         }
710                                     });
711                                 }
712                             });
713                         } catch (ESException e) {
714                             e.printStackTrace();
715                             runOnUiThread(new Runnable() {
716                                 @Override
717                                 public void run() {
718                                     mProvisionDevPropState.setText("Failed");
719                                     mStartProvisionDevProp.setEnabled(true);
720                                 }
721                             });
722                         }
723                     }
724                 };
725
726                 thread.start();
727             }
728         });
729     }
730
731     private void addListenerForStartProvisionCloudProp() {
732         mStartProvisionCloudProp.setOnClickListener(new View.OnClickListener() {
733             @Override
734             public void onClick(View v) {
735                 Thread thread = new Thread() {
736                     @Override
737                     public void run() {
738                         runOnUiThread(new Runnable() {
739                             @Override
740                             public void run() {
741                                 mProvisionCloudPropState.setText("Progress");
742                                 mStartProvisionCloudProp.setEnabled(false);
743                             }
744                         });
745
746                         try {
747                             String authCode = mAuthCodeText.getText().toString();
748                             String authProvider = mAuthProviderText.getText().toString();
749                             String ciserver = samsungCIServer;
750
751                             CloudProp cloudProp = new CloudProp();
752                             cloudProp.setCloudProp(authCode, authProvider, ciserver);
753                             cloudProp.setCloudID("f002ae8b-c42c-40d3-8b8d-1927c17bd1b3");
754                             cloudProp.setCredID(1);
755
756                             mRemoteEnrollee.provisionCloudProperties(cloudProp, new CloudPropProvisioningCallback() {
757                                 @Override
758                                 public void onProgress(CloudPropProvisioningStatus cloudProvisioningStatus) {
759                                     final ESResult result = cloudProvisioningStatus.getESResult();
760                                     runOnUiThread(new Runnable() {
761                                         @Override
762                                         public void run() {
763                                             if(result.equals(ESResult.ES_ENROLLEE_DISCOVERY_FAILURE)) {
764                                                 mProvisionCloudPropState.setText("Not Found Resource");
765                                             }
766                                             else if(result.equals(ESResult.ES_OK)) {
767                                                 mProvisionCloudPropState.setText("Cloud Provisioning succeeds");
768                                             }
769                                             else if(result.equals(ESResult.ES_ACL_PROVISIONING_FAILURE)){
770                                                 mProvisionCloudPropState.setText("ACL-provisioning fails");
771                                             }
772                                             else if(result.equals(ESResult.ES_CERT_PROVISIONING_FAILURE)){
773                                                 mProvisionCloudPropState.setText("CERT-provisioning fails");
774                                             }
775                                             else if(result.equals(ESResult.ES_COMMUNICATION_ERROR)){
776                                                 mProvisionCloudPropState.setText("Communication Error");
777                                             }
778                                             else {
779                                                 mProvisionCloudPropState.setText("Cloud Provisioning fails");
780                                             }
781                                         }
782                                     });
783                                 }
784                             });
785                         } catch (ESException e) {
786                             e.printStackTrace();
787                             runOnUiThread(new Runnable() {
788                                 @Override
789                                 public void run() {
790                                     mProvisionCloudPropState.setText("Failed");
791                                     mStartProvisionCloudProp.setEnabled(true);
792                                 }
793                             });
794                         }
795                     }
796                 };
797
798                 thread.start();
799             }
800         });
801     }
802
803     private boolean copyJsonFromAsset() {
804         InputStream inputStream = null;
805         OutputStream outputStream = null;
806         int length;
807         byte[] buffer = new byte[BUFFER_SIZE];
808         try {
809             inputStream = getAssets().open(OIC_CLIENT_JSON_DB_FILE);
810             File file = new File(filePath);
811             //check files directory exists
812             if (!(file.exists() && file.isDirectory())) {
813                 file.mkdirs();
814             }
815             outputStream = new FileOutputStream(filePath + OIC_CLIENT_JSON_DB_FILE);
816             while ((length = inputStream.read(buffer)) != -1) {
817                 outputStream.write(buffer, 0, length);
818             }
819         } catch (NullPointerException e) {
820             logMessage(TAG + "Null pointer exception " + e.getMessage());
821             Log.e(TAG, e.getMessage());
822             return false;
823         } catch (FileNotFoundException e) {
824             logMessage(TAG + "Json svr db file not found " + e.getMessage());
825             Log.e(TAG, e.getMessage());
826             return false;
827         } catch (IOException e) {
828             logMessage(TAG + OIC_CLIENT_JSON_DB_FILE + " file copy failed");
829             Log.e(TAG, e.getMessage());
830             return false;
831         } finally {
832             if (inputStream != null) {
833                 try {
834                     inputStream.close();
835                 } catch (IOException e) {
836                     Log.e(TAG, e.getMessage());
837                     return false;
838                 }
839             }
840             if (outputStream != null) {
841                 try {
842                     outputStream.close();
843                 } catch (IOException e) {
844                     Log.e(TAG, e.getMessage());
845                     return false;
846                 }
847             }
848         }
849         return true;
850     }
851
852     public void logMessage(String text) {
853
854     }
855
856     public void setWifiModes(ArrayList<WIFI_MODE> types) {
857         String temp = "WIFI - ";
858
859         for(WIFI_MODE type : types) {
860             if(type.equals(WIFI_MODE.WIFI_11A)) {
861                 temp = temp + "11A ";
862             }
863             else if(type.equals(WIFI_MODE.WIFI_11B)) {
864                 temp = temp + "11B ";
865             }
866             else if(type.equals(WIFI_MODE.WIFI_11G)) {
867                 temp = temp + "11G ";
868             }
869             else if(type.equals(WIFI_MODE.WIFI_11N)) {
870                 temp = temp + "11N ";
871             }
872             else if(type.equals(WIFI_MODE.WIFI_11AC)) {
873                 temp = temp + "11AC ";
874             }
875         }
876         final String modeTypes = temp;
877         runOnUiThread(new Runnable() {
878             @Override
879             public void run() {
880                 mWifiModeText.setText(modeTypes);
881             }
882         });
883     }
884
885     public void setWifiFreq(final WIFI_FREQ freq) {
886         runOnUiThread(new Runnable() {
887             @Override
888             public void run() {
889                 if(freq.equals(WIFI_FREQ.WIFI_24G)) {
890                     mWifiFreqText.setText("2.4G");
891                 }
892                 else if(freq.equals(WIFI_FREQ.WIFI_5G)) {
893                     mWifiFreqText.setText("5G");
894                 }
895                 else if(freq.equals(WIFI_FREQ.WIFI_BOTH)) {
896                     mWifiFreqText.setText("2.4G & 5G");
897                 }
898             }
899         });
900     }
901
902     @Override
903     public void onPresence(OcPresenceStatus status, int sequence, String host) {
904         final String strStaus = status.getValue();
905         Log.d(TAG, "Presence response: " + strStaus + " sequence: " + sequence + " host: " + host);
906         runOnUiThread(new Runnable()
907         {
908             public void run() {
909                 Toast.makeText(EasysetupActivity.this, "Easy-Setup completed", Toast.LENGTH_SHORT).show();
910             }
911         });
912     }
913
914     @Override
915     protected void onActivityResult(int requestCode, int resultCode, Intent data) {
916         super.onActivityResult(requestCode, resultCode, data);
917         if(resultCode==RESULT_OK && requestCode==1){
918             mAuthCode = data.getStringExtra("authCode");
919             mAuthProvider = data.getStringExtra("authProvider");
920             String text = "Received authCode= " + mAuthCode;
921             Log.d(TAG, text);
922             SignUpDevice();
923         }
924         else if(resultCode==RESULT_OK && requestCode==2)
925         {
926             mEnrolleeAuthCode = data.getStringExtra("authCode");
927             mAuthCodeText.setText(mEnrolleeAuthCode);
928             mAuthProviderText.setText("samsung");
929             mAuthCodeText.setEnabled(false);
930             mAuthProviderText.setEnabled(false);
931             subscribeDevicePresence();
932         }
933     }
934
935     OcResource.OnPostListener onRefreshTokenPost = new OcResource.OnPostListener() {
936         @Override
937         public void onPostCompleted(List<OcHeaderOption> list, OcRepresentation ocRepresentation) {
938             Log.d(TAG, "onRefreshTokenPost..");
939             try {
940                 mAccessToken = ocRepresentation.getValue("accesstoken");
941                 mRefreshtoken = ocRepresentation.getValue("refreshtoken");
942
943                 saveCloudTokenAtSharedPreferences();
944             }
945             catch (OcException e)
946             {
947                 e.printStackTrace();
948             }
949
950             SignInDevice();
951         }
952
953         @Override
954         public void onPostFailed(Throwable throwable) {
955             Log.d(TAG, "onRefreshTokenPost failed..");
956         }
957     };
958
959     public void RefreshToken() {
960         try {
961             OcResource authResource = OcPlatform.constructResourceObject(samsungCIServer, "/.well-known/ocf/account/tokenrefresh",
962                     EnumSet.of(OcConnectivityType.CT_ADAPTER_TCP, OcConnectivityType.CT_IP_USE_V4),
963                     false, Arrays.asList("oic.wk.account"), Arrays.asList(OcPlatform.DEFAULT_INTERFACE));
964             OcRepresentation rep = new OcRepresentation();
965
966             runOnUiThread(new Runnable()
967             {
968                 public void run() {
969                     Toast.makeText(EasysetupActivity.this, "RefreshToken in progress..", Toast.LENGTH_SHORT).show();
970                 }
971             });
972
973             rep.setValue("di", deviceID);
974             rep.setValue("granttype", "refresh_token");
975             rep.setValue("refreshtoken", mRefreshtoken);
976             rep.setValue("uid", mUserID);
977             authResource.post(rep, new HashMap<String, String>(), onRefreshTokenPost);
978         }
979         catch(OcException e)
980         {
981             e.printStackTrace();
982         }
983
984         Log.d(TAG, "No error while executing login");
985     }
986
987     private void saveCloudTokenAtSharedPreferences() {
988         Log.d(TAG, "accesstoken: " + mAccessToken);
989         SharedPreferences settings = getApplicationContext().getSharedPreferences("IoTivityCloud", 0);
990         SharedPreferences.Editor editor = settings.edit();
991         editor.putString("accesstoken", mAccessToken);
992         editor.putString("refreshtoken", mRefreshtoken);
993         editor.putString("uid", mUserID);
994
995         if(editor.commit() == true)
996             Log.d(TAG, "accesstoken saved");
997         else
998             Log.d(TAG, "accesstoken not saved");
999     }
1000
1001     OcAccountManager.OnPostListener onSignUpPost = new OcAccountManager.OnPostListener() {
1002         @Override
1003         public void onPostCompleted(List<OcHeaderOption> list, OcRepresentation ocRepresentation) {
1004             Log.d(TAG, "onSignUpPost..");
1005             try {
1006                 runOnUiThread(new Runnable()
1007                 {
1008                     public void run() {
1009                         Toast.makeText(EasysetupActivity.this, "Sign-up completed", Toast.LENGTH_SHORT).show();
1010                     }
1011                 });
1012
1013                 mAccessToken = ocRepresentation.getValue("accesstoken");
1014                 mRefreshtoken = ocRepresentation.getValue("refreshtoken");
1015                 mUserID = ocRepresentation.getValue("uid");
1016
1017                 if(mAccessToken != null)
1018                 {
1019                     saveCloudTokenAtSharedPreferences();
1020                     SignInDevice();
1021                 }
1022             }
1023             catch (OcException e)
1024             {
1025                 e.printStackTrace();
1026             }
1027         }
1028
1029         @Override
1030         public void onPostFailed(Throwable throwable) {
1031             Log.d(TAG, "onSignUpPost failed.. : " + throwable.getMessage());
1032         }
1033     };
1034
1035     private void SignUpDevice() {
1036         try {
1037             Log.d(TAG, "SignUpDevice..");
1038
1039             runOnUiThread(new Runnable()
1040             {
1041                 public void run() {
1042                     Toast.makeText(EasysetupActivity.this, "SignUpDevice in progress..", Toast.LENGTH_SHORT).show();
1043                 }
1044             });
1045
1046             if(m_accountManager != null) {
1047                 m_accountManager.signUp(mAuthProvider, mAuthCode, onSignUpPost);
1048             }
1049         }
1050         catch(OcException e)
1051         {
1052             e.printStackTrace();
1053         }
1054
1055         Log.d(TAG, "No error while executing SignUp");
1056     }
1057
1058     OcAccountManager.OnPostListener onSignInPost = new OcAccountManager.OnPostListener() {
1059         @Override
1060         public void onPostCompleted(List<OcHeaderOption> list, OcRepresentation ocRepresentation) {
1061             Log.d(TAG, "onSignInPost..");
1062
1063             runOnUiThread(new Runnable()
1064             {
1065                 public void run() {
1066                     Toast.makeText(EasysetupActivity.this, "Sign-in completed", Toast.LENGTH_SHORT).show();
1067                 }
1068             });
1069         }
1070
1071         @Override
1072         public void onPostFailed(Throwable ex) {
1073             if (ex instanceof OcException) {
1074                 OcException ocEx = (OcException) ex;
1075                 ErrorCode errCode = ocEx.getErrorCode();
1076                 Log.e(TAG, ocEx.getMessage());
1077                 if (ErrorCode.UNAUTHORIZED_REQ != errCode) {
1078                     RefreshToken();
1079                 }
1080             }
1081         }
1082     };
1083
1084     private void SignInDevice() {
1085         try {
1086             Log.d(TAG, "SignInDevice..");
1087
1088             runOnUiThread(new Runnable()
1089             {
1090                 public void run() {
1091                     Toast.makeText(EasysetupActivity.this, "SignInDevice in progress..", Toast.LENGTH_SHORT).show();
1092                 }
1093             });
1094             if(m_accountManager != null) {
1095                 m_accountManager.signIn(mUserID, mAccessToken, onSignInPost);
1096             }
1097         }
1098         catch(OcException e)
1099         {
1100             e.printStackTrace();
1101         }
1102
1103         Log.d(TAG, "No error while executing login");
1104     }
1105
1106     @Override
1107     public void onObserveCompleted(List<OcHeaderOption> list, OcRepresentation ocRepresentation, int i) {
1108         Log.d(TAG,"onObserveCompleted");
1109     }
1110
1111     @Override
1112     public void onObserveFailed(Throwable throwable) {
1113         Log.d(TAG,"onObserveFailed");
1114     }
1115
1116     public void subscribeDevicePresence()
1117     {
1118         List<String> deviceIDs = new ArrayList<String>();
1119         deviceIDs.add(mEnrolleeDeviceID);
1120
1121         try {
1122
1123             OcPlatform.subscribeDevicePresence(samsungCIServer, deviceIDs, EnumSet.of(OcConnectivityType.
1124                                                CT_ADAPTER_TCP), this);
1125         } catch(OcException e)
1126         {
1127             e.printStackTrace();
1128         }
1129
1130     }
1131
1132     @Override
1133     protected void onDestroy() {
1134         super.onDestroy();
1135     }
1136 }