replace : iotivity -> iotivity-sec
[platform/upstream/iotivity.git] / service / resource-encapsulation / examples / android / RESampleClientApp / app / src / main / java / org / iotivity / service / sample / client / ResourceClientActivity.java
1 /******************************************************************
2  * Copyright 2015 Samsung Electronics All Rights Reserved.
3  * <p>
4  * <p>
5  * <p>
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  * <p>
10  * http://www.apache.org/licenses/LICENSE-2.0
11  * <p>
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  ******************************************************************/
18 package org.iotivity.service.sample.client;
19
20 import static org.iotivity.service.client.RcsRemoteResourceObject.OnCacheUpdatedListener;
21 import static org.iotivity.service.client.RcsRemoteResourceObject.OnStateChangedListener;
22 import static org.iotivity.service.client.RcsRemoteResourceObject.ResourceState;
23
24 import java.lang.ref.WeakReference;
25
26 import org.iotivity.service.RcsException;
27 import org.iotivity.service.RcsResourceAttributes;
28 import org.iotivity.service.RcsValue;
29 import org.iotivity.service.client.RcsAddress;
30 import org.iotivity.service.client.RcsDiscoveryManager;
31 import org.iotivity.service.client.RcsDiscoveryManager.OnResourceDiscoveredListener;
32 import org.iotivity.service.client.RcsRemoteResourceObject;
33 import org.iotivity.service.client.RcsRemoteResourceObject.OnRemoteAttributesReceivedListener;
34
35 import android.app.Activity;
36 import android.app.AlertDialog;
37 import android.content.DialogInterface;
38 import android.os.Bundle;
39 import android.os.Handler;
40 import android.os.Message;
41 import android.util.Log;
42 import android.view.View;
43 import android.widget.AdapterView;
44 import android.widget.AdapterView.OnItemClickListener;
45 import android.widget.ArrayAdapter;
46 import android.widget.Button;
47 import android.widget.EditText;
48 import android.widget.ListView;
49 import android.widget.TextView;
50 import android.widget.Toast;
51
52 /*
53  * Activity for handling user's selection on UI for Resource Client APIs.
54  * & for updating UI.
55  */
56 public class ResourceClientActivity extends Activity
57         implements OnItemClickListener {
58
59     private static final String LOG_TAG = ResourceClientActivity.class
60             .getSimpleName();
61
62     private static final int MSG_ID_RESOURCE_DISCOVERED = 0;
63     private static final int MSG_ID_ATTRIBUTE_RECEIVED  = 1;
64     private static final int MSG_ID_PRINT_LOG           = 2;
65
66     private static final String RESOURCE_TYPE = "oic.r.temperature.sensor";
67     private static final String ATTR_KEY_TEMPERATURE = "Temperature";
68
69     private TextView mLogView;
70     private ListView mListView;
71     private Button   mDiscoveryBtn;
72
73     private Handler            mHandler;
74     private ArrayAdapter<Item> mItemAdapter;
75
76     private RcsDiscoveryManager.DiscoveryTask mDiscoveryTask;
77     private RcsRemoteResourceObject           mResourceObj;
78
79     private OnResourceDiscoveredListener mOnResourceDiscoveredListener = new OnResourceDiscoveredListener() {
80
81         @Override
82         public void onResourceDiscovered(
83                 RcsRemoteResourceObject foundResource) {
84             Log.i(LOG_TAG, "onResourceDiscovered");
85
86             mHandler.obtainMessage(MSG_ID_RESOURCE_DISCOVERED, foundResource)
87                     .sendToTarget();
88         }
89     };
90
91     private OnStateChangedListener mOnStateChangedListener = new OnStateChangedListener() {
92
93         @Override
94         public void onStateChanged(ResourceState resourceState) {
95             Log.i(LOG_TAG, "onStateChanged");
96
97             mHandler.obtainMessage(MSG_ID_PRINT_LOG,
98                     "Current Resource State : " + resourceState);
99         }
100     };
101
102     private OnRemoteAttributesReceivedListener mOnRemoteAttributesReceivedListener = new OnRemoteAttributesReceivedListener() {
103         @Override
104         public void onAttributesReceived(RcsResourceAttributes attrs,
105                 int eCode) {
106             Log.i(LOG_TAG, "onAttributesReceived");
107
108             mHandler.obtainMessage(MSG_ID_ATTRIBUTE_RECEIVED, attrs)
109                     .sendToTarget();
110         }
111     };
112
113     private OnCacheUpdatedListener mOnCacheUpdatedListener = new OnCacheUpdatedListener() {
114         @Override
115         public void onCacheUpdated(RcsResourceAttributes attrs, int eCode) {
116             Log.i(LOG_TAG, "onCacheUpdated");
117
118             mHandler.obtainMessage(MSG_ID_ATTRIBUTE_RECEIVED, attrs)
119                     .sendToTarget();
120         }
121     };
122
123     private Item mStartMonitoring = new Item("1. Start Monitoring") {
124         @Override
125         public void execute() throws RcsException {
126             if (mResourceObj.isMonitoring()) {
127                 printLog("Monitoring already started");
128                 return;
129             }
130
131             mResourceObj.startMonitoring(mOnStateChangedListener);
132
133             if (mResourceObj.isMonitoring()) {
134                 printLog("Monitoring started successfully");
135             }
136         }
137     };
138
139     private Item mStopMonitoring = new Item("2. Stop Monitoring") {
140         @Override
141         public void execute() throws RcsException {
142             if (mResourceObj.isMonitoring()) {
143
144                 mResourceObj.stopMonitoring();
145
146                 if (!mResourceObj.isMonitoring()) {
147                     printLog("Monitoring stopped successfully");
148                 }
149
150             } else {
151                 printLog("Monitoring not started");
152             }
153         }
154     };
155
156     private Item mGetRemoteAttributes = new Item("3. Get Remote Attributes") {
157         @Override
158         public void execute() throws RcsException {
159             mResourceObj
160                     .getRemoteAttributes(mOnRemoteAttributesReceivedListener);
161         }
162     };
163
164     private Item mSetRemoteAttributes = new Item("4. Set Remote Attributes") {
165
166         @Override
167         public void execute() throws RcsException {
168             showInputValueDialog();
169         }
170     };
171
172     private Item mStartCaching = new Item("5. Start Caching") {
173         @Override
174         public void execute() throws RcsException {
175             if (mResourceObj.isCaching()) {
176                 printLog("Caching already started");
177                 return;
178             }
179
180             mResourceObj.startCaching(mOnCacheUpdatedListener);
181
182             if (mResourceObj.isCaching()) {
183                 printLog("Caching started successfully");
184             }
185
186         }
187     };
188
189     private Item mGetCacheState = new Item("6. Get Cache State") {
190         @Override
191         public void execute() throws RcsException {
192             printLog("Cache State : " + mResourceObj.getCacheState());
193         }
194     };
195
196     private Item mGetCachedAttributes = new Item(
197             "7. Get All Cached Attributes") {
198         @Override
199         public void execute() throws RcsException {
200             printAttributes(mResourceObj.getCachedAttributes());
201         }
202     };
203
204     private Item mGetCachedAttribute = new Item("8. Get Cached Attribute") {
205         @Override
206         public void execute() throws RcsException {
207             printLog(ATTR_KEY_TEMPERATURE + " : " + mResourceObj
208                     .getCachedAttribute(ATTR_KEY_TEMPERATURE).asInt());
209         }
210     };
211
212     private Item mStopCaching = new Item("9. Stop Caching") {
213         @Override
214         public void execute() throws RcsException {
215             if (mResourceObj.isCaching()) {
216
217                 mResourceObj.stopCaching();
218
219                 if (!mResourceObj.isCaching()) {
220                     printLog("Caching stopped successfully");
221                 } else {
222                     printLog("Stopping caching unsuccessful");
223                 }
224
225             } else {
226                 printLog("Caching not started");
227             }
228         }
229
230     };
231
232     @Override
233     protected void onCreate(Bundle savedInstanceState) {
234         super.onCreate(savedInstanceState);
235         setContentView(R.layout.activity_resource_client);
236
237         mListView = (ListView) findViewById(R.id.list_menu);
238         mLogView = (TextView) findViewById(R.id.text_log);
239         mDiscoveryBtn = (Button) findViewById(R.id.btn_discovery);
240
241         mHandler = new ClientHandler(this);
242
243         initMenuList();
244     }
245
246     @Override
247     protected void onDestroy() {
248         super.onDestroy();
249
250         if (mDiscoveryTask != null) mDiscoveryTask.cancel();
251         if (mResourceObj != null) mResourceObj.destroy();
252     }
253
254     private void initMenuList() {
255         Item[] items = new Item[] { mStartMonitoring, mStopMonitoring,
256                 mGetRemoteAttributes, mSetRemoteAttributes, mStartCaching,
257                 mGetCacheState, mGetCachedAttributes, mGetCachedAttribute,
258                 mStopCaching };
259
260         mItemAdapter = new ArrayAdapter<>(this,
261                 android.R.layout.simple_list_item_1, items);
262
263         mListView.setAdapter(mItemAdapter);
264
265         mListView.setOnItemClickListener(this);
266     }
267
268     @Override
269     public void onItemClick(AdapterView<?> parent, View view, int position,
270             long id) {
271         if (mResourceObj == null) {
272             showError("no discovered RemoteResourceObject");
273             return;
274         }
275
276         try {
277             mItemAdapter.getItem(position).execute();
278         } catch (RcsException e) {
279             showError(e);
280         }
281     }
282
283     public void onDiscoverResourceClick(View v) {
284         toggleDiscovery();
285     }
286
287     private void toggleDiscovery() {
288         if (mDiscoveryTask == null) {
289             try {
290                 mDiscoveryTask = RcsDiscoveryManager.getInstance()
291                         .discoverResourceByType(RcsAddress.multicast(), RESOURCE_TYPE,
292                                 mOnResourceDiscoveredListener);
293                 mDiscoveryBtn.setText(R.string.cancel_discovery);
294
295                 mListView.setVisibility(View.INVISIBLE);
296
297                 if (mResourceObj != null) {
298                     mResourceObj.destroy();
299                     mResourceObj = null;
300                 }
301             } catch (RcsException e) {
302                 showError(e);
303             }
304         } else {
305             mDiscoveryTask.cancel();
306             mDiscoveryTask = null;
307
308             mDiscoveryBtn.setText(R.string.discover_resource);
309         }
310     }
311
312     private void printAttributes(RcsResourceAttributes attributes) {
313         try {
314             StringBuilder sb = new StringBuilder();
315             for (String key : attributes.keySet()) {
316                 sb.append(key + " : " + attributes.get(key));
317             }
318             printLog(sb.toString());
319         } catch (Exception e) {
320             printLog(e);
321         }
322     }
323
324     private void setRemoteResourceObject(
325             RcsRemoteResourceObject foundResource) {
326         if (mResourceObj != null) {
327             Log.w(LOG_TAG, "Another remote resource found...");
328             return;
329         }
330
331         mResourceObj = foundResource;
332
333         mListView.setVisibility(View.VISIBLE);
334         toggleDiscovery();
335
336         try {
337             printLog(resourceInfo(mResourceObj));
338         } catch (RcsException e) {
339             showError(e);
340         }
341     }
342
343     private void showInputValueDialog() {
344         final AlertDialog dialog = new AlertDialog.Builder(this)
345                 .setTitle("Enter the Temperature Value")
346                 .setView(R.layout.dialog_content_edit_text)
347                 .setNegativeButton("Cancel", null).create();
348
349         dialog.setButton(DialogInterface.BUTTON_POSITIVE, "OK",
350                 new DialogInterface.OnClickListener() {
351                     @Override
352                     public void onClick(DialogInterface dialogInterface,
353                             int which) {
354
355                         EditText temperatureValue = (EditText) dialog
356                                 .findViewById(R.id.attributeValue);
357
358                         try {
359                             RcsValue value = new RcsValue(Integer.parseInt(
360                                     temperatureValue.getText().toString()));
361
362                             RcsResourceAttributes attrs = new RcsResourceAttributes();
363                             attrs.put(ATTR_KEY_TEMPERATURE, value);
364
365                             mResourceObj.setRemoteAttributes(attrs,
366                                     mOnRemoteAttributesReceivedListener);
367                         } catch (NumberFormatException e) {
368                             showError("Please enter the Integer Value");
369                         } catch (RcsException e) {
370                             showError(e);
371                         }
372                     }
373                 });
374         dialog.show();
375     }
376
377     private void showError(String msg) {
378         Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
379         Log.e(LOG_TAG, msg);
380     }
381
382     private void showError(Exception e) {
383         Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
384         Log.e(LOG_TAG, e.getMessage(), e);
385     }
386
387     private void printLog(String message) {
388         Log.i(LOG_TAG, message);
389         mLogView.setText(message);
390     }
391
392     private void printLog(Exception e) {
393         Log.i(LOG_TAG, e.getMessage(), e);
394         mLogView.setText(e.getMessage());
395     }
396
397     private String resourceInfo(RcsRemoteResourceObject resourceObject)
398             throws RcsException {
399         StringBuilder sb = new StringBuilder();
400
401         sb.append("URI : " + resourceObject.getUri() + "\n");
402         sb.append("Host : " + resourceObject.getAddress() + "\n");
403         for (String type : resourceObject.getTypes()) {
404             sb.append("resourceType : " + type + "\n");
405         }
406
407         for (String itf : resourceObject.getInterfaces()) {
408             sb.append("resourceInterfaces : " + itf + "\n");
409         }
410
411         sb.append("isObservable : " + resourceObject.isObservable() + "\n");
412
413         return sb.toString();
414     }
415
416     private static abstract class Item {
417         private final String mTitle;
418
419         protected Item(String title) {
420             mTitle = title;
421         }
422
423         @Override
424         public String toString() {
425             return mTitle;
426         }
427
428         public abstract void execute() throws RcsException;
429     }
430
431     private static class ClientHandler extends Handler {
432         private WeakReference<ResourceClientActivity> mActivityRef;
433
434         private ClientHandler(ResourceClientActivity activity) {
435             mActivityRef = new WeakReference<>(activity);
436         }
437
438         @Override
439         public void handleMessage(Message msg) {
440             super.handleMessage(msg);
441
442             ResourceClientActivity activity = mActivityRef.get();
443             if (activity == null) return;
444
445             switch (msg.what) {
446                 case MSG_ID_RESOURCE_DISCOVERED:
447                     activity.setRemoteResourceObject(
448                             (RcsRemoteResourceObject) msg.obj);
449                     break;
450
451                 case MSG_ID_ATTRIBUTE_RECEIVED:
452                     activity.printAttributes((RcsResourceAttributes) msg.obj);
453                     break;
454
455                 case MSG_ID_PRINT_LOG:
456                     activity.printLog(msg.obj.toString());
457                     break;
458             }
459         }
460     }
461 }