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(boolean 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(boolean 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(boolean 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(boolean 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 OcCloudProvisioning.GetAclIdByDeviceListener getAclIdByDeviceListener =
240 new OcCloudProvisioning.GetAclIdByDeviceListener() {
242 public void getAclIdByDeviceListener(boolean result, String aclId) {
243 Log.d(TAG, "Inside getAclIdByDeviceListener ");
246 logMessage("Acl Id by device !!" + acl_Id);
248 logMessage("Error: Acl Id by device failed !!");
252 private OcAccountManager mAccountManager;
253 private String filePath = "";
254 private TextView mEventsTextView;
257 protected void onCreate(Bundle savedInstanceState) {
258 super.onCreate(savedInstanceState);
259 setContentView(R.layout.main_activity);
261 signUp = (Button) findViewById(R.id.signup);
262 signIn = (Button) findViewById(R.id.signin);
263 signOut = (Button) findViewById(R.id.signout);
264 getAclId = (Button) findViewById(R.id.getAclId);
265 getAclInfo = (Button) findViewById(R.id.getAclInfo);
266 requestCert = (Button) findViewById(R.id.request);
267 postCrl = (Button) findViewById(R.id.postCRL);
268 getCrl = (Button) findViewById(R.id.getCRL);
270 lyt1 = (LinearLayout) findViewById(R.id.lyt1);
271 lyt2 = (LinearLayout) findViewById(R.id.lyt2);
272 signupLyt = (LinearLayout) findViewById(R.id.signupLyt);
273 signinLyt = (LinearLayout) findViewById(R.id.signinLyt);
276 userid = (TextView) findViewById(R.id.userid);
278 mEventsTextView = (TextView) findViewById(R.id.eventView);
280 filePath = getFilesDir().getPath() + "/"; // data/data/<package>/files/
281 //copy CBOR file when application runs first time
282 settingPreference = PreferenceManager.getDefaultSharedPreferences(this);
283 boolean isFirstRun = settingPreference.getBoolean("FIRSTRUN", true);
286 SharedPreferences.Editor editor = settingPreference.edit();
287 editor.putBoolean("FIRSTRUN", false);
288 editor.putString("IP", StringConstants.DEFAULT_COAP_DERVER_IP);
289 editor.putString("PORT", StringConstants.DEFAULT_COAP_DERVER_PORT);
290 editor.putString("DEVICEID", StringConstants.DEFAULT_DEVICE_ID);
293 if (settingPreference.getString("useruuid", "").equals("")) {
295 lyt1.setVisibility(View.GONE);
296 lyt2.setVisibility(View.GONE);
297 signupLyt.setVisibility(View.VISIBLE);
298 signinLyt.setVisibility(View.GONE);
302 userid.setText(settingPreference.getString("useruuid", ""));
303 lyt1.setVisibility(View.VISIBLE);
304 lyt2.setVisibility(View.VISIBLE);
305 signupLyt.setVisibility(View.GONE);
306 signinLyt.setVisibility(View.VISIBLE);
310 ocCloudProvisioning = new OcCloudProvisioning(settingPreference.getString("IP", ""),
311 Integer.valueOf(settingPreference.getString("PORT", "")));
313 signUp.setOnClickListener(new View.OnClickListener() {
315 public void onClick(View v) {
319 signIn.setOnClickListener(new View.OnClickListener() {
321 public void onClick(View v) {
325 signOut.setOnClickListener(new View.OnClickListener() {
327 public void onClick(View v) {
331 getAclId.setOnClickListener(new View.OnClickListener() {
333 public void onClick(View v) {
337 getAclInfo.setOnClickListener(new View.OnClickListener() {
339 public void onClick(View v) {
343 requestCert.setOnClickListener(new View.OnClickListener() {
345 public void onClick(View v) {
349 postCrl.setOnClickListener(new View.OnClickListener() {
351 public void onClick(View v) {
355 getCrl.setOnClickListener(new View.OnClickListener() {
357 public void onClick(View v) {
365 public boolean onCreateOptionsMenu(Menu menu) {
366 // Inflate the menu; this adds items to the action bar if it is present.
367 getMenuInflater().inflate(R.menu.menu_cloud_provision, menu);
372 public boolean onOptionsItemSelected(MenuItem item) {
373 switch (item.getItemId()) {
374 case R.id.action_settings:
375 setDefualtSettings();
380 return (super.onOptionsItemSelected(item));
383 private void signIn() {
385 logMessage("signIn");
386 if(mAccountManager==null)
388 mAccountManager = OcPlatform.constructAccountManagerObject(
389 StringConstants.COAP_TCP + settingPreference.getString("IP",
390 StringConstants.DEFAULT_COAP_DERVER_IP) + ":" +
391 settingPreference.getString("PORT", StringConstants.DEFAULT_COAP_DERVER_PORT),
392 EnumSet.of(OcConnectivityType.CT_ADAPTER_TCP));
395 mAccountManager.signIn(settingPreference.getString("useruuid", ""),
396 settingPreference.getString("accesstoken", ""), onSignIn);
397 } catch (OcException e) {
402 private void signOut() {
404 logMessage("signOut");
405 if(mAccountManager==null)
407 mAccountManager = OcPlatform.constructAccountManagerObject(
408 StringConstants.COAP_TCP + settingPreference.getString("IP",
409 StringConstants.DEFAULT_COAP_DERVER_IP) + ":" +
410 settingPreference.getString("PORT", StringConstants.DEFAULT_COAP_DERVER_PORT),
411 EnumSet.of(OcConnectivityType.CT_ADAPTER_TCP));
414 mAccountManager.signOut(settingPreference.getString("accesstoken", ""),onSignOut);
415 } catch (OcException e) {
421 private void getAclId() {
423 logMessage("getAclId");
424 logMessage("\tdeviceId= " + settingPreference.getString("DEVICEID", ""));
425 ocCloudProvisioning.getAclIdByDevice(settingPreference.getString("DEVICEID", ""), getAclIdByDeviceListener);
426 } catch (OcException e) {
431 private void getAclInfo() {
433 logMessage("getAclInfo");
434 logMessage("\taclid="+acl_Id);
435 ocCloudProvisioning.getIndividualAclInfo(acl_Id, getIndividualAclInfoListener);
437 } catch (OcException e) {
442 private void requestCert() {
444 logMessage("requestCert");
445 ocCloudProvisioning = new OcCloudProvisioning(settingPreference.getString("IP", ""),
446 Integer.valueOf(settingPreference.getString("PORT", "")));
447 ocCloudProvisioning.requestCertificate(requestCertificateListener);
449 } catch (OcException e) {
454 private void postCrl() {
456 logMessage("postCrl");
457 ArrayList<String> arrayList = new ArrayList<>();
458 arrayList.add("1234");
460 ocCloudProvisioning.postCRL("20160727000000", "20161027000000", null, arrayList, postCRLListener);
462 } catch (OcException e) {
467 private void getCrl() {
469 logMessage("getCrl");
470 ocCloudProvisioning.getCRL(getCRLListener);
472 } catch (OcException e) {
477 private void signUp() {
479 mAccountManager = OcPlatform.constructAccountManagerObject(
480 StringConstants.COAP_TCP + settingPreference.getString("IP",
481 StringConstants.DEFAULT_COAP_DERVER_IP) + settingPreference.getString("PORT",
482 StringConstants.DEFAULT_COAP_DERVER_PORT),
483 EnumSet.of(OcConnectivityType.CT_ADAPTER_TCP));
484 logMessage(StringConstants.COAP_TCP + settingPreference.getString("IP",
485 StringConstants.DEFAULT_COAP_DERVER_IP) + settingPreference.getString("PORT",
486 StringConstants.DEFAULT_COAP_DERVER_PORT));
487 } catch (OcException e) {
491 Intent intentLogin = new Intent(this, LoginActivity.class);
492 startActivityForResult(intentLogin, REQUEST_LOGIN);
497 * configure OIC platform and call findResource
499 private void initOICStack() {
500 //create platform config
501 PlatformConfig cfg = new PlatformConfig(
504 ModeType.CLIENT_SERVER,
505 "0.0.0.0", // bind to all available interfaces
507 QualityOfService.LOW, filePath + StringConstants.OIC_CLIENT_CBOR_DB_FILE);
508 OcPlatform.Configure(cfg);
511 * Initialize DataBase
513 String sqlDbPath = getFilesDir().getAbsolutePath().replace("files", "databases") +
515 File file = new File(sqlDbPath);
516 //check files directory exists
517 if (!(file.isDirectory())) {
519 Log.d(TAG, "Sql db directory created at " + sqlDbPath);
521 Log.d(TAG, "Sql db directory exists at " + sqlDbPath);
522 OcProvisioning.provisionInit(sqlDbPath + StringConstants.OIC_SQL_DB_FILE);
523 } catch (OcException e) {
524 logMessage(TAG + "provisionInit error: " + e.getMessage());
525 Log.e(TAG, e.getMessage());
530 public void onActivityResult(int requestCode, int resultCode, Intent data) {
531 super.onActivityResult(requestCode, resultCode, data);
532 if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_LOGIN) {
533 String mAuthCode = data.getStringExtra("authCode");
536 logMessage("\tauthCode: " + mAuthCode);
539 logMessage("Sign Up");
540 mAccountManager = OcPlatform.constructAccountManagerObject(
541 StringConstants.COAP_TCP + settingPreference.getString("IP",
542 StringConstants.DEFAULT_COAP_DERVER_IP) + ":" +
543 settingPreference.getString("PORT", StringConstants.DEFAULT_COAP_DERVER_PORT),
544 EnumSet.of(OcConnectivityType.CT_ADAPTER_TCP));
546 mAccountManager.signUp("github", mAuthCode, onSignUp);
547 } catch (OcException e) {
555 * Copy svr db CBOR dat file from assets folder to app data files dir
557 private void copyCborFromAsset() {
558 InputStream inputStream = null;
559 OutputStream outputStream = null;
561 byte[] buffer = new byte[BUFFER_SIZE];
563 inputStream = getAssets().open(StringConstants.OIC_CLIENT_CBOR_DB_FILE);
564 File file = new File(filePath);
565 //check files directory exists
566 if (!(file.exists() && file.isDirectory())) {
569 outputStream = new FileOutputStream(filePath + StringConstants.OIC_CLIENT_CBOR_DB_FILE);
570 while ((length = inputStream.read(buffer)) != -1) {
571 outputStream.write(buffer, 0, length);
573 } catch (NullPointerException e) {
574 logMessage(TAG + "Null pointer exception " + e.getMessage());
575 Log.e(TAG, e.getMessage());
576 } catch (FileNotFoundException e) {
577 logMessage(TAG + "CBOR svr db file not found " + e.getMessage());
578 Log.e(TAG, e.getMessage());
579 } catch (IOException e) {
580 logMessage(TAG + StringConstants.OIC_CLIENT_CBOR_DB_FILE + " file copy failed");
581 Log.e(TAG, e.getMessage());
583 if (inputStream != null) {
586 } catch (IOException e) {
587 Log.e(TAG, e.getMessage());
590 if (outputStream != null) {
592 outputStream.close();
593 } catch (IOException e) {
594 Log.e(TAG, e.getMessage());
600 public void logMessage(String text) {
604 public void logMsg(final String text) {
605 runOnUiThread(new Runnable() {
607 Message msg = new Message();
609 mEventsTextView.append(text);
610 mEventsTextView.append("\n");
614 Intent intent = new Intent(getPackageName());
615 intent.putExtra(StringConstants.MESSAGE, text);
616 sendBroadcast(intent);
620 private void setDefualtSettings() {
621 View setingLayout = getLayoutInflater().inflate(R.layout.setting_layout, null);
623 final EditText ip = (EditText) setingLayout.findViewById(R.id.ip);
624 final EditText port = (EditText) setingLayout.findViewById(R.id.port);
625 final EditText deviceId = (EditText) setingLayout.findViewById(R.id.deviceId);
627 ip.setText(settingPreference.getString("IP", ""));
628 port.setText(settingPreference.getString("PORT", ""));
629 deviceId.setText(settingPreference.getString("DEVICEID", ""));
632 final AlertDialog.Builder builder = new AlertDialog.Builder(CloudProvisioningClient.this);
633 builder.setView(setingLayout);
634 builder.setPositiveButton("Submit", null).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
635 public void onClick(DialogInterface dialog, int id) {
636 Log.d(TAG, "AlertDialog onClick");
640 final AlertDialog alertDialog = builder.create();
641 alertDialog.setMessage("Settings");
643 alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
645 public void onClick(View v) {
647 String ip_address = ip.getText().toString();
648 String port_num = port.getText().toString();
649 String deviceId_val = deviceId.getText().toString();
651 SharedPreferences.Editor editor = settingPreference.edit();
653 editor.putString("IP", ip_address);
654 editor.putString("PORT", port_num);
655 editor.putString("DEVICEID", deviceId_val);
658 alertDialog.cancel();
661 alertDialog.getButton(AlertDialog.BUTTON_NEGATIVE).setOnClickListener(new View.OnClickListener() {
663 public void onClick(View v) {
665 alertDialog.cancel();
672 public void onPostCompleted(List<OcHeaderOption> ocHeaderOptions, OcRepresentation ocRepresentation) {
677 public void onPostFailed(Throwable throwable) {
683 * to display on Server Message on Client screen
685 public class MessageReceiver extends BroadcastReceiver {
687 public void onReceive(Context context, Intent intent) {
688 final String message = intent.getStringExtra(StringConstants.MESSAGE);