[Simulator] Minor UI changes fixing the IOT-1087.
[platform/upstream/iotivity.git] / cloud / account / src / main / java / org / iotivity / cloud / accountserver / resources / AccountResource.java
1 /*
2  *******************************************************************
3  *
4  * Copyright 2016 Samsung Electronics All Rights Reserved.
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.cloud.accountserver.resources;
23
24 import java.util.ArrayList;
25 import java.util.HashMap;
26 import java.util.List;
27
28 import org.iotivity.cloud.accountserver.AccountServerManager;
29 import org.iotivity.cloud.accountserver.Const;
30 import org.iotivity.cloud.accountserver.util.CoapMessageBuilder;
31 import org.iotivity.cloud.accountserver.util.JSONUtil;
32 import org.iotivity.cloud.base.Resource;
33 import org.iotivity.cloud.base.protocols.coap.CoapRequest;
34 import org.iotivity.cloud.base.protocols.coap.CoapResponse;
35 import org.iotivity.cloud.base.protocols.coap.enums.CoapMethod;
36 import org.iotivity.cloud.base.protocols.coap.enums.CoapStatus;
37 import org.iotivity.cloud.util.Logger;
38
39 import io.netty.channel.ChannelHandlerContext;
40
41 /**
42  *
43  * This class provides a set of APIs to handle requests for publishing and
44  * finding resources.
45  *
46  */
47 public class AccountResource extends Resource {
48
49     public AccountResource() {
50         setUri(Const.ACCOUNT_URI);
51     }
52
53     @Override
54     public void onRequestReceived(ChannelHandlerContext ctx,
55             CoapRequest request) {
56
57         Logger.d("AccountResource IN");
58
59         if (ctx == null || request == null) {
60             Logger.d("ctx or request msg is null");
61         }
62
63         else {
64             CoapMethod method = request.getRequestMethod();
65
66             switch (method) {
67                 case GET:
68                     try {
69                         handleGetRequest(ctx, request);
70                     } catch (Exception e) {
71                         e.printStackTrace();
72                     }
73                     break;
74
75                 case POST:
76                     try {
77                         handlePostRequest(ctx, request);
78                     } catch (Exception e) {
79                         e.printStackTrace();
80                     }
81                     break;
82
83                 default:
84                     Logger.w("method[" + method + "] is not supported");
85                     break;
86             }
87         }
88     }
89
90     /**
91      * API for handling GET message
92      * 
93      * @param ctx
94      *            ChannelHandlerContext of request message
95      * @param request
96      *            CoAP request message
97      * @throws Exception
98      */
99     private void handleGetRequest(ChannelHandlerContext ctx,
100             CoapRequest request) throws Exception {
101
102         String reqType = extractQuery(request, Const.REQ_TYPE);
103
104         if (reqType == null)
105             throw new IllegalArgumentException(
106                     "request type is null in query!");
107
108         CoapResponse response = null;
109
110         switch (reqType) {
111
112             case Const.TYPE_FIND:
113                 response = handleFindRequest(request);
114                 break;
115             default:
116                 Logger.w("reqType[" + reqType + "] is not supported");
117         }
118
119         ctx.write(response);
120
121     }
122
123     /**
124      * API for handling POST message
125      * 
126      * @param ctx
127      *            ChannelHandlerContext of request message
128      * @param request
129      *            CoAP request message
130      * @throws Exception
131      */
132     private void handlePostRequest(ChannelHandlerContext ctx,
133             CoapRequest request) throws Exception {
134
135         String reqType = extractQuery(request, Const.REQ_TYPE);
136
137         if (reqType == null)
138             throw new IllegalArgumentException(
139                     "request type is null in query!");
140
141         CoapResponse response = null;
142
143         switch (reqType) {
144             case Const.TYPE_PUBLISH:
145                 response = handlePublishRequest(request);
146                 break;
147             default:
148                 throw new IllegalArgumentException(
149                         "request type is not supported");
150         }
151
152         ctx.write(response);
153     }
154
155     private CoapResponse handlePublishRequest(CoapRequest request) {
156
157         String payload = request.getPayloadString();
158
159         JSONUtil util = new JSONUtil();
160         String userId = util.parseJSON(payload, Const.REQUEST_USER_ID);
161         String deviceId = util.parseJSON(payload, Const.REQUEST_DEVICE_ID);
162
163         Logger.d("userId: " + userId + ", deviceId: " + deviceId);
164
165         AccountServerManager oauthServerManager = new AccountServerManager();
166         Boolean status = oauthServerManager.registerUserAccount(userId,
167                 deviceId);
168
169         Logger.d("status : " + status);
170
171         CoapMessageBuilder responseMessage = new CoapMessageBuilder();
172         CoapResponse coapResponse = null;
173
174         if (status) {
175             coapResponse = responseMessage.buildCoapResponse(request.getToken(),
176                     CoapStatus.CREATED);
177         } else {
178             coapResponse = responseMessage.buildCoapResponse(request.getToken(),
179                     CoapStatus.INTERNAL_SERVER_ERROR);
180         }
181
182         return coapResponse;
183     }
184
185     private CoapResponse handleFindRequest(CoapRequest request) {
186
187         String payload = request.getPayloadString();
188         // String payload = getPayloadString(request.getPayload());
189
190         JSONUtil util = new JSONUtil();
191         String userId = util.parseJSON(payload, Const.REQUEST_USER_ID);
192
193         Logger.d("userId: " + userId);
194
195         AccountServerManager oauthServerManager = new AccountServerManager();
196         ArrayList<String> deviceList = oauthServerManager
197                 .requestAccountDevices(userId);
198
199         ResponseObject response = new ResponseObject();
200         response.setDeviceList(deviceList);
201
202         String responseJson = convertFindResponseToJson(response);
203         Logger.d("responseJson: " + responseJson);
204
205         CoapMessageBuilder responseMessage = new CoapMessageBuilder();
206         CoapResponse coapResponse = responseMessage.buildCoapResponse(
207                 request.getToken(), responseJson, CoapStatus.CONTENT);
208
209         return coapResponse;
210     }
211
212     private String convertFindResponseToJson(ResponseObject response) {
213
214         HashMap<Object, Object> responseMap = new HashMap<Object, Object>();
215
216         ArrayList<String> deviceList = response.getDeviceList();
217         responseMap.put(Const.RESPONSE_DEVICES, deviceList);
218
219         JSONUtil jsonUtil = new JSONUtil();
220         String responseJson = jsonUtil.writeJSON(responseMap);
221
222         return responseJson;
223     }
224
225     private String extractQuery(CoapRequest request, String key) {
226
227         String value = null;
228
229         List<String> Segments = request.getUriQuerySegments();
230
231         for (String s : Segments) {
232
233             String pair[] = s.split("=");
234
235             if (pair[0].equals(key)) {
236
237                 value = pair[1];
238             }
239         }
240
241         return value;
242     }
243
244     /*
245      * private static String getPayloadString(byte[] payload) {
246      * 
247      * if (payload == null) return "";
248      * 
249      * return new String(payload, Charset.forName("UTF-8")); }
250      */
251
252 }