Imported Upstream version 1.1.0
[platform/upstream/iotivity.git] / service / resource-container / examples / android / RCSampleServerApp / app / src / main / java / org / iotivity / service / sample / container / ResourceContainerActivity.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
19 package org.iotivity.service.sample.container;
20
21 import android.app.Activity;
22 import android.app.AlertDialog;
23 import android.content.Context;
24 import android.content.DialogInterface;
25 import android.content.res.AssetManager;
26 import android.graphics.Typeface;
27 import android.net.ConnectivityManager;
28 import android.os.Bundle;
29 import android.os.Handler;
30 import android.os.Message;
31 import android.util.Log;
32 import android.view.LayoutInflater;
33 import android.view.View;
34 import android.view.View.OnClickListener;
35 import android.view.ViewGroup;
36 import android.widget.BaseExpandableListAdapter;
37 import android.widget.Button;
38 import android.widget.EditText;
39 import android.widget.ExpandableListAdapter;
40 import android.widget.ExpandableListView;
41 import android.widget.TextView;
42 import android.widget.Toast;
43
44 import org.iotivity.base.ModeType;
45 import org.iotivity.base.OcPlatform;
46 import org.iotivity.base.PlatformConfig;
47 import org.iotivity.base.QualityOfService;
48 import org.iotivity.base.ServiceType;
49
50 import java.io.FileOutputStream;
51 import java.io.IOException;
52 import java.io.InputStream;
53 import java.io.OutputStream;
54 import java.util.ArrayList;
55 import java.util.HashMap;
56 import java.util.List;
57
58 /**
59  * Activity for handling user's selection on UI for Resource container APIs. &
60  * for updating UI.
61  */
62 public class ResourceContainerActivity extends Activity {
63
64     private final String                     LOG_TAG = "[RCSampleServerApp] "
65             + this.getClass()
66             .getSimpleName();
67     private static ResourceContainerActivity resourceContainerActivityInstance;
68     private ResourceContainer                resourceContainerInstance;
69     private static String                    logMessage;
70
71     private Context                          context;
72     public ExpandableListAdapter             listAdapter;
73     public ExpandableListView                expListView;
74     private int lastExpandedPosition = -1;
75
76     public List<String>                      sensors;
77     public List<String>                      diApiList;
78     public List<String>                      bmiApiList;
79     public List<String>                      diAndroidApiList;
80     HashMap<String, List<String>>            listChild;
81
82     private static Handler                   mHandler;
83     private Button                           startContainer;
84     private Button                           listBundles;
85     private static EditText                  logs;
86     private static String                    sdCardPath;
87
88     public static void setMessageLog(String message) {
89         logMessage = message;
90     }
91
92     public static ResourceContainerActivity getResourceContainerActivityObj() {
93         return resourceContainerActivityInstance;
94     }
95
96     @Override
97     protected void onCreate(Bundle savedInstanceState) {
98
99         super.onCreate(savedInstanceState);
100         context = this;
101
102         /*if (!isWifiConnected()) {
103             showWifiUnavailableDialog();
104             return;
105         }*/
106
107         configurePlatform();
108         CopyAssetsToSDCard();
109
110         setContentView(R.layout.resource_container);
111         resourceContainerActivityInstance = this;
112
113         resourceContainerInstance = new ResourceContainer();
114
115         expListView = (ExpandableListView) findViewById(R.id.lvExp);
116         startContainer = (Button) findViewById(R.id.startContainer);
117         listBundles = (Button) findViewById(R.id.listBundles);
118         listBundles.setEnabled(false);
119         logs = (EditText) findViewById(R.id.log);
120
121         sensors = new ArrayList<String>();
122         bmiApiList = new ArrayList<String>();
123         diApiList = new ArrayList<String>();
124         diAndroidApiList = new ArrayList<String>();
125         listChild = new HashMap<String, List<String>>();
126
127         // Adding list items (header)
128         sensors.add("BMI Sensor");
129         sensors.add("Discomfort Index Sensor");
130         sensors.add("Android Discomfort Index Sensor");
131
132         // Adding child data [BMI sensor]
133         bmiApiList.add("1. Add BMI sensor bundle");
134         bmiApiList.add("2. Start BMI sensor bundle");
135         bmiApiList.add("3. List bundle resources");
136         bmiApiList.add("4. Stop BMI sensor bundle");
137         bmiApiList.add("5. Remove BMI sensor bundle");
138
139         // Adding child data [discomfort Index sensor]
140         diApiList.add("1. Add DI sensor bundle");
141         diApiList.add("2. Start DI sensor bundle");
142         diApiList.add("3. List bundle resources");
143         diApiList.add("4. Stop DI sensor bundle");
144         diApiList.add("5. Remove DI sensor bundle");
145
146         // Adding child data [discomfort Index sensor - android]
147         diAndroidApiList.add("1. Add Android DI sensor bundle");
148         diAndroidApiList.add("2. Start Android DI sensor bundle");
149         diAndroidApiList.add("3. List bundle resources");
150         diAndroidApiList.add("4. Stop Android DI sensor bundle");
151         diAndroidApiList.add("5. Remove Android DI sensor bundle");
152
153         listChild.put(sensors.get(0), bmiApiList);
154         listChild.put(sensors.get(1), diApiList);
155         listChild.put(sensors.get(2), diAndroidApiList);
156         listAdapter = new ExpandableList(this, sensors, listChild);
157
158         // getting the sd card path
159         sdCardPath = this.getFilesDir().getPath();
160
161         // handler for updating the UI i.e. MessageLog (TextBox) & ListView
162         mHandler = new Handler() {
163             @Override
164             public void handleMessage(Message msg) {
165                 switch (msg.what) {
166                     case 0:
167                         expListView.setAdapter(listAdapter);
168                         expListView.bringToFront();
169                         break;
170                     case 1:
171                         logs.setText("");
172                         logs.setText(logMessage);
173                         Log.i(LOG_TAG, logMessage);
174                         break;
175                     case 2:
176                         listAdapter = null;
177                         expListView.setAdapter(listAdapter);
178                         break;
179                 }
180             }
181         };
182         setHandler(mHandler);
183
184         // StartContainer/stopContainer Button Listener
185         startContainer.setOnClickListener(new OnClickListener() {
186             @Override
187             public void onClick(View v) {
188
189                 String text = (String) startContainer.getText();
190                 if (text.contains("Start")) {
191                     resourceContainerInstance.startContainer(sdCardPath);
192                     listAdapter = new ExpandableList(ResourceContainerActivity
193                             .getResourceContainerActivityObj(), sensors,
194                             listChild);
195                     listBundles.setEnabled(true);
196                     startContainer.setText("Stop Container");
197                 } else {
198                     resourceContainerInstance.stopContainer();
199                     startContainer.setText("Start Container");
200                     listBundles.setEnabled(false);
201                     Message msg;
202                     msg = Message.obtain();
203                     msg.what = 2;
204                     resourceContainerActivityInstance.getHandler().sendMessage(
205                             msg);
206                 }
207             }
208         });
209
210         // List Bundles Button Listener
211         listBundles.setOnClickListener(new OnClickListener() {
212             @Override
213             public void onClick(View v) {
214                 resourceContainerInstance.listBundles();
215             }
216         });
217
218
219         expListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
220             @Override
221             public void onGroupExpand(int groupPosition) {
222                 if (lastExpandedPosition != -1
223                         && groupPosition != lastExpandedPosition) {
224                     expListView.collapseGroup(lastExpandedPosition);
225                 }
226                 lastExpandedPosition = groupPosition;
227             }
228         });
229
230         expListView
231                 .setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
232
233                     @Override
234                     public boolean onChildClick(ExpandableListView parent,
235                                                 View v, int groupPosition, int childPosition,
236                                                 long id) {
237                         BundleInformation bundleToTest;
238
239                         switch (groupPosition) {
240                             case 0:
241                                 bundleToTest = ExampleBundleDescription.BMIBundle;
242                                 break;
243
244                             case 1:
245                                 bundleToTest = ExampleBundleDescription.DIBundle;
246                                 break;
247
248                             case 2:
249                                 bundleToTest = ExampleBundleDescription.DIAndroidBundle;
250                                 break;
251
252                             default:
253                                 return false;
254                         }
255
256                         switch (childPosition) {
257                             case 0:
258                                 resourceContainerInstance.addBundle(bundleToTest);
259                                 break;
260
261                             case 1:
262                                 resourceContainerInstance.startBundle(bundleToTest);
263                                 break;
264
265                             case 2:
266                                 resourceContainerInstance
267                                         .listBundleResources(bundleToTest.mBundleId);
268                                 break;
269
270                             case 3:
271                                 resourceContainerInstance.stopBundle(bundleToTest);
272                                 break;
273
274                             case 4:
275                                 resourceContainerInstance.removeBundle(bundleToTest);
276                                 break;
277
278                             default:
279                                 return false;
280                         }
281                         return true;
282                     }
283                 });
284     }
285
286     private void CopyAssetsToSDCard() {
287         AssetManager assetManager = getAssets();
288         String[] files = null;
289         try {
290             files = assetManager.list("lib");
291         } catch (IOException e) {
292             Log.e(LOG_TAG, e.getMessage());
293         }
294
295         for (String filename : files) {
296             InputStream in = null;
297             OutputStream out = null;
298             try {
299                 in = assetManager.open("lib/" + filename);
300                 out = new FileOutputStream(context.getFilesDir().getParent()
301                         + "/files/" + filename);
302                 copyIndividualFile(in, out);
303                 in.close();
304                 in = null;
305                 out.flush();
306                 out.close();
307                 out = null;
308             } catch (Exception e) {
309                 Log.e(LOG_TAG, e.getMessage());
310             }
311         }
312     }
313
314     private void copyIndividualFile(InputStream in, OutputStream out)
315             throws IOException {
316
317         Log.i(LOG_TAG, "copyIndividualFile");
318         byte[] buffer = new byte[2048];
319         int read;
320         while ((read = in.read(buffer)) != -1) {
321             out.write(buffer, 0, read);
322         }
323     }
324
325     @Override
326     public void onBackPressed() {
327         listAdapter = null;
328         expListView.setAdapter(listAdapter);
329         resourceContainerInstance.stopContainer();
330         ResourceContainer.startBundleFlag = false;
331         super.onBackPressed();
332     }
333
334     // class for handling expandable list items
335     public class ExpandableList extends BaseExpandableListAdapter {
336
337         private Context                       mContext;
338         private HashMap<String, List<String>> mListDataChild;
339         private List<String>                  mListDataHeader;
340
341         // constructor
342         public ExpandableList(Context context, List<String> dataHeader,
343                               HashMap<String, List<String>> childData) {
344             this.mContext = context;
345             this.mListDataHeader = dataHeader;
346             this.mListDataChild = childData;
347         }
348
349         // get the child ID
350         @Override
351         public long getChildId(int grpPosition, int childPosition) {
352             return childPosition;
353         }
354
355         // get the child
356         @Override
357         public Object getChild(int grpPosition, int childPosititon) {
358             return this.mListDataChild.get(
359                     this.mListDataHeader.get(grpPosition)).get(childPosititon);
360         }
361
362         // get Group View
363         @Override
364         public View getGroupView(int grpPosition, boolean isExpandable,
365                                  View changeView, ViewGroup head) {
366             String mainHeading = (String) getGroup(grpPosition);
367             if (changeView == null) {
368                 LayoutInflater flater;
369                 flater = (LayoutInflater) this.mContext
370                         .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
371                 changeView = flater.inflate(R.layout.group, null);
372             }
373
374             TextView listHeader = (TextView) changeView
375                     .findViewById(R.id.ListHead);
376             listHeader.setTypeface(null, Typeface.BOLD);
377             listHeader.setText(mainHeading);
378             return changeView;
379         }
380
381         // get Children count
382         @Override
383         public int getChildrenCount(int grpPosition) {
384             int count = this.mListDataChild.get(
385                     this.mListDataHeader.get(grpPosition)).size();
386             return count;
387         }
388
389         // Get Group
390         @Override
391         public Object getGroup(int grpPosition) {
392             return this.mListDataHeader.get(grpPosition);
393         }
394
395         // get Group size
396         @Override
397         public int getGroupCount() {
398             int size = this.mListDataHeader.size();
399             return size;
400         }
401
402         // get Group ID
403         @Override
404         public long getGroupId(int grpPosition) {
405             return grpPosition;
406         }
407
408         // get Group View
409         @Override
410         public View getChildView(int grpPosition, final int childPosition,
411                                  boolean isLastItem, View changeView, ViewGroup head) {
412
413             final String innerText = (String) getChild(grpPosition,
414                     childPosition);
415
416             if (changeView == null) {
417                 LayoutInflater flater = (LayoutInflater) this.mContext
418                         .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
419                 changeView = flater.inflate(R.layout.list_item, null);
420             }
421
422             TextView textListChild = (TextView) changeView
423                     .findViewById(R.id.listItem);
424
425             textListChild.setText(innerText);
426             return changeView;
427         }
428
429         // To check whether child is selectable or not
430         @Override
431         public boolean isChildSelectable(int grpPosition, int childPosition) {
432             return true;
433         }
434
435         // To check the stable IDs
436         @Override
437         public boolean hasStableIds() {
438             return false;
439         }
440     }
441
442     private void showWifiUnavailableDialog() {
443         new AlertDialog.Builder(this)
444                 .setTitle("Error")
445                 .setMessage(
446                         "WiFi is not enabled/connected! Please connect the WiFi and start application again...")
447                 .setCancelable(false)
448                 .setPositiveButton("OK", new DialogInterface.OnClickListener() {
449                     @Override
450                     public void onClick(DialogInterface dialog, int which) {
451                         finish();
452                     }
453                 }).create().show();
454     }
455
456     private boolean isWifiConnected() {
457         ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
458         return connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
459                 .isConnected();
460     }
461
462     private void configurePlatform() {
463         OcPlatform.Configure(new PlatformConfig(getApplicationContext(),
464                 ServiceType.IN_PROC, ModeType.CLIENT_SERVER, "0.0.0.0", 0,
465                 QualityOfService.LOW));
466         Log.i(LOG_TAG, "Configuration done successfully");
467     }
468
469     public Handler getHandler() {
470         return mHandler;
471     }
472
473     public void setHandler(Handler mHandler) {
474         ResourceContainerActivity.mHandler = mHandler;
475     }
476
477     public void displayToastMessage(String message) {
478         Toast toast = Toast.makeText(this, message, Toast.LENGTH_SHORT);
479         toast.show();
480         Log.i(LOG_TAG, message);
481     }
482 }