Clean up some SonarQube warnings (trailing whitespace, etc).
[platform/upstream/iotivity.git] / android / examples / simpleserver / src / main / java / org / iotivity / base / examples / simpleserver / LightResource.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.content.Context;
26 import android.content.Intent;
27 import android.util.Log;
28
29 import org.iotivity.base.EntityHandlerResult;
30 import org.iotivity.base.ObservationInfo;
31 import org.iotivity.base.OcException;
32 import org.iotivity.base.OcPlatform;
33 import org.iotivity.base.OcRepresentation;
34 import org.iotivity.base.OcResourceHandle;
35 import org.iotivity.base.OcResourceRequest;
36 import org.iotivity.base.OcResourceResponse;
37 import org.iotivity.base.RequestHandlerFlag;
38 import org.iotivity.base.RequestType;
39 import org.iotivity.base.ResourceProperty;
40
41 import java.util.EnumSet;
42 import java.util.LinkedList;
43 import java.util.List;
44
45 import base.iotivity.org.examples.message.IMessageLogger;
46
47 /**
48  * LightResource
49  *
50  * class LightResource is the main class of the simpleServer. This creates resources and handles incoming requests from the client.
51  */
52 public class LightResource implements IMessageLogger {
53     private Context mContext;
54     private static String TAG = "SimpleServer: ";
55
56     private String mName;
57     private Boolean mState;
58     private Integer mPower;
59     private OcRepresentation mLightRep;
60     private OcResourceHandle mResourceHandle;
61     private List<Byte> mObservationIds;
62     private static boolean doOnce; // used in POST
63     LightRepThread lightRepThread;
64
65     // constructor
66     LightResource(Context context) {
67         mContext = context;
68         mName = "John's light";
69         mState = false;
70         mPower = 0;
71         mObservationIds = new LinkedList<>();
72         mLightRep = new OcRepresentation();
73         try {
74             mLightRep.setValue(StringConstants.STATE, mState);
75             mLightRep.setValue(StringConstants.POWER, mPower);
76             mLightRep.setValue(StringConstants.NAME, mName);
77         } catch (OcException e) {
78             Log.e(TAG, e.getMessage());
79         }
80         doOnce = true; // used in post
81         lightRepThread = null;
82     }
83
84     //accessor methods
85     protected int getPower() {
86         return mPower;
87     }
88     protected void setPower(int power) {
89         mPower = power;
90     }
91     protected OcResourceHandle getHandle() {
92         return mResourceHandle;
93     }
94
95     /**
96      *  creates a resource. this method internally calls registerResource
97      * @return returns the OcResourceHandle after creating and registering the resource
98      */
99     protected OcResourceHandle createResource0() {
100         // entityhandler for registerResource
101         OcPlatform.EntityHandler eh = new OcPlatform.EntityHandler() {
102             @Override
103             public EntityHandlerResult handleEntity(OcResourceRequest ocResourceRequest) {
104                 // this is where the main logic of simpleserver is handled as different requests (GET, PUT, POST, OBSERVE, DELETE) are handled
105                 return entityHandler(ocResourceRequest);
106             }
107         };
108
109         try {
110             mResourceHandle = OcPlatform.registerResource(StringConstants.RESOURCE_URI0, StringConstants.RESOURCE_TYPENAME,
111                 StringConstants.RESOURCE_INTERFACE, eh,
112                 EnumSet.of(ResourceProperty.DISCOVERABLE, ResourceProperty.OBSERVABLE));
113         } catch (OcException e) {
114             logMessage(TAG + "RegisterResource error. " + e.getMessage());
115             Log.e(TAG, e.getMessage());
116         }
117         logMessage(TAG + "Successfully registered resource");
118         return mResourceHandle;
119     }
120
121     /**
122      *  create another resource. this method internally calls registerResource
123      */
124     private void createResource1() {
125         // entityhandler for registerResource
126         OcPlatform.EntityHandler eh = new OcPlatform.EntityHandler() {
127             @Override
128             public EntityHandlerResult handleEntity(OcResourceRequest ocResourceRequest) {
129                 // this is where the main logic of simpleserver is handled as different requests (GET, PUT, POST, OBSERVE, DELETE) are handled
130             return entityHandler(ocResourceRequest);
131             }
132         };
133
134         try {
135             OcPlatform.registerResource(StringConstants.RESOURCE_URI1, StringConstants.RESOURCE_TYPENAME,
136                 StringConstants.RESOURCE_INTERFACE, eh,
137                 EnumSet.of(ResourceProperty.DISCOVERABLE, ResourceProperty.OBSERVABLE));
138         } catch (OcException e) {
139             logMessage(TAG + "RegisterResource1 error: " + e.getMessage());
140             Log.e(TAG, e.getMessage());
141         }
142         logMessage(TAG + "Successfully registered resource1");
143     }
144
145     /**
146      * post representation . Post can act like put or can create a new resource.
147      * Gets value from the representation and updates the internal state
148      * @param rep current OcRepresentation of the object
149      * @return updated OcRepresentation
150      */
151     private OcRepresentation post(OcRepresentation rep) {
152         //create a resource the first time
153         if (true == doOnce) {
154             createResource1();
155             OcRepresentation representation = rep;
156             try {
157                 representation.setValue(StringConstants.CREATED_URI, StringConstants.RESOURCE_URI1);
158             } catch (OcException e) {
159                 Log.e(TAG, e.getMessage());
160             }
161             doOnce = false;
162             return representation;
163         }
164         // from second time onwards, put
165         put(rep);
166         return get();
167     }
168
169     /**
170      * puts representation . Gets value from the representation and updates the internal state
171      * @param rep current OcRepresentation of the object
172      */
173     private void put(OcRepresentation rep) {
174         try {
175             mState = rep.getValue(StringConstants.STATE);
176             mPower = rep.getValue(StringConstants.POWER);
177         } catch (OcException e) {
178             Log.e(TAG, e.getMessage());
179         }
180         logMessage(TAG + "Put State: " +  mState + " Name: " + mName + " Power: " + mPower);
181     }
182
183     /**
184      *  gets the updated representation. Updates the representation with internal state before sending out
185      * @return OcRepresentation after updating the values of the lightRepresentation
186      */
187     protected OcRepresentation get() {
188         try {
189             mLightRep.setValue(StringConstants.STATE, mState);
190             mLightRep.setValue(StringConstants.POWER, mPower);
191             mLightRep.setValue(StringConstants.NAME, mName);
192         } catch (OcException e) {
193             Log.e(TAG, e.getMessage());
194         }
195         return mLightRep;
196     }
197
198     /**
199      * this is the main method which handles different incoming requests appropriately.
200      * Init is not supported currently.
201      * @param request OcResourceRequest from the client
202      * @return EntityHandlerResult depending on whether the request was handled successfully or not
203      */
204     private EntityHandlerResult entityHandler(OcResourceRequest request) {
205         EntityHandlerResult result = EntityHandlerResult.ERROR;
206         if (null != request) {
207             RequestType requestType = request.getRequestType();
208             EnumSet<RequestHandlerFlag> requestFlag = request.getRequestHandlerFlagSet();
209
210             if (requestFlag.contains(RequestHandlerFlag.INIT)) {
211                 logMessage(TAG + "Init");
212             }
213             if (requestFlag.contains(RequestHandlerFlag.REQUEST)) {
214                 try {
215                     logMessage(TAG + "Request");
216                     OcResourceResponse ocResourceResponse = new OcResourceResponse();
217                     ocResourceResponse.setRequestHandle(request.getRequestHandle());
218                     ocResourceResponse.setResourceHandle(request.getResourceHandle());
219
220                     switch (requestType) {
221                         // handle GET request
222                         case GET:
223                             logMessage("GET");
224                             ocResourceResponse.setResponseResult(EntityHandlerResult.OK);
225                             ocResourceResponse.setErrorCode(StringConstants.ERROR_CODE);
226                             ocResourceResponse.setResourceRepresentation(get());
227                             OcPlatform.sendResponse(ocResourceResponse);
228                             break;
229                         // handle PUT request
230                         case PUT:
231                             OcRepresentation rep = request.getResourceRepresentation();
232                             put(rep);
233                             ocResourceResponse.setErrorCode(StringConstants.ERROR_CODE);
234                             ocResourceResponse.setResponseResult(EntityHandlerResult.OK);
235                             ocResourceResponse.setResourceRepresentation(get());
236                             OcPlatform.sendResponse(ocResourceResponse);
237                             break;
238                         // handle POST request
239                         case POST:
240                             rep = request.getResourceRepresentation();
241                             OcRepresentation rep_post = post(rep);
242                             ocResourceResponse.setResourceRepresentation(rep_post);
243                             ocResourceResponse.setErrorCode(StringConstants.ERROR_CODE);
244                             if (rep_post.hasAttribute(StringConstants.CREATED_URI)) {
245                                 String createdUri = rep_post.getValue(StringConstants.CREATED_URI);
246                                 if (createdUri.equals(StringConstants.RESOURCE_URI1)) {
247                                     ocResourceResponse.setNewResourceUri(createdUri);
248                                     ocResourceResponse.setResponseResult
249                                             (EntityHandlerResult.RESOURCE_CREATED);
250                                 } else {
251                                     ocResourceResponse.setResponseResult(EntityHandlerResult.OK);
252                                 }
253                             }
254                             OcPlatform.sendResponse(ocResourceResponse);
255                             break;
256                         // handle DELETE request
257                         case DELETE:
258                             logMessage(TAG + "DELETE");
259                             OcPlatform.unregisterResource(getHandle());
260                             OcPlatform.unregisterResource(getHandle());
261                             break;
262
263                     }
264
265                     result = EntityHandlerResult.OK;
266                 } catch(OcException e) {
267                     logMessage(TAG + "Error in Request " + e.getMessage());
268                     Log.e(TAG, e.getMessage());
269                 }
270             }
271             // handle OBSERVER request
272             if (requestFlag.contains(RequestHandlerFlag.OBSERVER)) {
273                 logMessage(TAG + "OBSERVER");
274                 ObservationInfo observationInfo = request.getObservationInfo();
275
276                 switch (observationInfo.getObserveAction()) {
277                     case REGISTER:
278                         synchronized (mObservationIds) {
279                             mObservationIds.add(observationInfo.getOcObservationId());
280                         }
281                         break;
282                     case UNREGISTER:
283                         synchronized (mObservationIds) {
284                             mObservationIds.remove(observationInfo.getOcObservationId());
285                         }
286                         break;
287                 }
288                 if (null == lightRepThread) {
289                     lightRepThread = new LightRepThread(this, mObservationIds);
290                     lightRepThread.run();
291                 }
292                 result = EntityHandlerResult.OK;
293             }
294         }
295         return result;
296     }
297
298     @Override
299     public void logMessage(String msg) {
300         logMsg(msg);
301     }
302
303     public void logMsg(final String text) {
304         Intent intent = new Intent("org.iotivity.base.examples.simpleserver");
305         intent.putExtra(StringConstants.MESSAGE, text);
306         mContext.sendBroadcast(intent);
307     }
308 }