001    /*
002     * Licensed to the Apache Software Foundation (ASF) under one
003     * or more contributor license agreements.  See the NOTICE file
004     * distributed with this work for additional information
005     * regarding copyright ownership.  The ASF licenses this file
006     * to you under the Apache License, Version 2.0 (the
007     * "License"); you may not use this file except in compliance
008     * with the License.  You may obtain a copy of the License at
009     *
010     *     http://www.apache.org/licenses/LICENSE-2.0
011     *
012     * Unless required by applicable law or agreed to in writing,
013     * software distributed under the License is distributed on an
014     * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015     * KIND, either express or implied.  See the License for the
016     * specific language governing permissions and limitations
017     * under the License.
018     */
019    package org.apache.shiro.session.mgt.eis;
020    
021    import org.apache.shiro.session.Session;
022    import org.apache.shiro.session.UnknownSessionException;
023    import org.apache.shiro.session.mgt.SimpleSession;
024    
025    import java.io.Serializable;
026    
027    
028    /**
029     * An abstract {@code SessionDAO} implementation that performs some sanity checks on session creation and reading and
030     * allows for pluggable Session ID generation strategies if desired.  The {@code SessionDAO}
031     * {@link SessionDAO#update update} and {@link SessionDAO#delete delete} methods are left to
032     * subclasses.
033     * <h3>Session ID Generation</h3>
034     * This class also allows for plugging in a {@link SessionIdGenerator} for custom ID generation strategies.  This is
035     * optional, as the default generator is probably sufficient for most cases.  Subclass implementations that do use a
036     * generator (default or custom) will want to call the
037     * {@link #generateSessionId(org.apache.shiro.session.Session)} method from within their {@link #doCreate}
038     * implementations.
039     * <p/>
040     * Subclass implementations that rely on the EIS data store to generate the ID automatically (e.g. when the session
041     * ID is also an auto-generated primary key), they can simply ignore the {@code SessionIdGenerator} concept
042     * entirely and just return the data store's ID from the {@link #doCreate} implementation.
043     *
044     * @author The Apache Shiro Project (shiro-dev@incubator.apache.org)
045     * @since 1.0
046     */
047    public abstract class AbstractSessionDAO implements SessionDAO {
048    
049        /**
050         * Optional SessionIdGenerator instance available to subclasses via the
051         * {@link #generateSessionId(org.apache.shiro.session.Session)} method.
052         */
053        private SessionIdGenerator sessionIdGenerator;
054    
055        /**
056         * Default no-arg constructor that defaults the {@link #setSessionIdGenerator sessionIdGenerator} to be a
057         * {@link org.apache.shiro.session.mgt.eis.JavaUuidSessionIdGenerator}.
058         */
059        public AbstractSessionDAO() {
060            this.sessionIdGenerator = new JavaUuidSessionIdGenerator();
061        }
062    
063        /**
064         * Returns the {@code SessionIdGenerator} used by the {@link #generateSessionId(org.apache.shiro.session.Session)}
065         * method.  Unless overridden by the {@link #setSessionIdGenerator(SessionIdGenerator)} method, the default instance
066         * is a {@link JavaUuidSessionIdGenerator}.
067         *
068         * @return the {@code SessionIdGenerator} used by the {@link #generateSessionId(org.apache.shiro.session.Session)}
069         *         method.
070         */
071        public SessionIdGenerator getSessionIdGenerator() {
072            return sessionIdGenerator;
073        }
074    
075        /**
076         * Sets the {@code SessionIdGenerator} used by the {@link #generateSessionId(org.apache.shiro.session.Session)}
077         * method.  Unless overridden by this method, the default instance ss a {@link JavaUuidSessionIdGenerator}.
078         *
079         * @param sessionIdGenerator the {@code SessionIdGenerator} to use in the
080         *                           {@link #generateSessionId(org.apache.shiro.session.Session)} method.
081         */
082        public void setSessionIdGenerator(SessionIdGenerator sessionIdGenerator) {
083            this.sessionIdGenerator = sessionIdGenerator;
084        }
085    
086        /**
087         * Generates a new ID to be applied to the specified {@code session} instance.  This method is usually called
088         * from within a subclass's {@link #doCreate} implementation where they assign the returned id to the session
089         * instance and then create a record with this ID in the EIS data store.
090         * <p/>
091         * Subclass implementations backed by EIS data stores that auto-generate IDs during record creation, such as
092         * relational databases, don't need to use this method or the {@link #getSessionIdGenerator() sessionIdGenerator}
093         * attribute - they can simply return the data store's generated ID from the {@link #doCreate} implementation
094         * if desired.
095         * <p/>
096         * This implementation uses the {@link #setSessionIdGenerator configured} {@link SessionIdGenerator} to create
097         * the ID.
098         *
099         * @param session the new session instance for which an ID will be generated and then assigned
100         * @return the generated ID to assign
101         */
102        protected Serializable generateSessionId(Session session) {
103            if (this.sessionIdGenerator == null) {
104                String msg = "sessionIdGenerator attribute has not been configured.";
105                throw new IllegalStateException(msg);
106            }
107            return this.sessionIdGenerator.generateId(session);
108        }
109    
110        /**
111         * Creates the session by delegating EIS creation to subclasses via the {@link #doCreate} method, and then
112         * asserting that the returned sessionId is not null.
113         *
114         * @param session Session object to create in the EIS and associate with an ID.
115         */
116        public Serializable create(Session session) {
117            Serializable sessionId = doCreate(session);
118            verifySessionId(sessionId);
119            return sessionId;
120        }
121    
122        /**
123         * Ensures the sessionId returned from the subclass implementation of {@link #doCreate} is not null and not
124         * already in use.
125         *
126         * @param sessionId session id returned from the subclass implementation of {@link #doCreate}
127         */
128        private void verifySessionId(Serializable sessionId) {
129            if (sessionId == null) {
130                String msg = "sessionId returned from doCreate implementation is null.  Please verify the implementation.";
131                throw new IllegalStateException(msg);
132            }
133        }
134    
135        /**
136         * Utility method available to subclasses that wish to
137         * assign a generated session ID to the session instance directly.  This method is not used by the
138         * {@code AbstractSessionDAO} implementation directly, but it is provided so subclasses don't
139         * need to know the {@code Session} implementation if they don't need to.
140         * <p/>
141         * This default implementation casts the argument to a {@link SimpleSession}, Shiro's default EIS implementation.
142         *
143         * @param session   the session instance to which the sessionId will be applied
144         * @param sessionId the id to assign to the specified session instance.
145         */
146        protected void assignSessionId(Session session, Serializable sessionId) {
147            ((SimpleSession) session).setId(sessionId);
148        }
149    
150        /**
151         * Subclass hook to actually persist the given <tt>Session</tt> instance to the underlying EIS.
152         *
153         * @param session the Session instance to persist to the EIS.
154         * @return the id of the session created in the EIS (i.e. this is almost always a primary key and should be the
155         *         value returned from {@link org.apache.shiro.session.Session#getId() Session.getId()}.
156         */
157        protected abstract Serializable doCreate(Session session);
158    
159        /**
160         * Retrieves the Session object from the underlying EIS identified by <tt>sessionId</tt> by delegating to
161         * the {@link #doReadSession(java.io.Serializable)} method.  If {@code null} is returned from that method, an
162         * {@link UnknownSessionException} will be thrown.
163         *
164         * @param sessionId the id of the session to retrieve from the EIS.
165         * @return the session identified by <tt>sessionId</tt> in the EIS.
166         * @throws UnknownSessionException if the id specified does not correspond to any session in the EIS.
167         */
168        public Session readSession(Serializable sessionId) throws UnknownSessionException {
169            Session s = doReadSession(sessionId);
170            if (s == null) {
171                throw new UnknownSessionException("There is no session with id [" + sessionId + "]");
172            }
173            return s;
174        }
175    
176        /**
177         * Subclass implementation hook that retrieves the Session object from the underlying EIS or {@code null} if a
178         * session with that ID could not be found.
179         *
180         * @param sessionId the id of the <tt>Session</tt> to retrieve.
181         * @return the Session in the EIS identified by <tt>sessionId</tt> or {@code null} if a
182         *         session with that ID could not be found.
183         */
184        protected abstract Session doReadSession(Serializable sessionId);
185    
186    }