added code to close the netlink socket.
[contrib/iotivity.git] / android / examples / groupclient / src / main / java / org / iotivity / base / examples / GroupClient.java
1 /*
2  *******************************************************************
3  *
4  * Copyright 2015 Intel Corporation.
5  *
6  *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
7  *
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
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
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.
19  *
20  *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
21  */
22 package org.iotivity.base.examples;
23
24 import android.app.Activity;
25 import android.content.Context;
26 import android.os.Bundle;
27 import android.text.method.ScrollingMovementMethod;
28 import android.util.Log;
29 import android.view.View;
30 import android.widget.CompoundButton;
31 import android.widget.ScrollView;
32 import android.widget.TextView;
33 import android.widget.ToggleButton;
34
35 import org.iotivity.base.ErrorCode;
36 import org.iotivity.base.ModeType;
37 import org.iotivity.base.OcConnectivityType;
38 import org.iotivity.base.OcException;
39 import org.iotivity.base.OcHeaderOption;
40 import org.iotivity.base.OcPlatform;
41 import org.iotivity.base.OcRepresentation;
42 import org.iotivity.base.OcResource;
43 import org.iotivity.base.PlatformConfig;
44 import org.iotivity.base.QualityOfService;
45 import org.iotivity.base.ServiceType;
46
47 import java.util.EnumSet;
48 import java.util.HashMap;
49 import java.util.List;
50 import java.util.Map;
51
52 /**
53  * GroupClient
54  */
55 public class GroupClient extends Activity implements
56         OcPlatform.OnResourceFoundListener,
57         OcResource.OnGetListener {
58
59     private OcResource mFoundCollectionResource;
60
61     /**
62      * A local method to configure and initialize platform and then search for the collection
63      * resources
64      */
65     private synchronized void startGroupClient() {
66         Context context = this;
67
68         PlatformConfig platformConfig = new PlatformConfig(
69                 context,
70                 ServiceType.IN_PROC,
71                 ModeType.CLIENT,
72                 "0.0.0.0", 0,
73                 QualityOfService.LOW
74         );
75
76         msg("Configuring platform.");
77         OcPlatform.Configure(platformConfig);
78
79         msg("Find all resources of type \"a.collection\".");
80         try {
81             OcPlatform.findResource(
82                     "",
83                     OcPlatform.WELL_KNOWN_QUERY + "?rt=a.collection",
84                     EnumSet.of(OcConnectivityType.CT_DEFAULT),
85                     this
86             );
87         } catch (OcException e) {
88             Log.e(TAG, e.toString());
89             msg("Failed to invoke find resource API");
90         }
91
92         printLine();
93     }
94
95     /**
96      * An event handler to be executed whenever a "findResource" request completes successfully
97      *
98      * @param foundResource found resource
99      */
100     @Override
101     public synchronized void onResourceFound(OcResource foundResource) {
102         if (null == foundResource) {
103             msg("Found resource is invalid");
104             return;
105         }
106         if (null != mFoundCollectionResource) {
107             msg("Found another resource, ignoring");
108             return;
109         }
110
111         // Get the resource URI
112         String resourceUri = foundResource.getUri();
113         // Get the resource host address
114         String hostAddress = foundResource.getHost();
115         msg("\tURI of the resource: " + resourceUri);
116         msg("\tHost address of the resource: " + hostAddress);
117         // Get the resource types
118         msg("\tList of resource types: ");
119         for (String resourceType : foundResource.getResourceTypes()) {
120             msg("\t\t" + resourceType);
121         }
122         msg("\tList of resource interfaces:");
123         for (String resourceInterface : foundResource.getResourceInterfaces()) {
124             msg("\t\t" + resourceInterface);
125         }
126         msg("\tList of resource connectivity types:");
127         for (OcConnectivityType connectivityType : foundResource.getConnectivityTypeSet()) {
128             msg("\t\t" + connectivityType);
129         }
130
131         if (resourceUri.equals("/core/a/collection")) {
132             mFoundCollectionResource = foundResource;
133
134             msg("Getting representation of a collection resource...");
135
136             Map<String, String> queryParams = new HashMap<>();
137             try {
138                 mFoundCollectionResource.get(
139                         "",
140                         OcPlatform.DEFAULT_INTERFACE,
141                         queryParams,
142                         this
143                 );
144             } catch (OcException e) {
145                 Log.e(TAG, e.toString());
146                 msg("Error occurred while invoking \"get\" API");
147             }
148         }
149
150         printLine();
151         enableStartStopButton();
152     }
153
154     /**
155      * An event handler to be executed whenever a "get" request completes successfully
156      *
157      * @param list           list of the header options
158      * @param representation representation of a resource
159      */
160     @Override
161     public void onGetCompleted(List<OcHeaderOption> list, OcRepresentation representation) {
162         msg("Representation of a light collection resource:");
163         for (OcRepresentation childRepresentation : representation.getChildren()) {
164             msg("\t\tURI: " + childRepresentation.getUri());
165         }
166     }
167
168     /**
169      * An event handler to be executed whenever a "get" request fails
170      *
171      * @param throwable exception
172      */
173     @Override
174     public synchronized void onGetFailed(Throwable throwable) {
175         if (throwable instanceof OcException) {
176             OcException ocEx = (OcException) throwable;
177             Log.e(TAG, ocEx.toString());
178             ErrorCode errCode = ocEx.getErrorCode();
179             //do something based on errorCode
180             msg("Error code: " + errCode);
181         }
182         msg("Failed to get representation of a found collection resource");
183     }
184
185     /**
186      * A local method to reset group client
187      */
188     private synchronized void stopGroupClient() {
189         mFoundCollectionResource = null;
190
191         msg("Group Client is reset.");
192         printLine();
193
194         enableStartStopButton();
195     }
196
197     //******************************************************************************
198     // End of the OIC specific code
199     //******************************************************************************
200
201     private final static String TAG = GroupClient.class.getSimpleName();
202     private TextView mConsoleTextView;
203     private ScrollView mScrollView;
204
205     @Override
206     protected void onCreate(Bundle savedInstanceState) {
207         super.onCreate(savedInstanceState);
208         setContentView(R.layout.activity_group_client);
209
210         mConsoleTextView = (TextView) findViewById(R.id.consoleTextView);
211         mConsoleTextView.setMovementMethod(new ScrollingMovementMethod());
212         mScrollView = (ScrollView) findViewById(R.id.scrollView);
213         mScrollView.fullScroll(View.FOCUS_DOWN);
214         final ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
215
216         if (null == savedInstanceState) {
217             toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
218                 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
219                     toggleButton.setEnabled(false);
220                     if (isChecked) {
221                         new Thread(new Runnable() {
222                             public void run() {
223                                 startGroupClient();
224                             }
225                         }).start();
226                     } else {
227                         new Thread(new Runnable() {
228                             public void run() {
229                                 stopGroupClient();
230                             }
231                         }).start();
232                     }
233                 }
234             });
235         } else {
236             String consoleOutput = savedInstanceState.getString("consoleOutputString");
237             mConsoleTextView.setText(consoleOutput);
238             boolean buttonCheked = savedInstanceState.getBoolean("toggleButtonChecked");
239             toggleButton.setChecked(buttonCheked);
240         }
241     }
242
243     @Override
244     protected void onSaveInstanceState(Bundle outState) {
245         super.onSaveInstanceState(outState);
246         outState.putString("consoleOutputString", mConsoleTextView.getText().toString());
247         ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
248         outState.putBoolean("toggleButtonChecked", toggleButton.isChecked());
249     }
250
251     @Override
252     protected void onRestoreInstanceState(Bundle savedInstanceState) {
253         super.onRestoreInstanceState(savedInstanceState);
254
255         String consoleOutput = savedInstanceState.getString("consoleOutputString");
256         mConsoleTextView.setText(consoleOutput);
257
258         final ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
259         boolean buttonCheked = savedInstanceState.getBoolean("toggleButtonChecked");
260         toggleButton.setChecked(buttonCheked);
261     }
262
263     private void msg(final String text) {
264         runOnUiThread(new Runnable() {
265             public void run() {
266                 mConsoleTextView.append("\n");
267                 mConsoleTextView.append(text);
268                 mScrollView.fullScroll(View.FOCUS_DOWN);
269             }
270         });
271         Log.i(TAG, text);
272     }
273
274     private void printLine() {
275         msg("------------------------------------------------------------------------");
276     }
277
278     private void sleep(int seconds) {
279         try {
280             Thread.sleep(seconds * 1000);
281         } catch (InterruptedException e) {
282             e.printStackTrace();
283             Log.e(TAG, e.toString());
284         }
285     }
286
287     private void enableStartStopButton() {
288         runOnUiThread(new Runnable() {
289             public void run() {
290                 ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
291                 toggleButton.setEnabled(true);
292             }
293         });
294     }
295 }