Clean up some SonarQube warnings (trailing whitespace, etc).
[platform/upstream/iotivity.git] / android / examples / simpleserver / src / main / java / org / iotivity / base / examples / simpleserver / SimpleServer.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
23 package org.iotivity.base.examples.simpleserver;
24
25 import android.app.Activity;
26 import android.content.BroadcastReceiver;
27 import android.content.Context;
28 import android.content.Intent;
29 import android.content.IntentFilter;
30 import android.os.Bundle;
31 import android.os.Message;
32 import android.support.v4.content.LocalBroadcastManager;
33 import android.text.method.ScrollingMovementMethod;
34 import android.util.Log;
35 import android.view.Menu;
36 import android.view.MenuItem;
37 import android.widget.LinearLayout;
38 import android.widget.TextView;
39 import android.content.SharedPreferences;
40 import android.content.res.AssetManager;
41 import android.preference.PreferenceManager;
42
43 import org.iotivity.base.ModeType;
44 import org.iotivity.base.OcPlatform;
45 import org.iotivity.base.OcRepresentation;
46 import org.iotivity.base.PlatformConfig;
47 import org.iotivity.base.QualityOfService;
48 import org.iotivity.base.ServiceType;
49
50 import java.io.File;
51 import java.io.FileNotFoundException;
52 import java.io.FileOutputStream;
53 import java.io.IOException;
54 import java.io.InputStream;
55 import java.io.OutputStream;
56
57 import base.iotivity.org.examples.message.IMessageLogger;
58
59 /**
60  * SimpleServer
61  *
62  * SimpleServer instantiates a TextView and creates and configures OICPlatform.
63  * It also creates a LightResource and waits for the incoming client requests to handle specific scenarios.
64  * This implements IMessageLogger to display messages on the screen
65  */
66
67 public class SimpleServer extends Activity implements IMessageLogger {
68     private final static String TAG = "SimpleServer: ";
69     private static final int BUFFER_SIZE = 1024;
70     private String filePath = "";
71     private TextView mEventsTextView;
72     private MessageReceiver mMessageReceiver = new MessageReceiver();
73
74     @Override
75     protected void onCreate(Bundle savedInstanceState) {
76         super.onCreate(savedInstanceState);
77         setContentView(R.layout.activity_main);
78         registerReceiver(mMessageReceiver, new IntentFilter("org.iotivity.base.examples.simpleserver"));
79
80         mEventsTextView = new TextView(this);
81         mEventsTextView.setMovementMethod(new ScrollingMovementMethod());
82         LinearLayout layout = (LinearLayout)findViewById(R.id.linearLayout);
83         layout.addView(mEventsTextView, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f));
84
85         OcRepresentation rep = new OcRepresentation();
86         rep.setValueBool("test", false);
87         boolean result = rep.getValueBool("test");
88         filePath = getFilesDir().getPath() + "/";//  data/data/<package>/files/
89         //copy json when application runs first time
90         SharedPreferences wmbPreference = PreferenceManager.getDefaultSharedPreferences(this);
91         boolean isFirstRun = wmbPreference.getBoolean("FIRSTRUN", true);
92         if (isFirstRun) {
93             copyJsonFromAsset();
94             SharedPreferences.Editor editor = wmbPreference.edit();
95             editor.putBoolean("FIRSTRUN", false);
96             editor.commit();
97         }
98
99         initOICStack();
100     }
101
102     /**
103      * Copy svr db json file from assets folder to app data files dir
104      */
105     private void copyJsonFromAsset() {
106         AssetManager assetManager = getAssets();
107
108         InputStream in = null;
109         OutputStream out = null;
110         try {
111
112             in = assetManager.open(StringConstants.OIC_SERVER_JSON_DB_FILE);
113             File file = new File(filePath);
114             //check files directory exists
115             if (!(file.exists() && file.isDirectory())) {
116                 file.mkdirs();
117             }
118             out = new FileOutputStream(filePath + StringConstants.OIC_SERVER_JSON_DB_FILE);
119             copyFile(in, out);
120         } catch (NullPointerException e) {
121             logMessage(TAG + "Null pointer exception " + e.getMessage());
122             Log.e(TAG, e.getMessage());
123         } catch (FileNotFoundException e) {
124             logMessage(TAG + "Json svr db file not found " + e.getMessage());
125             Log.e(TAG, e.getMessage());
126         } catch (IOException e) {
127             logMessage(TAG + StringConstants.OIC_SERVER_JSON_DB_FILE + " file copy failed");
128             Log.e(TAG, e.getMessage());
129         } finally {
130             if (in != null) {
131                 try {
132                     in.close();
133                 } catch (IOException e) {
134                     Log.e(TAG, e.getMessage());
135                 }
136             }
137             if (out != null) {
138                 try {
139                     out.close();
140                 } catch (IOException e) {
141                     Log.e(TAG, e.getMessage());
142                 }
143             }
144         }
145     }
146
147     private void copyFile(InputStream in, OutputStream out) throws IOException {
148         byte[] buffer = new byte[BUFFER_SIZE];
149         int read;
150         while ((read = in.read(buffer)) != -1) {
151             out.write(buffer, 0, read);
152         }
153     }
154     /**
155      * configure OIC platform and call findResource
156      */
157     private void initOICStack() {
158         //create platform config
159         PlatformConfig cfg = new PlatformConfig(
160                 this,
161                 ServiceType.IN_PROC,
162                 ModeType.SERVER,
163                 "0.0.0.0", // bind to all available interfaces
164                 0,
165                 QualityOfService.LOW,
166                 filePath + StringConstants.OIC_SERVER_JSON_DB_FILE);
167         OcPlatform.Configure(cfg);
168         // Create instance of lightResource
169         LightResource myLight = new LightResource(this);
170         // create and register a resource
171         myLight.createResource0();
172     }
173
174     public class MessageReceiver extends BroadcastReceiver {
175         @Override
176         public void onReceive(Context context, Intent intent) {
177             final String message = intent.getStringExtra(StringConstants.MESSAGE);
178             logMessage(message);
179         }
180     }
181
182     public void logMessage(final String text) {
183         runOnUiThread(new Runnable() {
184             public void run() {
185                 final Message msg = new Message();
186                 msg.obj = text;
187                 mEventsTextView.append("\n");
188                 mEventsTextView.append(text);
189             }
190         });
191         Log.i(TAG, text);
192     }
193
194     @Override
195     public boolean onCreateOptionsMenu(Menu menu) {
196         getMenuInflater().inflate(R.menu.menu_main, menu);
197         return true;
198     }
199
200     @Override
201     public boolean onOptionsItemSelected(MenuItem item) {
202         int id = item.getItemId();
203         if (id == R.id.action_settings) {
204             return true;
205         }
206         return super.onOptionsItemSelected(item);
207     }
208
209     @Override
210     public void onDestroy() {
211         super.onDestroy();
212         onStop();
213     }
214
215     @Override
216     protected void onStop() {
217         LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
218         super.onStop();
219     }
220 }