Imported Upstream version 1.1.0
[platform/upstream/iotivity.git] / cloud / stack / src / main / java / org / iotivity / cloud / base / SessionManager.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.base;
23
24 import java.util.ArrayList;
25 import java.util.HashMap;
26 import java.util.List;
27 import java.util.Map.Entry;
28 import java.util.Objects;
29
30 import io.netty.channel.ChannelHandlerContext;
31
32 public class SessionManager {
33
34     HashMap<String, ChannelHandlerContext> sessions = new HashMap<String, ChannelHandlerContext>();
35
36     public void addSession(String did, ChannelHandlerContext ctx) {
37         synchronized (sessions) {
38             sessions.put(did, ctx);
39         }
40     }
41
42     public void removeSession(String did) {
43
44         synchronized (sessions) {
45             sessions.remove(did);
46         }
47     }
48
49     public void removeSessionByChannel(ChannelHandlerContext ctx) {
50
51         String did = queryDid(ctx);
52         if (did != null) {
53             removeSession(did);
54         }
55     }
56
57     public ChannelHandlerContext querySession(String did) {
58         ChannelHandlerContext ctx = null;
59
60         synchronized (sessions) {
61             ctx = sessions.get(did);
62         }
63
64         return ctx;
65     }
66
67     public String queryDid(ChannelHandlerContext ctx) {
68         synchronized (sessions) {
69             for (Entry<String, ChannelHandlerContext> entry : sessions
70                     .entrySet()) {
71                 if (Objects.equals(ctx, entry.getValue())) {
72                     return entry.getKey();
73                 }
74             }
75         }
76
77         return null;
78     }
79
80     public List<String> getSessions() {
81         synchronized (sessions) {
82             List<String> list = new ArrayList<String>(sessions.keySet());
83             return list;
84         }
85     }
86 }