001//@formatter:off
002/*
003 * Session - supplementary class
004 * Code-Beispiel zum Buch Patterns Kompakt, Verlag Springer Vieweg
005 * Copyright 2014 Karl Eilebrecht
006 * 
007 * Licensed under the Apache License, Version 2.0 (the "License"):
008 * you may not use this file except in compliance with the License.
009 * You may obtain a copy of the License at
010 *
011 * http://www.apache.org/licenses/LICENSE-2.0
012 *
013 * Unless required by applicable law or agreed to in writing, software
014 * distributed under the License is distributed on an "AS IS" BASIS,
015 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
016 * See the License for the specific language governing permissions and
017 * limitations under the License.
018 */
019//@formatter:on
020package de.calamanari.pk.identitymap;
021
022import java.util.HashMap;
023import java.util.Map;
024
025/**
026 * Session - supplementary class, the place where the IDENTITY MAPs reside in this example.
027 * 
028 * @author <a href="mailto:Karl.Eilebrecht(a/t)calamanari.de">Karl Eilebrecht</a>
029 */
030public class Session {
031
032    /**
033     * The session maintains session-local identity maps in this example
034     */
035    private final Map<Class<?>, IdentityMap<?, ?>> identityMaps = new HashMap<>();
036
037    /**
038     * This simulates some kind of session management
039     */
040    private static final ThreadLocal<Session> SESSION_HOLDER = ThreadLocal.withInitial(Session::new);
041
042    /**
043     * Returns the current session from our simulated session management
044     * 
045     * @return session
046     */
047    public static final Session getCurrentSession() {
048        return SESSION_HOLDER.get();
049    }
050
051    /**
052     * This is used by the finder to lookup the corresponding identity map for an entity
053     * 
054     * @param entityType class object of entity
055     * @param <K> some key type
056     * @param <E> some entity with key of corresponding type
057     * @return identity map for the given entity type, never null
058     */
059    public <K extends Object, E extends Entity<K>> IdentityMap<K, E> getIdentityMap(Class<E> entityType) {
060        @SuppressWarnings("unchecked")
061        IdentityMap<K, E> result = (IdentityMap<K, E>) identityMaps.computeIfAbsent(entityType, key -> new IdentityMap<>(entityType));
062        return result;
063    }
064
065    /**
066     * Method to be called when the current thread does not need the session data anymore.
067     */
068    public static void cleanUp() {
069        SESSION_HOLDER.remove();
070    }
071
072}