1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 package org.apache.directory.server.core.api;
22
23
24 import java.io.File;
25
26 import net.sf.ehcache.Cache;
27 import net.sf.ehcache.CacheManager;
28 import net.sf.ehcache.Status;
29 import net.sf.ehcache.config.Configuration;
30 import net.sf.ehcache.config.ConfigurationFactory;
31
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
34
35
36
37
38
39
40
41
42
43
44
45
46 public class CacheService
47 {
48
49 private static final String DIRECTORY_CACHESERVICE_XML = "directory-cacheservice.xml";
50
51 private static final Logger LOG = LoggerFactory.getLogger( CacheService.class );
52
53
54 private CacheManager cacheManager;
55
56 private boolean initialized;
57
58 public CacheService()
59 {
60 }
61
62
63
64
65
66
67
68 public CacheService( CacheManager cachemanager )
69 {
70 this.cacheManager = cachemanager;
71 if ( cachemanager != null )
72 {
73 initialized = true;
74 }
75 }
76
77
78 public void initialize( InstanceLayout layout )
79 {
80 if ( initialized )
81 {
82 LOG.debug( "CacheService was already initialized, returning" );
83 return;
84 }
85
86 if ( ( cacheManager != null ) && ( cacheManager.getStatus() == Status.STATUS_ALIVE ) )
87 {
88 LOG.warn( "cache service was already initialized and is alive" );
89 initialized = true;
90 return;
91 }
92
93 File configFile = new File( layout.getConfDirectory(), DIRECTORY_CACHESERVICE_XML );
94
95 Configuration cc;
96
97 if ( !configFile.exists() )
98 {
99 LOG.info( "no custom cache configuration was set, loading the default cache configuration" );
100 cc = ConfigurationFactory.parseConfiguration( getClass().getClassLoader().getResource( DIRECTORY_CACHESERVICE_XML ) );
101 }
102 else
103 {
104 LOG.info( "loading cache configuration from the file {}", configFile );
105
106 cc = ConfigurationFactory.parseConfiguration( configFile );
107 }
108
109 cc.getDiskStoreConfiguration().setPath( layout.getCacheDirectory().getAbsolutePath() );
110 cacheManager = new CacheManager( cc );
111
112 initialized = true;
113 }
114
115
116 public void destroy()
117 {
118 if ( !initialized )
119 {
120 return;
121 }
122
123 LOG.info( "clearing all the caches" );
124
125 initialized = false;
126
127 cacheManager.clearAll();
128 cacheManager.shutdown();
129 }
130
131
132 public Cache getCache( String name )
133 {
134 if ( !initialized )
135 {
136 throw new IllegalStateException( "CacheService was not initialized" );
137 }
138
139 LOG.info( "fetching the cache named {}", name );
140
141 Cache cache = cacheManager.getCache( name );
142
143 if( cache == null )
144 {
145 cacheManager.addCache( name );
146 cache = cacheManager.getCache( name );
147 }
148
149 return cache;
150 }
151
152
153 public void remove( String name )
154 {
155 cacheManager.removeCache( name );
156 }
157
158
159 public void attach( Cache cache )
160 {
161 cacheManager.addCache( cache );
162 }
163
164 }