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