001/*
002 * JGrapes Event Driven Framework
003 * Copyright (C) 2017-2018 Michael N. Lipp
004 * 
005 * This program is free software; you can redistribute it and/or modify it 
006 * under the terms of the GNU Affero General Public License as published by 
007 * the Free Software Foundation; either version 3 of the License, or 
008 * (at your option) any later version.
009 * 
010 * This program is distributed in the hope that it will be useful, but 
011 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
012 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License 
013 * for more details.
014 * 
015 * You should have received a copy of the GNU Affero General Public License along 
016 * with this program; if not, see <http://www.gnu.org/licenses/>.
017 */
018
019package org.jgrapes.http;
020
021import java.time.Duration;
022import java.time.Instant;
023import java.util.LinkedHashMap;
024import java.util.Map;
025import java.util.Map.Entry;
026import java.util.Optional;
027import org.jgrapes.core.Channel;
028import org.jgrapes.http.events.DiscardSession;
029import org.jgrapes.http.events.Request;
030
031/**
032 * A in memory session manager. 
033 */
034public class InMemorySessionManager extends SessionManager {
035
036    @SuppressWarnings({ "PMD.UseConcurrentHashMap", "PMD.LooseCoupling" })
037    private final Map<String, InMemorySession> sessionsById
038        = new LinkedHashMap<>(16, 0.75f, true) {
039
040            @Override
041            protected boolean
042                    removeEldestEntry(Entry<String, InMemorySession> eldest) {
043                if (maxSessions() > 0 && size() > maxSessions()
044                    && eldest.getValue().setBeingDiscarded()) {
045                    fire(new DiscardSession(eldest.getValue()));
046                }
047                return false;
048            }
049        };
050
051    /**
052     * Creates a new session manager with its channel set to
053     * itself and the path set to "/". The manager handles
054     * all {@link Request} events.
055     */
056    public InMemorySessionManager() {
057        this("/");
058    }
059
060    /**
061     * Creates a new session manager with its channel set to
062     * itself and the path set to the given path. The manager
063     * handles all requests that match the given path, using the
064     * same rules as browsers do for selecting the cookies that
065     * are to be sent.
066     * 
067     * @param path the path
068     */
069    public InMemorySessionManager(String path) {
070        this(SELF, path);
071    }
072
073    /**
074     * Creates a new session manager with its channel set to
075     * the given channel, the path to "/" and the handler's priority 
076     * to 1000. The manager handles all {@link Request} events.
077     * 
078     * @param componentChannel the component channel
079     */
080    public InMemorySessionManager(Channel componentChannel) {
081        this(componentChannel, "/");
082    }
083
084    /**
085     * Creates a new session manager with the given channel and path.
086     * The manager handles all requests that match the given path, using
087     * the same rules as browsers do for selecting the cookies that
088     * are to be sent. The request handler's priority is set to 1000.
089     *  
090     * @param componentChannel the component channel
091     * @param path the path
092     */
093    public InMemorySessionManager(Channel componentChannel, String path) {
094        this(componentChannel, derivePattern(path), 1000, path);
095    }
096
097    /**
098     * Creates a new session manager using the given channel and path.
099     * The manager handles only requests that match the given pattern.
100     * The {@link Request} handler is registered with the given priority.
101     * 
102     * This constructor can be used if special handling of top level
103     * requests is needed.
104     *
105     * @param componentChannel the component channel
106     * @param pattern the path part of a {@link ResourcePattern}
107     * @param priority the priority
108     * @param path the path
109     */
110    public InMemorySessionManager(Channel componentChannel, String pattern,
111            int priority, String path) {
112        super(componentChannel, pattern, priority, path);
113    }
114
115    @Override
116    @SuppressWarnings({ "PMD.CognitiveComplexity", "PMD.LooseCoupling",
117        "PMD.AvoidInstantiatingObjectsInLoops",
118        "PMD.AvoidSynchronizedStatement", "PMD.AvoidDuplicateLiterals" })
119    protected Optional<Instant> startDiscarding(long absoluteTimeout,
120            long idleTimeout) {
121        synchronized (this) {
122            Instant nextTimout = null;
123            for (InMemorySession session : sessionsById.values()) {
124                if (hasTimedOut(session)) {
125                    if (session.setBeingDiscarded()) {
126                        fire(new DiscardSession(session));
127                    }
128                    continue;
129                }
130                if (absoluteTimeout > 0) {
131                    Instant timesOutAt = session.createdAt()
132                        .plus(Duration.ofMillis(absoluteTimeout));
133                    if (nextTimout == null
134                        || timesOutAt.isBefore(nextTimout)) {
135                        nextTimout = timesOutAt;
136                    }
137                }
138                if (idleTimeout > 0) {
139                    Instant timesOutAt = session.lastUsedAt()
140                        .plus(Duration.ofMillis(idleTimeout));
141                    if (nextTimout == null
142                        || timesOutAt.isBefore(nextTimout)) {
143                        nextTimout = timesOutAt;
144                    }
145                }
146            }
147            return Optional.ofNullable(nextTimout);
148        }
149    }
150
151    @Override
152    @SuppressWarnings("PMD.AvoidSynchronizedStatement")
153    protected Session createSession(String sessionId) {
154        @SuppressWarnings("PMD.LooseCoupling")
155        InMemorySession session = new InMemorySession(sessionId);
156        synchronized (this) {
157            sessionsById.put(sessionId, session);
158        }
159        return session;
160    }
161
162    @Override
163    @SuppressWarnings("PMD.AvoidSynchronizedStatement")
164    protected Optional<Session> lookupSession(String sessionId) {
165        synchronized (this) {
166            return Optional.ofNullable(sessionsById.get(sessionId));
167        }
168    }
169
170    @Override
171    @SuppressWarnings("PMD.AvoidSynchronizedStatement")
172    protected void removeSession(String sessionId) {
173        synchronized (this) {
174            sessionsById.remove(sessionId);
175        }
176    }
177
178    /*
179     * (non-Javadoc)
180     * 
181     * @see org.jgrapes.http.SessionManager#sessionCount()
182     */
183    @Override
184    @SuppressWarnings("PMD.AvoidSynchronizedStatement")
185    protected int sessionCount() {
186        synchronized (this) {
187            return sessionsById.size();
188        }
189    }
190
191}