2 * ******************************************************************
4 * Copyright 2016 Samsung Electronics All Rights Reserved.
6 * -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
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
12 * http://www.apache.org/licenses/LICENSE-2.0
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.
20 * -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
22 package org.iotivity.base.examples.cloudprovisioningclient;
24 import android.app.Activity;
25 import android.app.AlertDialog;
26 import android.content.BroadcastReceiver;
27 import android.content.Context;
28 import android.content.DialogInterface;
29 import android.content.Intent;
30 import android.content.SharedPreferences;
31 import android.os.Bundle;
32 import android.os.Message;
33 import android.preference.PreferenceManager;
34 import android.util.Log;
35 import android.view.Menu;
36 import android.view.MenuItem;
37 import android.view.View;
38 import android.widget.Button;
39 import android.widget.EditText;
40 import android.widget.LinearLayout;
41 import android.widget.TextView;
43 import org.iotivity.base.ErrorCode;
44 import org.iotivity.base.ModeType;
45 import org.iotivity.base.OcAccountManager;
46 import org.iotivity.base.OcCloudProvisioning;
47 import org.iotivity.base.OcConnectivityType;
48 import org.iotivity.base.OcException;
49 import org.iotivity.base.OcHeaderOption;
50 import org.iotivity.base.OcPlatform;
51 import org.iotivity.base.OcProvisioning;
52 import org.iotivity.base.OcRepresentation;
53 import org.iotivity.base.PlatformConfig;
54 import org.iotivity.base.QualityOfService;
55 import org.iotivity.base.ServiceType;
56 import org.iotivity.base.examples.cloudprovisioningclient.R;
59 import java.io.FileNotFoundException;
60 import java.io.FileOutputStream;
61 import java.io.IOException;
62 import java.io.InputStream;
63 import java.io.OutputStream;
64 import java.util.ArrayList;
65 import java.util.EnumSet;
66 import java.util.List;
68 public class CloudProvisioningClient extends Activity implements OcAccountManager.OnPostListener {
70 private static final String TAG = "Cloud Provisioning Client: ";
71 OcAccountManager.OnPostListener onSignUp = new OcAccountManager.OnPostListener() {
73 public synchronized void onPostCompleted(List<OcHeaderOption> list,
74 OcRepresentation ocRepresentation) {
75 logMessage("signUp was successful");
77 String mUserUuid = ocRepresentation.getValue("uid");
78 String mAccesstoken = ocRepresentation.getValue("accesstoken");
80 String mRefreshtoken = ocRepresentation.getValue("refreshtoken");
81 String tokenType = ocRepresentation.getValue("tokentype");
83 SharedPreferences.Editor editor = settingPreference.edit();
84 editor.putString("useruuid", mUserUuid);
85 editor.putString("accesstoken", mAccesstoken);
88 logMessage("\tuserID: " + mUserUuid);
89 logMessage("\taccessToken: " + mAccesstoken);
90 logMessage("\trefreshToken: " + mRefreshtoken);
91 logMessage("\ttokenType: " + tokenType);
93 if (ocRepresentation.hasAttribute("expiresin")) {
94 int expiresIn = ocRepresentation.getValue("expiresin");
95 logMessage("\texpiresIn: " + expiresIn);
98 runOnUiThread(new Runnable() {
101 signupLyt.setVisibility(View.GONE);
102 signinLyt.setVisibility(View.VISIBLE);
107 } catch (OcException e) {
108 Log.e(TAG, e.toString());
114 public synchronized void onPostFailed(Throwable throwable) {
115 logMessage("Failed to signUp");
116 if (throwable instanceof OcException) {
117 OcException ocEx = (OcException) throwable;
118 Log.e(TAG, ocEx.toString());
119 ErrorCode errCode = ocEx.getErrorCode();
120 logMessage("Error code: " + errCode);
124 OcAccountManager.OnPostListener onSignIn = new OcAccountManager.OnPostListener() {
126 public synchronized void onPostCompleted(List<OcHeaderOption> list,
127 OcRepresentation ocRepresentation) {
128 logMessage("signIn was successful");
129 runOnUiThread(new Runnable() {
132 signinLyt.setVisibility(View.GONE);
133 userid.setText(settingPreference.getString("useruuid", ""));
134 lyt1.setVisibility(View.VISIBLE);
135 lyt2.setVisibility(View.VISIBLE);
143 public synchronized void onPostFailed(Throwable throwable) {
144 logMessage("Failed to signIn");
145 if (throwable instanceof OcException) {
146 OcException ocEx = (OcException) throwable;
147 Log.e(TAG, ocEx.toString());
148 ErrorCode errCode = ocEx.getErrorCode();
149 logMessage("Error code: " + errCode);
154 OcAccountManager.OnPostListener onSignOut = new OcAccountManager.OnPostListener() {
156 public synchronized void onPostCompleted(List<OcHeaderOption> list,
157 OcRepresentation ocRepresentation) {
158 logMessage("signOut was successful");
159 runOnUiThread(new Runnable() {
162 lyt1.setVisibility(View.GONE);
163 lyt2.setVisibility(View.GONE);
164 signinLyt.setVisibility(View.VISIBLE);
171 public synchronized void onPostFailed(Throwable throwable) {
172 logMessage("Failed to signOut");
173 if (throwable instanceof OcException) {
174 OcException ocEx = (OcException) throwable;
175 Log.e(TAG, ocEx.toString());
176 ErrorCode errCode = ocEx.getErrorCode();
177 logMessage("Error code: " + errCode);
182 OcCloudProvisioning.GetIndividualAclInfoListener getIndividualAclInfoListener =
183 new OcCloudProvisioning.GetIndividualAclInfoListener() {
185 public void getIndividualAclInfoListener(int result) {
186 Log.d(TAG, "Inside getIndividualAclInfoListener ");
188 logMessage("Individual ACL Info Successfull !!");
190 logMessage("Error: Individual ACL Info failed !!");
194 OcCloudProvisioning.RequestCertificateListener requestCertificateListener =
195 new OcCloudProvisioning.RequestCertificateListener() {
197 public void requestCertificateListener(int result) {
198 Log.d(TAG, "Inside requestCertificateListener ");
200 logMessage("Request certificate Successfull !!");
202 logMessage("Error: Request certificate failed !!");
206 OcCloudProvisioning.GetCRLListener getCRLListener =
207 new OcCloudProvisioning.GetCRLListener() {
209 public void getCRLListener(int result) {
210 Log.d(TAG, "Inside getCRLListener ");
212 logMessage("Get CRL Successfull !!");
214 logMessage("Error: Get CRL failed !!");
218 OcCloudProvisioning.PostCRLListener postCRLListener =
219 new OcCloudProvisioning.PostCRLListener() {
221 public void postCRLListener(int result) {
222 Log.d(TAG, "Inside postCRLListener ");
224 logMessage("Post CRL Successfull !!");
226 logMessage("Error: Post CRL failed !!");
230 private static final int BUFFER_SIZE = 1024;
231 private final int REQUEST_LOGIN = 1;
232 Button signUp, signIn, signOut, getAclId, getAclInfo, requestCert, postCrl, getCrl;
234 LinearLayout lyt1, lyt2, signupLyt, signinLyt;
235 // private TextView eventView;
236 SharedPreferences settingPreference;
237 OcCloudProvisioning ocCloudProvisioning;
239 String createacl_Id = null;
240 OcCloudProvisioning.GetAclIdByDeviceListener getAclIdByDeviceListener =
241 new OcCloudProvisioning.GetAclIdByDeviceListener() {
243 public void getAclIdByDeviceListener(int result, String aclId) {
244 Log.d(TAG, "Inside getAclIdByDeviceListener ");
247 logMessage("Acl Id by device !!" + acl_Id);
249 logMessage("Error: Acl Id by device failed !!");
254 OcCloudProvisioning.CreateAclIdListener createAclIdListener =
255 new OcCloudProvisioning.CreateAclIdListener() {
257 public void createAclIdListener(int result, String aclId) {
258 Log.d(TAG, "Inside createAclIdListener ");
260 createacl_Id = aclId;
261 logMessage("Acl Id by create aclid !!" + createacl_Id);
263 logMessage("Error: Acl Id by create aclid failed !!");
267 private OcAccountManager mAccountManager;
268 private String filePath = "";
269 private TextView mEventsTextView;
272 protected void onCreate(Bundle savedInstanceState) {
273 super.onCreate(savedInstanceState);
274 setContentView(R.layout.main_activity);
276 signUp = (Button) findViewById(R.id.signup);
277 signIn = (Button) findViewById(R.id.signin);
278 signOut = (Button) findViewById(R.id.signout);
279 getAclId = (Button) findViewById(R.id.getAclId);
280 getAclInfo = (Button) findViewById(R.id.getAclInfo);
281 requestCert = (Button) findViewById(R.id.request);
282 postCrl = (Button) findViewById(R.id.postCRL);
283 getCrl = (Button) findViewById(R.id.getCRL);
285 lyt1 = (LinearLayout) findViewById(R.id.lyt1);
286 lyt2 = (LinearLayout) findViewById(R.id.lyt2);
287 signupLyt = (LinearLayout) findViewById(R.id.signupLyt);
288 signinLyt = (LinearLayout) findViewById(R.id.signinLyt);
291 userid = (TextView) findViewById(R.id.userid);
293 mEventsTextView = (TextView) findViewById(R.id.eventView);
295 filePath = getFilesDir().getPath() + "/"; // data/data/<package>/files/
296 //copy CBOR file when application runs first time
297 settingPreference = PreferenceManager.getDefaultSharedPreferences(this);
298 boolean isFirstRun = settingPreference.getBoolean("FIRSTRUN", true);
301 SharedPreferences.Editor editor = settingPreference.edit();
302 editor.putBoolean("FIRSTRUN", false);
303 editor.putString("IP", StringConstants.DEFAULT_COAP_DERVER_IP);
304 editor.putString("PORT", StringConstants.DEFAULT_COAP_DERVER_PORT);
305 editor.putString("DEVICEID", StringConstants.DEFAULT_DEVICE_ID);
306 editor.putString("OWNERID", StringConstants.DEFAULT_OWNER_ID);
307 editor.putString("SERIALNUMBER", StringConstants.DEFAULT_SERIAL_NUMBER);
310 if (settingPreference.getString("useruuid", "").equals("")) {
312 lyt1.setVisibility(View.GONE);
313 lyt2.setVisibility(View.GONE);
314 signupLyt.setVisibility(View.VISIBLE);
315 signinLyt.setVisibility(View.GONE);
319 userid.setText(settingPreference.getString("useruuid", ""));
320 lyt1.setVisibility(View.VISIBLE);
321 lyt2.setVisibility(View.VISIBLE);
322 signupLyt.setVisibility(View.GONE);
323 signinLyt.setVisibility(View.VISIBLE);
327 ocCloudProvisioning = new OcCloudProvisioning(settingPreference.getString("IP", ""),
328 Integer.valueOf(settingPreference.getString("PORT", "")));
330 signUp.setOnClickListener(new View.OnClickListener() {
332 public void onClick(View v) {
336 signIn.setOnClickListener(new View.OnClickListener() {
338 public void onClick(View v) {
342 signOut.setOnClickListener(new View.OnClickListener() {
344 public void onClick(View v) {
348 getAclId.setOnClickListener(new View.OnClickListener() {
350 public void onClick(View v) {
354 getAclInfo.setOnClickListener(new View.OnClickListener() {
356 public void onClick(View v) {
360 requestCert.setOnClickListener(new View.OnClickListener() {
362 public void onClick(View v) {
366 postCrl.setOnClickListener(new View.OnClickListener() {
368 public void onClick(View v) {
372 getCrl.setOnClickListener(new View.OnClickListener() {
374 public void onClick(View v) {
382 public boolean onCreateOptionsMenu(Menu menu) {
383 // Inflate the menu; this adds items to the action bar if it is present.
384 getMenuInflater().inflate(R.menu.menu_cloud_provision, menu);
389 public boolean onOptionsItemSelected(MenuItem item) {
390 switch (item.getItemId()) {
391 case R.id.action_settings:
392 setDefualtSettings();
397 return (super.onOptionsItemSelected(item));
400 private void signIn() {
402 logMessage("signIn");
403 if(mAccountManager==null)
405 mAccountManager = OcPlatform.constructAccountManagerObject(
406 StringConstants.COAP_TCP + settingPreference.getString("IP",
407 StringConstants.DEFAULT_COAP_DERVER_IP) + ":" +
408 settingPreference.getString("PORT", StringConstants.DEFAULT_COAP_DERVER_PORT),
409 EnumSet.of(OcConnectivityType.CT_ADAPTER_TCP));
412 mAccountManager.signIn(settingPreference.getString("useruuid", ""),
413 settingPreference.getString("accesstoken", ""), onSignIn);
414 } catch (OcException e) {
419 private void signOut() {
421 logMessage("signOut");
422 if(mAccountManager==null)
424 logMessage("Please signIn first");
428 mAccountManager.signOut(settingPreference.getString("accesstoken", ""),onSignOut);
429 } catch (OcException e) {
435 private void getAclId() {
437 if(createacl_Id == null)
439 ocCloudProvisioning.createAclId(settingPreference.getString("OWNERID", ""),
440 settingPreference.getString("DEVICEID", ""), createAclIdListener);
443 ocCloudProvisioning.getAclIdByDevice(settingPreference.getString("DEVICEID", ""),
444 getAclIdByDeviceListener);
446 } catch (OcException e) {
451 private void getAclInfo() {
453 logMessage("getAclInfo");
454 logMessage("\taclid="+acl_Id);
455 ocCloudProvisioning.getIndividualAclInfo(acl_Id, getIndividualAclInfoListener);
457 } catch (OcException e) {
462 private void requestCert() {
464 logMessage("requestCert");
465 ocCloudProvisioning = new OcCloudProvisioning(settingPreference.getString("IP", ""),
466 Integer.valueOf(settingPreference.getString("PORT", "")));
467 ocCloudProvisioning.requestCertificate(requestCertificateListener);
469 } catch (OcException e) {
474 private void postCrl() {
476 logMessage("postCrl");
477 ArrayList<String> arrayList = new ArrayList<>();
478 arrayList.add(settingPreference.getString("SERIALNUMBER", "1234"));
480 ocCloudProvisioning.postCRL("20160727000000", "20161027000000", null, arrayList, postCRLListener);
482 } catch (OcException e) {
487 private void getCrl() {
489 logMessage("getCrl");
490 ocCloudProvisioning.getCRL(getCRLListener);
492 } catch (OcException e) {
497 private void signUp() {
499 mAccountManager = OcPlatform.constructAccountManagerObject(
500 StringConstants.COAP_TCP + settingPreference.getString("IP",
501 StringConstants.DEFAULT_COAP_DERVER_IP) + settingPreference.getString("PORT",
502 StringConstants.DEFAULT_COAP_DERVER_PORT),
503 EnumSet.of(OcConnectivityType.CT_ADAPTER_TCP));
504 logMessage(StringConstants.COAP_TCP + settingPreference.getString("IP",
505 StringConstants.DEFAULT_COAP_DERVER_IP) + settingPreference.getString("PORT",
506 StringConstants.DEFAULT_COAP_DERVER_PORT));
507 } catch (OcException e) {
511 Intent intentLogin = new Intent(this, LoginActivity.class);
512 startActivityForResult(intentLogin, REQUEST_LOGIN);
517 * configure OIC platform and call findResource
519 private void initOICStack() {
520 //create platform config
521 PlatformConfig cfg = new PlatformConfig(
524 ModeType.CLIENT_SERVER,
525 "0.0.0.0", // bind to all available interfaces
527 QualityOfService.LOW, filePath + StringConstants.OIC_CLIENT_CBOR_DB_FILE);
528 OcPlatform.Configure(cfg);
531 * Initialize DataBase
533 String sqlDbPath = getFilesDir().getAbsolutePath().replace("files", "databases") +
535 File file = new File(sqlDbPath);
536 //check files directory exists
537 if (!(file.isDirectory())) {
539 Log.d(TAG, "Sql db directory created at " + sqlDbPath);
541 Log.d(TAG, "Sql db directory exists at " + sqlDbPath);
542 OcProvisioning.provisionInit(sqlDbPath + StringConstants.OIC_SQL_DB_FILE);
543 } catch (OcException e) {
544 logMessage(TAG + "provisionInit error: " + e.getMessage());
545 Log.e(TAG, e.getMessage());
550 public void onActivityResult(int requestCode, int resultCode, Intent data) {
551 super.onActivityResult(requestCode, resultCode, data);
552 if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_LOGIN) {
553 String mAuthCode = data.getStringExtra("authCode");
556 logMessage("\tauthCode: " + mAuthCode);
559 logMessage("Sign Up");
560 mAccountManager = OcPlatform.constructAccountManagerObject(
561 StringConstants.COAP_TCP + settingPreference.getString("IP",
562 StringConstants.DEFAULT_COAP_DERVER_IP) + ":" +
563 settingPreference.getString("PORT", StringConstants.DEFAULT_COAP_DERVER_PORT),
564 EnumSet.of(OcConnectivityType.CT_ADAPTER_TCP));
566 mAccountManager.signUp("github", mAuthCode, onSignUp);
567 } catch (OcException e) {
575 * Copy svr db CBOR dat file from assets folder to app data files dir
577 private void copyCborFromAsset() {
578 InputStream inputStream = null;
579 OutputStream outputStream = null;
581 byte[] buffer = new byte[BUFFER_SIZE];
583 inputStream = getAssets().open(StringConstants.OIC_CLIENT_CBOR_DB_FILE);
584 File file = new File(filePath);
585 //check files directory exists
586 if (!(file.exists() && file.isDirectory())) {
589 outputStream = new FileOutputStream(filePath + StringConstants.OIC_CLIENT_CBOR_DB_FILE);
590 while ((length = inputStream.read(buffer)) != -1) {
591 outputStream.write(buffer, 0, length);
593 } catch (NullPointerException e) {
594 logMessage(TAG + "Null pointer exception " + e.getMessage());
595 Log.e(TAG, e.getMessage());
596 } catch (FileNotFoundException e) {
597 logMessage(TAG + "CBOR svr db file not found " + e.getMessage());
598 Log.e(TAG, e.getMessage());
599 } catch (IOException e) {
600 logMessage(TAG + StringConstants.OIC_CLIENT_CBOR_DB_FILE + " file copy failed");
601 Log.e(TAG, e.getMessage());
603 if (inputStream != null) {
606 } catch (IOException e) {
607 Log.e(TAG, e.getMessage());
610 if (outputStream != null) {
612 outputStream.close();
613 } catch (IOException e) {
614 Log.e(TAG, e.getMessage());
620 public void logMessage(String text) {
624 public void logMsg(final String text) {
625 runOnUiThread(new Runnable() {
627 Message msg = new Message();
629 mEventsTextView.append(text);
630 mEventsTextView.append("\n");
634 Intent intent = new Intent(getPackageName());
635 intent.putExtra(StringConstants.MESSAGE, text);
636 sendBroadcast(intent);
640 private void setDefualtSettings() {
641 View setingLayout = getLayoutInflater().inflate(R.layout.setting_layout, null);
643 final EditText ip = (EditText) setingLayout.findViewById(R.id.ip);
644 final EditText port = (EditText) setingLayout.findViewById(R.id.port);
645 final EditText deviceId = (EditText) setingLayout.findViewById(R.id.deviceId);
646 final EditText serialNum = (EditText) setingLayout.findViewById(R.id.serialNum);
648 ip.setText(settingPreference.getString("IP", ""));
649 port.setText(settingPreference.getString("PORT", ""));
650 deviceId.setText(settingPreference.getString("DEVICEID", ""));
651 serialNum.setText(settingPreference.getString("SERIALNUMBER", "1234"));
654 final AlertDialog.Builder builder = new AlertDialog.Builder(CloudProvisioningClient.this);
655 builder.setView(setingLayout);
656 builder.setPositiveButton("Submit", null).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
657 public void onClick(DialogInterface dialog, int id) {
658 Log.d(TAG, "AlertDialog onClick");
662 final AlertDialog alertDialog = builder.create();
663 alertDialog.setMessage("Settings");
665 alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
667 public void onClick(View v) {
669 String ip_address = ip.getText().toString();
670 String port_num = port.getText().toString();
671 String deviceId_val = deviceId.getText().toString();
672 String serialNum_val = serialNum.getText().toString();
674 SharedPreferences.Editor editor = settingPreference.edit();
676 editor.putString("IP", ip_address);
677 editor.putString("PORT", port_num);
678 editor.putString("DEVICEID", deviceId_val);
679 editor.putString("SERIALNUMBER", serialNum_val);
682 alertDialog.cancel();
685 alertDialog.getButton(AlertDialog.BUTTON_NEGATIVE).setOnClickListener(new View.OnClickListener() {
687 public void onClick(View v) {
689 alertDialog.cancel();
696 public void onPostCompleted(List<OcHeaderOption> ocHeaderOptions, OcRepresentation ocRepresentation) {
701 public void onPostFailed(Throwable throwable) {
707 * to display on Server Message on Client screen
709 public class MessageReceiver extends BroadcastReceiver {
711 public void onReceive(Context context, Intent intent) {
712 final String message = intent.getStringExtra(StringConstants.MESSAGE);