dbd6a187e4447f0c3ec539a61a5fcb1366e74cc1
[platform/upstream/iotivity.git] /
1 package org.iotivity.base.examples.provisioningclient;
2
3 import android.app.Activity;
4 import android.content.BroadcastReceiver;
5 import android.content.Context;
6 import android.content.Intent;
7 import android.content.SharedPreferences;
8 import android.os.AsyncTask;
9 import android.os.Bundle;
10 import android.os.Message;
11 import android.preference.PreferenceManager;
12 import android.text.method.ScrollingMovementMethod;
13 import android.util.Log;
14 import android.view.Gravity;
15 import android.widget.LinearLayout;
16 import android.widget.TextView;
17
18 import org.iotivity.base.CredType;
19 import org.iotivity.base.EncodingType;
20 import org.iotivity.base.DeviceStatus;
21 import org.iotivity.base.KeySize;
22 import org.iotivity.base.ModeType;
23 import org.iotivity.base.OcException;
24 import org.iotivity.base.OcPlatform;
25 import org.iotivity.base.OcProvisioning;
26 import org.iotivity.base.OcSecureResource;
27 import org.iotivity.base.OicSecAcl;
28 import org.iotivity.base.OicSecAce;
29 import org.iotivity.base.OicSecResr;
30 import org.iotivity.base.OicSecValidity;
31 import org.iotivity.base.OicSecPdAcl;
32 import org.iotivity.base.OcPrmType;
33 import org.iotivity.base.OxmType;
34 import org.iotivity.base.PlatformConfig;
35 import org.iotivity.base.ProvisionResult;
36 import org.iotivity.base.QualityOfService;
37 import org.iotivity.base.ServiceType;
38
39 import java.io.File;
40 import java.io.FileNotFoundException;
41 import java.io.FileOutputStream;
42 import java.io.IOException;
43 import java.io.InputStream;
44 import java.io.OutputStream;
45 import java.util.ArrayList;
46 import java.util.EnumSet;
47 import java.util.List;
48
49 public class ProvisioningClient extends Activity implements
50 OcSecureResource.DoOwnershipTransferListener, OcSecureResource.ProvisionPairwiseDevicesListener {
51
52     private static final String TAG = "Provisioning Client: ";
53     private static final int BUFFER_SIZE = 1024;
54     private int credId=0;
55     int unownedDevCount = StringConstants.NUMBER_ZERO;
56     OcProvisioning.PinCallbackListener pinCallbackListener =
57         new OcProvisioning.PinCallbackListener() {
58             @Override
59                 public String pinCallbackListener() {
60                     Log.d(TAG, "Inside Pin Callback ");
61                     return "";
62                 }
63         };
64     private String filePath = "";
65     private OcSecureResource newSecureResource;
66     private List<OcSecureResource> deviceList;
67     private List<OcSecureResource> ownedDeviceList;
68     private TextView mEventsTextView;
69
70     OcSecureResource.ProvisionDirectPairingListener provisionDPListener =
71         new OcSecureResource.ProvisionDirectPairingListener() {
72             @Override
73                 public void provisionDirectPairingListener(List<ProvisionResult> provisionResults,
74                         int hasError) {
75                     Log.d(TAG, "Inside provisionDPListener");
76                     ProvisionResult pResult = provisionResults.get(0);
77                     if (hasError == StringConstants.ERROR_CODE) {
78                         logMessage(TAG + "Provision direct pairing Failed for " + pResult.getDevId());
79                     } else {
80                         logMessage(TAG + "Provision direct pairing Successful for " + pResult.getDevId());
81                         if (ownedDeviceList.size() == 1) {
82                             new ProvisionACLAsyncTask().execute();
83                         }
84                         if (ownedDeviceList.size() > 1) {
85                             new GetLinkedDevicesAsyncTask().execute();
86                         }
87                     }
88                 }
89         };
90
91     OcSecureResource.ProvisionAclListener provisionAclListener =
92         new OcSecureResource.ProvisionAclListener() {
93             @Override
94                 public void provisionAclListener(List<ProvisionResult> provisionResults,
95                         int hasError) {
96                     Log.d(TAG, "Inside ProvisionAclListener ");
97                     if (hasError == StringConstants.ERROR_CODE) {
98                         logMessage("Error: ACL Provision failed !!");
99                     } else {
100                         logMessage("ACL Provision Done !!");
101                         provisionCertChain();
102                     }
103                 }
104         };
105     OcSecureResource.ProvisionCredentialsListener provisionCredentialsListener =
106         new OcSecureResource.ProvisionCredentialsListener() {
107             @Override
108                 public void provisionCredentialsListener(List<ProvisionResult> provisionResults,
109                         int hasError) {
110                     Log.d(TAG, "Inside ProvisionCredentialsListener ");
111                     if (hasError == StringConstants.ERROR_CODE) {
112                         logMessage("Error: Provision Credentials failed !!");
113                     } else {
114                         logMessage("Provision Credentials Done !!");
115                         new ProvisionACLAsyncTask().execute();
116                     }
117                 }
118         };
119
120     OcSecureResource.ProvisionTrustCertChainListener provisionTrustCertListener =
121         new OcSecureResource.ProvisionTrustCertChainListener() {
122             @Override
123                 public void provisionTrustCertChainListener(List<ProvisionResult> provisionResults,
124                         int hasError) {
125                     Log.d(TAG, "Inside provisionTrustCertChainListener ");
126                     if (hasError == StringConstants.ERROR_CODE) {
127                         logMessage("Error: Provision TrustCertChain failed !!");
128                     } else {
129                         logMessage("Provision TrustCertChain Done !!");
130                         new DeviceRevocationAsyncTask().execute();
131                     }
132                 }
133         };
134
135     OcSecureResource.UnlinkDevicesListener unlinkDevicesListener =
136         new OcSecureResource.UnlinkDevicesListener() {
137             @Override
138                 public void unlinkDevicesListener(List<ProvisionResult> provisionResults,
139                         int hasError) {
140                     Log.d(TAG, "Inside unlinkDevicesListener ");
141                     if (hasError == StringConstants.ERROR_CODE) {
142                         logMessage("Error: UnLinking device !!");
143                     } else {
144                         logMessage("Unlink Done !!");
145                         new ProvisionCredentialAsyncTask().execute();
146                     }
147                 }
148         };
149     OcSecureResource.RemoveDeviceListener removeDeviceListener =
150         new OcSecureResource.RemoveDeviceListener() {
151             @Override
152                 public void removeDeviceListener(List<ProvisionResult> provisionResults,
153                         int hasError) {
154                     if (hasError == StringConstants.ERROR_CODE) {
155                         logMessage("Error: Remove Fail !!");
156                     } else {
157                         logMessage("Remove Device done !!");
158                     }
159                 }
160         };
161
162     @Override
163         protected void onCreate(Bundle savedInstanceState) {
164             super.onCreate(savedInstanceState);
165             setContentView(R.layout.activity_secure_provision_client);
166             mEventsTextView = new TextView(this);
167             mEventsTextView.setGravity(Gravity.BOTTOM);
168             mEventsTextView.setMovementMethod(new ScrollingMovementMethod());
169             LinearLayout layout = (LinearLayout) findViewById(R.id.linearLayout);
170             layout.addView(mEventsTextView, new LinearLayout.LayoutParams(
171                         LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f)
172                     );
173             filePath = getFilesDir().getPath() + "/"; //  data/data/<package>/files/
174             //copy CBOR file when application runs first time
175             SharedPreferences wmbPreference = PreferenceManager.getDefaultSharedPreferences(this);
176             boolean isFirstRun = wmbPreference.getBoolean("FIRSTRUN", true);
177             if (isFirstRun) {
178                 copyCborFromAsset();
179                 SharedPreferences.Editor editor = wmbPreference.edit();
180                 editor.putBoolean("FIRSTRUN", false);
181                 editor.commit();
182             }
183             initOICStack();
184             saveCertChain();
185         }
186
187     /**
188      * configure OIC platform and call findResource
189      */
190     private void initOICStack() {
191         //create platform config
192         PlatformConfig cfg = new PlatformConfig(
193                 this,
194                 ServiceType.IN_PROC,
195                 ModeType.CLIENT_SERVER,
196                 "0.0.0.0", // bind to all available interfaces
197                 0,
198                 QualityOfService.LOW, filePath + StringConstants.OIC_CLIENT_CBOR_DB_FILE);
199         OcPlatform.Configure(cfg);
200         try {
201             /*
202              * Initialize DataBase
203              */
204             String sqlDbPath = getFilesDir().getAbsolutePath().replace("files", "databases") +
205                 File.separator;
206             File file = new File(sqlDbPath);
207             //check files directory exists
208             if (!(file.isDirectory())) {
209                 file.mkdirs();
210                 Log.d(TAG, "Sql db directory created at " + sqlDbPath);
211             }
212             Log.d(TAG, "Sql db directory exists at " + sqlDbPath);
213             OcProvisioning.provisionInit(sqlDbPath + StringConstants.OIC_SQL_DB_FILE);
214         } catch (OcException e) {
215             logMessage(TAG + "provisionInit error: " + e.getMessage());
216             Log.e(TAG, e.getMessage());
217         }
218         new DiscoveryOTTransferAsyncTask().execute();
219     }
220
221     @Override
222         synchronized public void doOwnershipTransferListener(List<ProvisionResult> ProvisionResultList,
223                 int hasError) {
224             ProvisionResult pResult = ProvisionResultList.get(0);
225             if (hasError == StringConstants.ERROR_CODE) {
226                 logMessage(TAG + "Ownership Transfer Failed for " + pResult.getDevId());
227             } else {
228                 logMessage(TAG + "Ownership Transfer Successful for "
229                         + pResult.getDevId());
230                 unownedDevCount--;
231             }
232             if (unownedDevCount == 0) { //When done with Ownership Transfer
233                 new OwnedDiscoveryAsyncTask().execute();
234             }
235         }
236
237
238     private void doDPProvisioning() {
239         try {
240             logMessage(TAG + "Provision direct pairing for " + ownedDeviceList.get(0).getDeviceID());
241             newSecureResource = ownedDeviceList.get(0);
242             String pin = "00000000";
243             List<OcPrmType> prmTypes = new ArrayList<OcPrmType>();
244             prmTypes.add(OcPrmType.DP_PRE_CONFIGURED);
245             boolean edp = true;
246             List<String> resources = new ArrayList<String>();
247             List<String> periods = new ArrayList<String>();
248             List<String> recurrences = new ArrayList<String>();
249             resources.add(StringConstants.DEFAULT_RESOURCES);
250             OicSecPdAcl pdAcl = new OicSecPdAcl(recurrences, periods,
251                     StringConstants.DEFAULT_PERMISSION, resources);
252             OicSecPdAcl[] oicSecPdAcls = new OicSecPdAcl[1];
253             oicSecPdAcls[0] = pdAcl;
254             newSecureResource.doProvisionDirectPairing(pin, oicSecPdAcls, prmTypes, edp,
255                     provisionDPListener);
256         } catch (Exception e) {
257             logMessage(TAG + "Direct Pairing Provisioning error: " + e.getMessage());
258             Log.e(TAG, e.getMessage());
259         }
260     }
261
262
263     private void doPairwiseProvisioning() {
264         try {
265             logMessage(TAG + "Pairwise Provisioning b/w " + ownedDeviceList.get(0).getDeviceID()
266                     + " and " + ownedDeviceList.get(1).getDeviceID());
267             newSecureResource = ownedDeviceList.get(0);
268
269             List<OicSecResr> resources1 = new ArrayList<OicSecResr>();
270             List<OicSecResr> resources2 = new ArrayList<OicSecResr>();
271             List<OicSecValidity> validities = new ArrayList<OicSecValidity>();
272
273             List<String> types1 = new ArrayList<String>();
274             types1.add(StringConstants.RESOURCE_TYPE_1A);
275             types1.add(StringConstants.RESOURCE_TYPE_1B);
276             List<String> types2 = new ArrayList<String>();
277             types2.add(StringConstants.RESOURCE_TYPE_2A);
278             types2.add(StringConstants.RESOURCE_TYPE_2B);
279             List<String> interfaces = new ArrayList<String>();
280             interfaces.add(StringConstants.RESOURCE_INTERFACE_1);
281             interfaces.add(StringConstants.RESOURCE_INTERFACE_2);
282
283             OicSecResr oicSecResr1a = new OicSecResr(StringConstants.HREF_RESOURCES_1A, "", types1, 2, interfaces, 2);
284             OicSecResr oicSecResr1b = new OicSecResr(StringConstants.HREF_RESOURCES_1B, "", types1, 2, interfaces, 2);
285             resources1.add(oicSecResr1a);
286             resources1.add(oicSecResr1b);
287
288             OicSecResr oicSecResr2a = new OicSecResr(StringConstants.HREF_RESOURCES_2A, "", types2, 2, interfaces, 2);
289             OicSecResr oicSecResr2b = new OicSecResr(StringConstants.HREF_RESOURCES_2B, "", types2, 2, interfaces, 2);
290             resources2.add(oicSecResr2a);
291             resources2.add(oicSecResr2b);
292
293             List<String> recurrences = new ArrayList<String>();
294             recurrences.add(StringConstants.DEFAULT_RECURRENCES_1);
295             recurrences.add(StringConstants.DEFAULT_RECURRENCES_2);
296             OicSecValidity oicSecValidity = new OicSecValidity(StringConstants.DEFAULT_PERIOD,
297                     recurrences, 2);
298             validities.add(oicSecValidity);
299
300             OicSecAce oicsecace1 = new OicSecAce(newSecureResource.getDeviceID(),
301                     StringConstants.DEFAULT_PERMISSION, resources1, validities);
302             OcSecureResource newSecureResource2 = ownedDeviceList.get(1);
303             OicSecAce oicsecace2 = new OicSecAce(newSecureResource2.getDeviceID(),
304                     StringConstants.DEFAULT_PERMISSION, resources2, validities);
305
306             List<OicSecAce> oicSecAces1=new ArrayList<OicSecAce>();
307             oicSecAces1.add(oicsecace1);
308             List<OicSecAce> oicSecAces2=new ArrayList<OicSecAce>();
309             oicSecAces2.add(oicsecace2);
310             OicSecAcl acl1 = new OicSecAcl(StringConstants.DEFAULT_ROWNER_ID,oicSecAces1);
311             OicSecAcl acl2 = new OicSecAcl(StringConstants.DEFAULT_ROWNER_ID,oicSecAces2);
312
313             newSecureResource.provisionPairwiseDevices(EnumSet.of(CredType.SYMMETRIC_PAIR_WISE_KEY),
314                     KeySize.OWNER_PSK_LENGTH_128, acl1, newSecureResource2, acl2, this);
315         } catch (Exception e) {
316             logMessage(TAG + "Pairwise Provisioning  error: " + e.getMessage());
317             Log.e(TAG, e.getMessage());
318         }
319     }
320
321     @Override
322         public void provisionPairwiseDevicesListener(List<ProvisionResult> ProvisionResultList,
323                 int hasError) {
324             if (hasError == StringConstants.ERROR_CODE) {
325                 logMessage(TAG + "provisionPairwiseDevices Failed");
326             } else {
327                 for (int i = 0; i < ProvisionResultList.size(); i++) {
328                     ProvisionResult pResult = ProvisionResultList.get(i);
329                     logMessage(TAG + "provisionPairwiseDevices Result for "
330                             + pResult.getDevId() + "is " + pResult.getResult());
331                 }
332                 doDPProvisioning();
333             }
334         }
335     /**
336      * get cert from asset folder & save trusted cert chain
337      */
338     private void saveCertChain() {
339         InputStream inputStream = null;
340         try {
341
342             inputStream = getAssets().open(StringConstants.CRT_FILE);
343             byte[] fileBytes = new byte[inputStream.available()+1];
344             inputStream.read(fileBytes);
345             fileBytes[inputStream.available()]=0x00;
346             credId = OcProvisioning.saveTrustCertChain(fileBytes,
347                     EncodingType.OIC_ENCODING_PEM);
348             logMessage(TAG + "saveTrustCertChain return credId = " + credId);
349         } catch (IOException e) {
350             logMessage(TAG + "Cert file not exist in Assets" + e.getMessage());
351             Log.e(TAG, e.getMessage());
352         } catch (OcException e) {
353             logMessage(TAG + "saveTrustCertChain failed " + e.getMessage());
354             Log.e(TAG, e.getMessage());
355         } finally {
356             if (inputStream != null) {
357                 try {
358                     inputStream.close();
359                 } catch (IOException e) {
360                     Log.e(TAG, e.getMessage());
361                 }
362             }
363
364         }
365     }
366
367     /**
368      * Provision cert chain
369      */
370     private void provisionCertChain() {
371
372         if (ownedDeviceList.size() > 0) {
373             try {
374                 OcSecureResource ocSecureResource = ownedDeviceList.get(0);
375                 logMessage(TAG + "Initiate provision cert chain credId = "
376                         + credId);
377                 ocSecureResource.provisionTrustCertChain(
378                         EnumSet.of(CredType.SIGNED_ASYMMETRIC_KEY), credId,
379                         provisionTrustCertListener);
380             } catch (OcException e) {
381                 logMessage(TAG + "Provision cert chain error: "
382                         + e.getMessage());
383                 Log.e(TAG, e.getMessage());
384             }
385         }
386
387     }
388
389     /**
390      * Copy svr db CBOR dat file from assets folder to app data files dir
391      */
392     private void copyCborFromAsset() {
393         InputStream inputStream = null;
394         OutputStream outputStream = null;
395         int length;
396         byte[] buffer = new byte[BUFFER_SIZE];
397         try {
398             inputStream = getAssets().open(StringConstants.OIC_CLIENT_CBOR_DB_FILE);
399             File file = new File(filePath);
400             //check files directory exists
401             if (!(file.exists() && file.isDirectory())) {
402                 file.mkdirs();
403             }
404             outputStream = new FileOutputStream(filePath + StringConstants.OIC_CLIENT_CBOR_DB_FILE);
405             while ((length = inputStream.read(buffer)) != -1) {
406                 outputStream.write(buffer, 0, length);
407             }
408         } catch (NullPointerException e) {
409             logMessage(TAG + "Null pointer exception " + e.getMessage());
410             Log.e(TAG, e.getMessage());
411         } catch (FileNotFoundException e) {
412             logMessage(TAG + "CBOR svr db file not found " + e.getMessage());
413             Log.e(TAG, e.getMessage());
414         } catch (IOException e) {
415             logMessage(TAG + StringConstants.OIC_CLIENT_CBOR_DB_FILE + " file copy failed");
416             Log.e(TAG, e.getMessage());
417         } finally {
418             if (inputStream != null) {
419                 try {
420                     inputStream.close();
421                 } catch (IOException e) {
422                     Log.e(TAG, e.getMessage());
423                 }
424             }
425             if (outputStream != null) {
426                 try {
427                     outputStream.close();
428                 } catch (IOException e) {
429                     Log.e(TAG, e.getMessage());
430                 }
431             }
432         }
433     }
434
435     public void logMessage(String text) {
436         logMsg(text);
437     }
438
439     public void logMsg(final String text) {
440         runOnUiThread(new Runnable() {
441                 public void run() {
442                 Message msg = new Message();
443                 msg.obj = text;
444                 mEventsTextView.append(text);
445                 mEventsTextView.append("\n\n");
446                 }
447                 });
448         Log.i(TAG, text);
449         Intent intent = new Intent(getPackageName());
450         intent.putExtra(StringConstants.MESSAGE, text);
451         sendBroadcast(intent);
452     }
453
454     private class DiscoveryOTTransferAsyncTask extends AsyncTask<Void, String, String> {
455
456         @Override
457             protected void onPreExecute() {
458                 super.onPreExecute();
459             }
460
461         @Override
462             protected String doInBackground(Void... params) {
463                 try {
464                     /**
465                      * Discover Un-owned devices
466                      */
467                     publishProgress(TAG + "Discovering Unowned Devices");
468                     deviceList = new ArrayList<OcSecureResource>(OcProvisioning.discoverUnownedDevices
469                             (StringConstants.DISCOVERY_TIMEOUT_10));
470                     if (deviceList.size() > 0) {
471                         unownedDevCount = deviceList.size();
472                         for (int i = 0; i < deviceList.size(); i++) {
473                             publishProgress(TAG + "Un-owned Discovered Device " + (i + 1) + "= " +
474                                     deviceList.get(i).getDeviceID());
475                         }
476                         try {
477                             OcProvisioning.SetownershipTransferCBdata(OxmType.OIC_JUST_WORKS,
478                                     pinCallbackListener);
479                             for (int i = 0; i < deviceList.size(); i++) {
480                                 publishProgress(TAG + "Doing Ownership Transfer for " +
481                                         deviceList.get(i).getDeviceID());
482                                 deviceList.get(i).doOwnershipTransfer(ProvisioningClient.this);
483                             }
484                         } catch (OcException e) {
485                             publishProgress(TAG + "Ownership Transfer error: " + e.getMessage());
486                             return "Ownership Transfer error: " + e.getMessage();
487
488                         }
489                     } else {
490                         publishProgress(TAG + "No un-owned devices present");
491                         new OwnedDiscoveryAsyncTask().execute();
492                     }
493                 } catch (OcException e) {
494                     publishProgress(TAG + "Un-owned discovery error: " + e.getMessage());
495                     return "Un-owned discovery error:  " + e.getMessage();
496                 }
497                 return "success";
498             }
499
500         @Override
501             protected void onProgressUpdate(String... values) {
502                 logMessage(values[0]);
503             }
504
505         @Override
506             protected void onPostExecute(String s) {
507                 super.onPostExecute(s);
508             }
509     }
510
511     private class ProvisionACLAsyncTask extends AsyncTask<Void, String, Void> {
512
513         @Override
514             protected void onPreExecute() {
515                 super.onPreExecute();
516             }
517
518         @Override
519             protected Void doInBackground(Void... params) {
520                 try {
521                     if (ownedDeviceList.size() > 0) {
522                         OcSecureResource ocSecureResource = ownedDeviceList.get(0);
523
524                         publishProgress(TAG + "ACL Provision for " + ocSecureResource.getDeviceID());
525                         List<OicSecResr> resources1 = new ArrayList<OicSecResr>();
526                         List<OicSecResr> resources2 = new ArrayList<OicSecResr>();
527                         List<OicSecValidity> validities = new ArrayList<OicSecValidity>();
528
529                         List<String> types1 = new ArrayList<String>();
530                         types1.add(StringConstants.RESOURCE_TYPE_1A);
531                         types1.add(StringConstants.RESOURCE_TYPE_1B);
532                         List<String> types2 = new ArrayList<String>();
533                         types2.add(StringConstants.RESOURCE_TYPE_2A);
534                         types2.add(StringConstants.RESOURCE_TYPE_2B);
535                         List<String> interfaces = new ArrayList<String>();
536                         interfaces.add(StringConstants.RESOURCE_INTERFACE_1);
537                         interfaces.add(StringConstants.RESOURCE_INTERFACE_2);
538
539                         OicSecResr oicSecResr1a = new OicSecResr(StringConstants.HREF_RESOURCES_1A, "", types1, 2, interfaces, 2);
540                         OicSecResr oicSecResr1b = new OicSecResr(StringConstants.HREF_RESOURCES_1B, "", types1, 2, interfaces, 2);
541                         resources1.add(oicSecResr1a);
542                         resources1.add(oicSecResr1b);
543
544                         OicSecResr oicSecResr2a = new OicSecResr(StringConstants.HREF_RESOURCES_2A, "", types2, 2, interfaces, 2);
545                         OicSecResr oicSecResr2b = new OicSecResr(StringConstants.HREF_RESOURCES_2B, "", types2, 2, interfaces, 2);
546                         resources2.add(oicSecResr2a);
547                         resources2.add(oicSecResr2b);
548
549                         List<String> recurrences = new ArrayList<String>();
550                         recurrences.add(StringConstants.DEFAULT_RECURRENCES_1);
551                         recurrences.add(StringConstants.DEFAULT_RECURRENCES_2);
552                         OicSecValidity oicSecValidity = new OicSecValidity(StringConstants.DEFAULT_PERIOD,
553                                 recurrences, 2);
554                         validities.add(oicSecValidity);
555
556                         OicSecAce oicsecace1 = new OicSecAce(StringConstants.DEFAULT_SUBJECT_ID1,
557                                 StringConstants.DEFAULT_PERMISSION, resources1, validities);
558
559                         OicSecAce oicsecace2 = new OicSecAce(StringConstants.DEFAULT_SUBJECT_ID2,
560                                 StringConstants.DEFAULT_PERMISSION, resources2, validities);
561
562                         List<OicSecAce> oicSecAces=new ArrayList<OicSecAce>();
563                         oicSecAces.add(oicsecace1);
564                         oicSecAces.add(oicsecace2);
565
566                         OicSecAcl aclObject = new OicSecAcl(StringConstants.DEFAULT_ROWNER_ID, oicSecAces);
567
568                         ocSecureResource.provisionACL(aclObject, provisionAclListener);
569                     } else {
570                         publishProgress(TAG + "No Owned devices present");
571                     }
572                 } catch (Exception e) {
573                     publishProgress(TAG + "ProvisionACL error: " + e.getMessage());
574                 }
575                 return null;
576             }
577
578         @Override
579             protected void onProgressUpdate(String... values) {
580                 logMessage(values[0]);
581             }
582     }
583
584     private class ProvisionCredentialAsyncTask extends AsyncTask<Void, String, Void> {
585
586         @Override
587             protected void onPreExecute() {
588                 super.onPreExecute();
589             }
590
591         @Override
592             protected Void doInBackground(Void... params) {
593                 try {
594                     if (ownedDeviceList.size() > 1) {
595                         OcSecureResource ocSecureResource = ownedDeviceList.get(0);
596                         OcSecureResource ocSecureResourceDest = ownedDeviceList.get(1);
597                         publishProgress(TAG + "ProvisionCredential for " +
598                                 ocSecureResource.getDeviceID() + " with " +
599                                 ocSecureResourceDest.getDeviceID());
600                         ocSecureResource.provisionCredentials(EnumSet.of(CredType.SYMMETRIC_PAIR_WISE_KEY),
601                                 KeySize.OWNER_PSK_LENGTH_128,
602                                 ocSecureResourceDest, provisionCredentialsListener);
603                     } else {
604                         publishProgress(TAG + "Cannot perform credentials between devices");
605                     }
606                 } catch (Exception e) {
607                     publishProgress(TAG + "Provision credentials error: " + e.getMessage());
608                 }
609                 return null;
610             }
611
612         @Override
613             protected void onProgressUpdate(String... values) {
614                 logMessage(values[0]);
615             }
616     }
617
618     private class GetLinkedDevicesAsyncTask extends AsyncTask<Void, String, String> {
619
620         @Override
621             protected void onPreExecute() {
622                 super.onPreExecute();
623             }
624
625         @Override
626             protected String doInBackground(Void... params) {
627                 try {
628                     if (ownedDeviceList.size() > 1) {
629                         OcSecureResource ocSecureResource = ownedDeviceList.get(0);
630                         publishProgress(TAG + "Get linked devices of " + ocSecureResource.getDeviceID());
631                         List<String> linkedDevices = ocSecureResource.getLinkedDevices();
632                         if (linkedDevices.size() > 0) {
633                             for (int i = 0; i < linkedDevices.size(); i++) {
634                                 publishProgress(TAG + "Linked Devices " +
635                                         (i + 1) + "= " + linkedDevices.get(i));
636                             }
637                         } else {
638                             publishProgress(TAG + "No linked Devices found");
639                         }
640                     } else {
641                         publishProgress(TAG + "Cannot perform linked devices");
642                     }
643                 } catch (Exception e) {
644                     publishProgress(TAG + "getLinked device error: " + e.getMessage());
645                     return "failed";
646                 }
647                 return "success";
648             }
649
650         @Override
651             protected void onProgressUpdate(String... values) {
652                 logMessage(values[0]);
653             }
654
655         @Override
656             protected void onPostExecute(String s) {
657                 if ("success".equals(s)) {
658                     new ProvisionUnlinkAsyncTask().execute();
659                 }
660             }
661     }
662
663     private class ProvisionUnlinkAsyncTask extends AsyncTask<Void, String, Void> {
664
665         @Override
666             protected void onPreExecute() {
667                 super.onPreExecute();
668             }
669
670         @Override
671             protected Void doInBackground(Void... params) {
672                 try {
673                     if (ownedDeviceList.size() > 1) {
674                         OcSecureResource ocSecureResource = ownedDeviceList.get(0);
675                         OcSecureResource ocSecureResourceDest = ownedDeviceList.get(1);
676                         publishProgress(TAG + "Un linking  " + ocSecureResource.getDeviceID() +
677                                 " with " + ocSecureResourceDest.getDeviceID());
678                         ocSecureResource.unlinkDevices(ocSecureResourceDest, unlinkDevicesListener);
679                     } else {
680                         publishProgress(TAG + "Cannot perform unlink devices");
681                     }
682                 } catch (Exception e) {
683                     publishProgress(TAG + "Unlink error: " + e.getMessage());
684                 }
685                 return null;
686             }
687
688         @Override
689             protected void onProgressUpdate(String... values) {
690                 logMessage(values[0]);
691             }
692     }
693
694     private class DeviceRevocationAsyncTask extends AsyncTask<Void, String, Void> {
695
696         @Override
697             protected void onPreExecute() {
698                 super.onPreExecute();
699             }
700
701         @Override
702             protected Void doInBackground(Void... params) {
703                 try {
704                     if (ownedDeviceList.size() > 0) {
705                         OcSecureResource ocSecureResource = ownedDeviceList.get(0);
706                         publishProgress(TAG + "Removing " + ocSecureResource.getDeviceID());
707                         ocSecureResource.removeDevice(StringConstants.DISCOVERY_TIMEOUT_20,
708                                 removeDeviceListener);
709                     } else {
710                         publishProgress(TAG + "Cannot remove");
711                     }
712                 } catch (Exception e) {
713                     publishProgress(TAG + "Remove Device error: " + e.getMessage());
714                 }
715                 return null;
716             }
717
718         @Override
719             protected void onProgressUpdate(String... values) {
720                 logMessage(values[0]);
721             }
722     }
723
724     private class OwnedDiscoveryAsyncTask extends AsyncTask<Void, String, String> {
725
726         @Override
727             protected void onPreExecute() {
728                 super.onPreExecute();
729             }
730
731         @Override
732             protected String doInBackground(Void... params) {
733                 try {
734                     publishProgress(TAG + "Initiate Owned device Discovery");
735                     ownedDeviceList = OcProvisioning.discoverOwnedDevices
736                         (StringConstants.DISCOVERY_TIMEOUT_10);
737                     if (ownedDeviceList.size() > 0) {
738                         for (int i = 0; i < ownedDeviceList.size(); i++) {
739                             publishProgress(TAG + "Owned Discovered Device " + (i + 1) + "= " +
740                                     ownedDeviceList.get(i).getDeviceID()
741                                     + "\nIP Address= " + ownedDeviceList.get(i).getIpAddr()
742                                     + "\nOwned Status= " + ownedDeviceList.get(i).getOwnedStatus()
743                                     + "\nDevice Status= " + ((ownedDeviceList.get(i).
744                                             getDeviceStatus() == DeviceStatus.ON) ? "ON" : "OFF")
745                                     );
746                         }
747                     } else {
748                         publishProgress(TAG + "No Owned devices present");
749                     }
750                 } catch (OcException e) {
751                     publishProgress(TAG + "Owned device Discovery error: " + e.getMessage());
752                     return "Owned device Discovery error: " + e.getMessage();
753                 }
754                 return "success";
755             }
756
757         @Override
758             protected void onProgressUpdate(String... values) {
759                 logMessage(values[0]);
760             }
761
762         @Override
763             protected void onPostExecute(String s) {
764
765
766                 if (ownedDeviceList.size() == 1 && "success".equals(s)) {
767                     doDPProvisioning();
768                 }
769                 if (ownedDeviceList.size() > 1 && "success".equals(s)) {
770                     doPairwiseProvisioning();
771                 }
772
773             }
774     }
775
776     /**
777      * to display on Server Message on Client screen
778      */
779     public class MessageReceiver extends BroadcastReceiver {
780         @Override
781             public void onReceive(Context context, Intent intent) {
782                 final String message = intent.getStringExtra(StringConstants.MESSAGE);
783                 logMessage(message);
784             }
785     }
786 }