fixed CI unit test.
[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, Object>> 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(int startTime, int intervalTime) {
86         mTimer.schedule(new KeepAliveTask(), startTime, intervalTime);
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(Constants.REQ_PING_ARRAY, 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, Object> payloadData = mCbor
112                 .parsePayloadFromCbor(request.getPayload(), HashMap.class);
113
114         checkPayloadException(Constants.REQ_PING, payloadData);
115
116         Long pingTime = Integer.valueOf(
117                 payloadData.get(Constants.REQ_PING).toString()) * (long) 60000;
118         Long connectionTime = System.currentTimeMillis() + pingTime;
119         mConnectionPool.put(srcDevice, connectionTime);
120
121         return MessageBuilder.createResponse(request, ResponseStatus.VALID);
122     }
123
124     /**
125      * API for managing session
126      */
127     private class KeepAliveTask extends TimerTask {
128
129         @Override
130         public void run() {
131             Map<Device, Long> map = Collections
132                     .synchronizedMap(mConnectionPool);
133
134             List<Device> deleteList = new ArrayList<>();
135
136             synchronized (map) {
137                 Long currentTime = System.currentTimeMillis();
138                 for (Device device : map.keySet()) {
139                     Long lifeTime = (Long) map.get(device);
140                     if (lifeTime != null && lifeTime < currentTime) {
141                         deleteList.add(device);
142                     }
143                 }
144             }
145
146             for (Device device : deleteList) {
147                 mConnectionPool.remove(device);
148                 device.getCtx().fireChannelInactive();
149                 device.getCtx().close();
150             }
151         }
152     }
153 }