Merge branch 'cloud-interface'
[platform/upstream/iotivity.git] / cloud / interface / src / main / java / org / iotivity / cloud / ciserver / resources / KeepAliveResource.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.ciserver.resources;
23
24 import java.util.ArrayList;
25 import java.util.Arrays;
26 import java.util.Collections;
27 import java.util.HashMap;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.Timer;
31 import java.util.TimerTask;
32
33 import org.iotivity.cloud.base.device.Device;
34 import org.iotivity.cloud.base.exception.ServerException;
35 import org.iotivity.cloud.base.exception.ServerException.BadRequestException;
36 import org.iotivity.cloud.base.protocols.IRequest;
37 import org.iotivity.cloud.base.protocols.IResponse;
38 import org.iotivity.cloud.base.protocols.MessageBuilder;
39 import org.iotivity.cloud.base.protocols.enums.ContentFormat;
40 import org.iotivity.cloud.base.protocols.enums.ResponseStatus;
41 import org.iotivity.cloud.base.resource.Resource;
42 import org.iotivity.cloud.ciserver.Constants;
43 import org.iotivity.cloud.util.Cbor;
44
45 /**
46  *
47  * This class provides a set of APIs to use KeepAlive Resource for ensuring the
48  * connection.
49  *
50  */
51 public class KeepAliveResource extends Resource {
52     private int[]                          mIntervals      = null;
53     private Timer                          mTimer          = new Timer();
54     private Cbor<HashMap<String, Integer>> mCbor           = new Cbor<>();
55     private HashMap<Device, Long>          mConnectionPool = new HashMap<>();
56
57     public KeepAliveResource(int[] intervals) {
58         super(Arrays.asList(Constants.PREFIX_OIC, Constants.KEEP_ALIVE_URI));
59         mIntervals = intervals;
60     }
61
62     @Override
63     public void onDefaultRequestReceived(Device srcDevice, IRequest request)
64             throws ServerException {
65
66         IResponse response = null;
67
68         switch (request.getMethod()) {
69             case GET:
70                 response = handleGetPingConfig(request);
71                 break;
72
73             case PUT:
74                 response = handlePutPingConfig(srcDevice, request);
75                 break;
76
77             default:
78                 throw new BadRequestException(
79                         request.getMethod() + " request type is not support");
80         }
81
82         srcDevice.sendResponse(response);
83     }
84
85     public void startSessionChecker() {
86         mTimer.schedule(new KeepAliveTask(), 30000, 60000);
87     }
88
89     public void stopSessionChecker() {
90         mTimer.cancel();
91     }
92
93     /**
94      * API for making interval and first response to Resource
95      * 
96      * @param request
97      *            ChannelHandlerContext of request message
98      */
99     private IResponse handleGetPingConfig(IRequest request) {
100
101         HashMap<String, int[]> payloadData = new HashMap<>();
102         payloadData.put("inarray", mIntervals);
103
104         return MessageBuilder.createResponse(request, ResponseStatus.CONTENT,
105                 ContentFormat.APPLICATION_CBOR,
106                 mCbor.encodingPayloadToCbor(payloadData));
107     }
108
109     private IResponse handlePutPingConfig(Device srcDevice, IRequest request) {
110
111         HashMap<String, Integer> payloadData = mCbor
112                 .parsePayloadFromCbor(request.getPayload(), HashMap.class);
113
114         if (payloadData.containsKey("in")) {
115             mConnectionPool.put(srcDevice, System.currentTimeMillis()
116                     + (payloadData.get("in") * (long) 60000));
117         }
118
119         return MessageBuilder.createResponse(request, ResponseStatus.VALID);
120     }
121
122     /**
123      * API for managing session
124      */
125     private class KeepAliveTask extends TimerTask {
126
127         @Override
128         public void run() {
129             Map<Device, Long> map = Collections
130                     .synchronizedMap(mConnectionPool);
131
132             List<Device> deleteList = new ArrayList<>();
133
134             synchronized (map) {
135                 Long currentTime = System.currentTimeMillis();
136                 for (Device device : map.keySet()) {
137                     Long lifeTime = (Long) map.get(device);
138                     if (lifeTime < currentTime) {
139                         deleteList.add(device);
140                     }
141                 }
142             }
143
144             for (Device device : deleteList) {
145                 mConnectionPool.remove(device);
146                 device.getCtx().fireChannelInactive();
147                 device.getCtx().close();
148             }
149         }
150     }
151 }