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