View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.shiro.session.mgt;
20  
21  import java.util.concurrent.Executors;
22  import java.util.concurrent.ScheduledExecutorService;
23  import java.util.concurrent.ThreadFactory;
24  import java.util.concurrent.TimeUnit;
25  import java.util.concurrent.atomic.AtomicInteger;
26  
27  import org.slf4j.Logger;
28  import org.slf4j.LoggerFactory;
29  
30  
31  /**
32   * SessionValidationScheduler implementation that uses a
33   * {@link ScheduledExecutorService} to call {@link ValidatingSessionManager#validateSessions()} every
34   * <em>{@link #getInterval interval}</em> milliseconds.
35   *
36   * @since 0.9
37   */
38  public class ExecutorServiceSessionValidationScheduler implements SessionValidationScheduler, Runnable {
39  
40      //TODO - complete JavaDoc
41  
42      /** Private internal log instance. */
43      private static final Logger log = LoggerFactory.getLogger(ExecutorServiceSessionValidationScheduler.class);
44  
45      ValidatingSessionManager sessionManager;
46      private ScheduledExecutorService service;
47      private long interval = DefaultSessionManager.DEFAULT_SESSION_VALIDATION_INTERVAL;
48      private boolean enabled = false;
49      private String threadNamePrefix = "SessionValidationThread-";
50  
51      public ExecutorServiceSessionValidationScheduler() {
52          super();
53      }
54  
55      public ExecutorServiceSessionValidationScheduler(ValidatingSessionManager sessionManager) {
56          this.sessionManager = sessionManager;
57      }
58  
59      public ValidatingSessionManager getSessionManager() {
60          return sessionManager;
61      }
62  
63      public void setSessionManager(ValidatingSessionManager sessionManager) {
64          this.sessionManager = sessionManager;
65      }
66  
67      public long getInterval() {
68          return interval;
69      }
70  
71      public void setInterval(long interval) {
72          this.interval = interval;
73      }
74  
75      public boolean isEnabled() {
76          return this.enabled;
77      }
78  
79      public void setThreadNamePrefix(String threadNamePrefix) {
80          this.threadNamePrefix = threadNamePrefix;
81      }
82  
83      public String getThreadNamePrefix() {
84          return this.threadNamePrefix;
85      }
86  
87      /**
88       * Creates a single thread {@link ScheduledExecutorService} to validate sessions at fixed intervals 
89       * and enables this scheduler. The executor is created as a daemon thread to allow JVM to shut down
90       */
91      //TODO Implement an integration test to test for jvm exit as part of the standalone example
92      // (so we don't have to change the unit test execution model for the core module)
93      public void enableSessionValidation() {
94          if (this.interval > 0l) {
95              this.service = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {  
96  	            private final AtomicInteger count = new AtomicInteger(1);
97  
98  	            public Thread newThread(Runnable r) {  
99  	                Thread thread = new Thread(r);  
100 	                thread.setDaemon(true);  
101 	                thread.setName(threadNamePrefix + count.getAndIncrement());
102 	                return thread;  
103 	            }  
104             });                  
105             this.service.scheduleAtFixedRate(this, interval, interval, TimeUnit.MILLISECONDS);
106         }
107         this.enabled = true;
108     }
109 
110     public void run() {
111         if (log.isDebugEnabled()) {
112             log.debug("Executing session validation...");
113         }
114         long startTime = System.currentTimeMillis();
115         this.sessionManager.validateSessions();
116         long stopTime = System.currentTimeMillis();
117         if (log.isDebugEnabled()) {
118             log.debug("Session validation completed successfully in " + (stopTime - startTime) + " milliseconds.");
119         }
120     }
121 
122     public void disableSessionValidation() {
123         if (this.service != null) {
124             this.service.shutdownNow();
125         }
126         this.enabled = false;
127     }
128 }