KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > ejb > base > sfsb > AbstractFileStoreManager


1 /*
2  * The contents of this file are subject to the terms
3  * of the Common Development and Distribution License
4  * (the License). You may not use this file except in
5  * compliance with the License.
6  *
7  * You can obtain a copy of the license at
8  * https://glassfish.dev.java.net/public/CDDLv1.0.html or
9  * glassfish/bootstrap/legal/CDDLv1.0.txt.
10  * See the License for the specific language governing
11  * permissions and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL
14  * Header Notice in each file and include the License file
15  * at glassfish/bootstrap/legal/CDDLv1.0.txt.
16  * If applicable, add the following below the CDDL Header,
17  * with the fields enclosed by brackets [] replaced by
18  * you own identifying information:
19  * "Portions Copyrighted [year] [name of copyright owner]"
20  *
21  * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
22  */

23
24 package com.sun.ejb.base.sfsb;
25
26 import java.io.File JavaDoc;
27 import java.io.IOException JavaDoc;
28 import java.io.FileInputStream JavaDoc;
29 import java.io.FileOutputStream JavaDoc;
30 import java.io.ObjectInputStream JavaDoc;
31 import java.io.BufferedInputStream JavaDoc;
32 import java.io.BufferedOutputStream JavaDoc;
33 import java.io.ObjectOutputStream JavaDoc;
34 import java.io.StringWriter JavaDoc;
35 import java.io.PrintWriter JavaDoc;
36
37 import java.util.Map JavaDoc;
38 import java.util.HashMap JavaDoc;
39 import java.util.Iterator JavaDoc;
40
41 import java.util.logging.*;
42 import com.sun.logging.*;
43
44 import com.sun.ejb.spi.sfsb.SFSBBeanState;
45 import com.sun.ejb.spi.sfsb.SFSBStoreManager;
46 import com.sun.ejb.spi.sfsb.SFSBStoreManagerException;
47 import com.sun.ejb.spi.sfsb.SFSBStoreManagerConstants;
48 import com.sun.ejb.spi.sfsb.SFSBUUIDUtil;
49
50 import com.sun.ejb.spi.monitorable.sfsb.MonitorableSFSBStore;
51
52 import com.sun.appserv.util.cache.CacheListener;
53 import com.sun.ejb.containers.util.cache.PassivatedSessionCache;
54
55 /**
56  * @author Mahesh Kannan
57  */

58  
59 public abstract class AbstractFileStoreManager
60     implements SFSBStoreManager, MonitorableSFSBStore,
61         CacheListener
62 {
63     protected static Logger _logger =
64         LogDomains.getLogger(LogDomains.EJB_LOGGER);
65
66     protected File JavaDoc baseDir;
67     protected String JavaDoc storeManagerName;
68
69     protected int passivationTimeoutInSeconds;
70
71     private int loadCount;
72     private int loadSuccessCount;
73     private int loadErrorCount;
74     private int storeCount;
75     private int storeSuccessCount;
76     private int storeErrorCount;
77     private int expiredSessionCount;
78
79     private boolean shutdown;
80     private PassivatedSessionCache passivatedSessions;
81
82     private Level TRACE_LEVEL = Level.FINE;
83     private ClassLoader JavaDoc classLoader;
84
85     /**
86      * No arg constructor
87      */

88     public AbstractFileStoreManager() {
89     }
90
91     /****************************************************/
92     /**** Implementation of SFSBStoreManager methods ****/
93     /****************************************************/
94
95     public void initSessionStore(Map JavaDoc storeEnv) {
96
97         String JavaDoc baseDirName = (String JavaDoc) storeEnv.get(
98                 SFSBStoreManagerConstants.PASSIVATION_DIRECTORY_NAME);
99         if (baseDirName == null) {
100             baseDirName = ".";
101         }
102         baseDir = new File JavaDoc(baseDirName);
103
104         this.storeManagerName = (String JavaDoc) storeEnv.get(
105         SFSBStoreManagerConstants.STORE_MANAGER_NAME);
106
107         this.classLoader = (ClassLoader JavaDoc) storeEnv.get(
108         SFSBStoreManagerConstants.CLASS_LOADER);
109
110         try {
111             Integer JavaDoc sessionTimeout = (Integer JavaDoc) storeEnv.get(
112                     SFSBStoreManagerConstants.SESSION_TIMEOUT_IN_SECONDS);
113             passivationTimeoutInSeconds = sessionTimeout.intValue();
114         } catch (Exception JavaDoc ex) {
115         }
116
117         try {
118             if ((baseDir.mkdirs() == false) && (!baseDir.isDirectory())) {
119         _logger.log(Level.WARNING, "ejb.sfsb_storemgr_mdirs_failed",
120             new Object JavaDoc[] {baseDirName});
121         }
122
123             passivatedSessions = new PassivatedSessionCache(
124             passivationTimeoutInSeconds * 1000);
125             passivatedSessions.init(8192, null);
126             passivatedSessions.addCacheListener(this);
127             onInitialization();
128         } catch (Exception JavaDoc ex) {
129         _logger.log(Level.WARNING, "ejb.sfsb_storemgr_init_failed",
130                     new Object JavaDoc[] {baseDirName});
131         _logger.log(Level.WARNING, "ejb.sfsb_storemgr_init_exception", ex);
132         }
133
134     }
135     
136     protected void onInitialization() {
137     }
138
139     public SFSBBeanState getState(Object JavaDoc sessionKey) {
140
141         String JavaDoc fileName = sessionKey.toString();
142         SFSBBeanState beanState = null;
143
144     if(_logger.isLoggable(TRACE_LEVEL)) {
145         _logger.log(TRACE_LEVEL, "[SFSBStore] Attempting to load session: "
146                 + sessionKey);
147     }
148
149         if (passivatedSessions.remove(fileName) == null) {
150         if(_logger.isLoggable(TRACE_LEVEL)) {
151         _logger.log(TRACE_LEVEL, "[SFSBStore] Could not find "
152             + "state for session: " + sessionKey);
153         }
154             return null;
155         }
156
157         File JavaDoc file = new File JavaDoc(baseDir, fileName);
158         if (file.exists()) {
159             int dataSize = (int) file.length();
160             byte[] data = new byte[dataSize];
161             BufferedInputStream JavaDoc bis = null;
162             FileInputStream JavaDoc fis = null;
163             try {
164                 loadCount++;
165                 fis = new FileInputStream JavaDoc(file);
166                 bis = new BufferedInputStream JavaDoc(fis);
167                 int offset = 0;
168                 for (int toRead = dataSize; toRead > 0; ) {
169                     int count = bis.read(data, offset, toRead);
170                     offset += count;
171                     toRead -= count;
172                 }
173         
174                 beanState = new SFSBBeanState(sessionKey, -1, false, data);
175                 loadSuccessCount++;
176         if(_logger.isLoggable(TRACE_LEVEL)) {
177             _logger.log(TRACE_LEVEL, "[SFSBStore] Successfully Loaded "
178                 + "session: " + sessionKey);
179         }
180             } catch (Exception JavaDoc ex) {
181                 loadErrorCount++;
182                 _logger.log(Level.WARNING,
183                     "ejb.sfsb_storemgr_loadstate_failed",
184                     new Object JavaDoc[] {fileName});
185                 _logger.log(Level.WARNING,
186                     "ejb.sfsb_storemgr_loadstate_exception", ex);
187                 remove(sessionKey);
188             } finally {
189                 try {
190             bis.close();
191         } catch (Exception JavaDoc ex) {
192             _logger.log(Level.FINE, "Error while closing buffered input stream", ex);
193         }
194                 try {
195             fis.close();
196         } catch (Exception JavaDoc ex) {
197             _logger.log(Level.FINE, "Error while closing file input stream", ex);
198         }
199             }
200         } else {
201         if(_logger.isLoggable(TRACE_LEVEL)) {
202         _logger.log(TRACE_LEVEL, "[SFSBStore] Could not find passivated "
203             + "file for: " + sessionKey);
204         }
205     }
206         return beanState;
207     }
208      
209     public void checkpointSave(SFSBBeanState[] beanStates,
210             boolean transactionFlag)
211     {
212         //Not yet implemented
213
}
214  
215     public void passivateSave(SFSBBeanState beanState) {
216         saveState(beanState, true);
217     }
218
219     public void remove(Object JavaDoc sessionKey) {
220         try {
221             passivatedSessions.remove(sessionKey);
222             removeFile(new File JavaDoc(baseDir, sessionKey.toString()));
223         } catch (Exception JavaDoc ex) {
224             _logger.log(Level.WARNING,
225                 "ejb.sfsb_storemgr_removestate_failed",
226                 new Object JavaDoc[] {sessionKey.toString()});
227             _logger.log(Level.WARNING,
228                 "ejb.sfsb_storemgr_removestate_exception", ex);
229         }
230     }
231       
232     public void removeExpired() {
233         if( shutdown ) {
234         if(_logger.isLoggable(TRACE_LEVEL)) {
235                 _logger.log(TRACE_LEVEL, "[SFSBStore] Server is being shutdown hence "
236                     + "method cannot be executed" );
237         }
238             return;
239         }
240         passivatedSessions.trimExpiredEntries(Integer.MAX_VALUE);
241     }
242       
243     public void removeAll() {
244         try {
245         String JavaDoc[] fileNames = baseDir.list();
246         for (int i=0; i<fileNames.length; i++) {
247                 remove(fileNames[i]);
248         }
249
250         if (baseDir.delete() == false) {
251         Object JavaDoc[] params = {baseDir.getAbsolutePath()};
252         _logger.log(Level.WARNING,
253             "ejb.sfsb_storemgr_removedir_failed", params);
254         }
255         } catch (Throwable JavaDoc th) {
256             _logger.log(Level.WARNING, "ejb.sfsb_storemgr_removeall_exception", th);
257         }
258     }
259       
260     public void shutdown() {
261         shutdown = true;
262     }
263       
264     public MonitorableSFSBStore getMonitorableSFSBStore() {
265         return this;
266     }
267
268     /***************************************************************/
269     /************** Methods on MonitorableSFSBCache **************/
270     /***************************************************************/
271
272     public int getCurrentSize() {
273         return passivatedSessions.getEntryCount();
274     }
275
276     public int getLoadCount() {
277         return loadCount;
278     }
279     
280     public int getLoadSuccessCount() {
281         return loadSuccessCount;
282     }
283     
284     public int getLoadErrorCount() {
285         return loadErrorCount;
286     }
287
288     public int getPassivationCount() {
289         return storeCount;
290     }
291     
292     public int getPassivationSuccessCount() {
293         return storeSuccessCount;
294     }
295     
296     public int getPassivationErrorCount() {
297         return storeErrorCount;
298     }
299
300     public int getCheckpointCount() {
301         return storeCount;
302     }
303     
304     public int getCheckpointSuccessCount() {
305         return storeSuccessCount;
306     }
307     
308     public int getCheckpointErrorCount() {
309         return storeErrorCount;
310     }
311
312     public int getExpiredSessionCount() {
313         return expiredSessionCount;
314     }
315
316
317     /***************************************************************/
318     /********************* Internal methods **********************/
319     /***************************************************************/
320
321     private void saveState(SFSBBeanState beanState, boolean isPassivated) {
322
323         Object JavaDoc sessionKey = beanState.getId();
324         String JavaDoc fileName = sessionKey.toString();
325
326     if(_logger.isLoggable(TRACE_LEVEL)) {
327         _logger.log(TRACE_LEVEL, "[SFSBStore] Attempting to save session: "
328             + sessionKey);
329     }
330         File JavaDoc file = null;
331
332         BufferedOutputStream JavaDoc bos = null;
333         FileOutputStream JavaDoc fos = null;
334
335         try {
336             storeCount++;
337             file = new File JavaDoc(baseDir, fileName);
338             fos = new FileOutputStream JavaDoc(file);
339             bos = new BufferedOutputStream JavaDoc(fos);
340             byte[] data = beanState.getState();
341             bos.write(data, 0, data.length);
342
343             storeSuccessCount++;
344             if (isPassivated) {
345                 passivatedSessions.put(fileName, new Long JavaDoc(beanState.getLastAccess()));
346         if(_logger.isLoggable(TRACE_LEVEL)) {
347             _logger.log(TRACE_LEVEL, "[SFSBStore] Successfully saved session: "
348                 + sessionKey);
349         }
350             }
351         } catch (Exception JavaDoc ex) {
352             storeErrorCount++;
353         _logger.log(Level.WARNING, "ejb.sfsb_storemgr_savestate_failed",
354                 new Object JavaDoc[] {fileName});
355         _logger.log(Level.WARNING, "ejb.sfsb_storemgr_savestate_exception", ex);
356             try { removeFile(file); } catch (Exception JavaDoc ex1) {}
357             String JavaDoc errMsg = "Could not save session: " + beanState.getId();
358             throw new SFSBStoreManagerException(errMsg, ex);
359         } finally {
360             try {
361         if (bos != null) bos.close();
362         } catch (Exception JavaDoc ex) {
363         _logger.log(Level.FINE, "Error while closing buffered output stream", ex);
364         }
365             try {
366         if (fos != null) fos.close();
367         } catch (Exception JavaDoc ex) {
368         _logger.log(Level.FINE, "Error while closing file output stream", ex);
369         }
370         }
371     }
372       
373     private void removeFile(File JavaDoc file) {
374         final File JavaDoc localFile = file;
375         Boolean JavaDoc temp = (Boolean JavaDoc) java.security.AccessController.doPrivileged(
376             new java.security.PrivilegedAction JavaDoc() {
377                 public java.lang.Object JavaDoc run() {
378                     return (new Boolean JavaDoc(localFile.delete()));
379                 }
380             }
381         );
382         boolean success = temp.booleanValue();
383         if (!success) {
384             _logger.log(Level.WARNING, "ejb.sfsb_storemgr_removestate_failed",
385                 new Object JavaDoc[] {file.getName()});
386         } else {
387         if(_logger.isLoggable(TRACE_LEVEL)) {
388         _logger.log(TRACE_LEVEL, "[SFSBStore] Removed session: "
389             + file.getName());
390             }
391     }
392     }
393
394     protected void addPassivatedSession(String JavaDoc fileName, long lastAccessTime) {
395         passivatedSessions.add(fileName, new Long JavaDoc(lastAccessTime));
396     }
397
398     /****************************************************/
399     /**** Implementation of CacheListener method ****/
400     /****************************************************/
401     public void trimEvent(Object JavaDoc sessionKey, Object JavaDoc lastAccessedAt) {
402         //This can only happen through trimExpiredSessions
403
//So it is already running in an async thread
404
if(_logger.isLoggable(TRACE_LEVEL)) {
405         _logger.log(TRACE_LEVEL, "[SFSBStore] Removing expired session: "
406                 + sessionKey);
407     }
408         remove(sessionKey);
409         expiredSessionCount++;
410     }
411
412     protected ClassLoader JavaDoc getClassLoader() {
413     return this.classLoader;
414     }
415
416 }
417
Popular Tags