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