2 * Copyright (C) 2010 Mathieu Baudier <mbaudier@argeo.org>
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package org
.argeo
.jackrabbit
;
20 import java
.io
.IOException
;
21 import java
.io
.InputStream
;
22 import java
.util
.HashMap
;
24 import java
.util
.Properties
;
25 import java
.util
.TreeSet
;
26 import java
.util
.UUID
;
28 import javax
.jcr
.Credentials
;
29 import javax
.jcr
.LoginException
;
30 import javax
.jcr
.NoSuchWorkspaceException
;
31 import javax
.jcr
.Repository
;
32 import javax
.jcr
.RepositoryException
;
33 import javax
.jcr
.Session
;
34 import javax
.jcr
.Value
;
36 import org
.apache
.commons
.io
.FileUtils
;
37 import org
.apache
.commons
.io
.IOUtils
;
38 import org
.apache
.commons
.logging
.Log
;
39 import org
.apache
.commons
.logging
.LogFactory
;
40 import org
.apache
.jackrabbit
.core
.RepositoryImpl
;
41 import org
.apache
.jackrabbit
.core
.config
.RepositoryConfig
;
42 import org
.apache
.jackrabbit
.core
.config
.RepositoryConfigurationParser
;
43 import org
.apache
.jackrabbit
.jcr2dav
.Jcr2davRepositoryFactory
;
44 import org
.argeo
.ArgeoException
;
45 import org
.xml
.sax
.InputSource
;
48 * Wrapper around a Jackrabbit repository which allows to simplify configuration
49 * and intercept some actions. It exposes itself as a {@link Repository}.
51 public abstract class JackrabbitWrapper
implements Repository
{
52 private Log log
= LogFactory
.getLog(JackrabbitWrapper
.class);
55 private String uri
= null;
58 private RepositoryConfig repositoryConfig
;
59 private File homeDirectory
;
60 private Boolean inMemory
= false;
63 private Repository repository
;
65 private Boolean autocreateWorkspaces
= false;
68 * Empty constructor, {@link #init()} should be called after properties have
71 public JackrabbitWrapper() {
75 * Reads the configuration which will initialize a {@link RepositoryConfig}.
77 protected abstract InputStream
readConfiguration();
80 * Reads the variables which will initialize a {@link Properties}. Returns
81 * null by default, to be overridden.
83 * @return a new stream or null if no variables available
85 protected InputStream
readVariables() {
90 * Resolves ${} placeholders in the provided string. Based on system
91 * properties if no map is provided.
93 protected abstract String
resolvePlaceholders(String string
,
94 Map
<String
, String
> variables
);
98 long begin
= System
.currentTimeMillis();
100 if (repository
!= null) {
101 // we are just wrapping another repository
104 createJackrabbitRepository();
108 double duration
= ((double) (System
.currentTimeMillis() - begin
)) / 1000;
109 log
.info("Initialized Jackrabbit wrapper in " + duration
+ " s");
113 * Called after initialization of an already existing {@link Repository}
114 * which is being wrapped (e.g. in order to impact its data model). To be
115 * overridden, does nothing by default.
117 protected void postInitWrapped() {
122 * Called after initialization of a new {@link Repository} either local or
123 * remote. To be overridden, does nothing by default.
125 protected void postInitNew() {
129 /** Actually creates the new repository. */
130 protected void createJackrabbitRepository() {
131 long begin
= System
.currentTimeMillis();
132 InputStream configurationIn
= null;
134 if (uri
!= null && !uri
.trim().equals("")) {// remote
135 Map
<String
, String
> params
= new HashMap
<String
, String
>();
137 org
.apache
.jackrabbit
.commons
.JcrUtils
.REPOSITORY_URI
,
139 repository
= new Jcr2davRepositoryFactory()
140 .getRepository(params
);
141 if (repository
== null)
142 throw new ArgeoException("Remote Davex repository " + uri
144 double duration
= ((double) (System
.currentTimeMillis() - begin
)) / 1000;
145 log
.info("Created Jackrabbit repository in " + duration
146 + " s from URI " + uri
);
147 // we assume that the data model of the remote repository has
148 // been properly initialized
150 // force uri to null in order to optimize isRemote()
154 if (inMemory
&& getHomeDirectory().exists()) {
155 FileUtils
.deleteDirectory(getHomeDirectory());
156 log
.warn("Deleted Jackrabbit home directory "
157 + getHomeDirectory());
160 // process configuration file
161 Properties vars
= getConfigurationProperties();
162 configurationIn
= readConfiguration();
164 RepositoryConfigurationParser
.REPOSITORY_HOME_VARIABLE
,
165 getHomeDirectory().getCanonicalPath());
166 repositoryConfig
= RepositoryConfig
.create(new InputSource(
167 configurationIn
), vars
);
170 // Actual repository creation
172 repository
= RepositoryImpl
.create(repositoryConfig
);
174 double duration
= ((double) (System
.currentTimeMillis() - begin
)) / 1000;
175 if (log
.isDebugEnabled())
176 log
.debug("Created Jackrabbit repository in " + duration
177 + " s, home: " + getHomeDirectory());
179 } catch (Exception e
) {
180 throw new ArgeoException("Cannot create Jackrabbit repository "
181 + getHomeDirectory(), e
);
183 IOUtils
.closeQuietly(configurationIn
);
188 protected File
getHomeDirectory() {
190 if (homeDirectory
== null) {
192 homeDirectory
= new File(
193 System
.getProperty("java.io.tmpdir")
195 + System
.getProperty("user.name")
196 + File
.separator
+ "jackrabbit-"
197 + UUID
.randomUUID());
198 homeDirectory
.mkdirs();
199 // will it work if directory is not empty??
200 homeDirectory
.deleteOnExit();
204 return homeDirectory
.getCanonicalFile();
205 } catch (IOException e
) {
206 throw new ArgeoException("Cannot get canonical file for "
211 /** Shutdown the repository */
212 public void destroy() throws Exception
{
213 if (repository
!= null && repository
instanceof RepositoryImpl
) {
214 long begin
= System
.currentTimeMillis();
215 ((RepositoryImpl
) repository
).shutdown();
217 if (getHomeDirectory().exists()) {
218 FileUtils
.deleteDirectory(getHomeDirectory());
219 if (log
.isDebugEnabled())
220 log
.debug("Deleted Jackrabbit home directory "
221 + getHomeDirectory());
223 double duration
= ((double) (System
.currentTimeMillis() - begin
)) / 1000;
224 log
.info("Destroyed Jackrabbit repository in " + duration
225 + " s, home: " + getHomeDirectory());
230 * @deprecated explicitly declare {@link #destroy()} as destroy-method
233 public void dispose() throws Exception
{
234 log
.error("## Declare destroy-method=\"destroy\". in the Jackrabbit container bean");
242 /** Generates the properties to use in the configuration. */
243 protected Properties
getConfigurationProperties() {
244 InputStream propsIn
= null;
247 vars
= new Properties();
248 propsIn
= readVariables();
249 if (propsIn
!= null) {
252 // resolve system properties
253 for (Object key
: vars
.keySet()) {
254 // TODO: implement a smarter mechanism to resolve nested ${}
255 String newValue
= resolvePlaceholders(
256 vars
.getProperty(key
.toString()), null);
257 vars
.put(key
, newValue
);
259 // override with system properties
260 vars
.putAll(System
.getProperties());
262 if (log
.isTraceEnabled()) {
263 log
.trace("Jackrabbit config variables:");
264 for (Object key
: new TreeSet
<Object
>(vars
.keySet()))
265 log
.trace(key
+ "=" + vars
.getProperty(key
.toString()));
268 } catch (IOException e
) {
269 throw new ArgeoException("Cannot read configuration properties", e
);
271 IOUtils
.closeQuietly(propsIn
);
277 * DELEGATED JCR REPOSITORY METHODS
280 public String
getDescriptor(String key
) {
281 return getRepository().getDescriptor(key
);
284 public String
[] getDescriptorKeys() {
285 return getRepository().getDescriptorKeys();
288 /** Central login method */
289 public Session
login(Credentials credentials
, String workspaceName
)
290 throws LoginException
, NoSuchWorkspaceException
,
291 RepositoryException
{
294 session
= getRepository().login(credentials
, workspaceName
);
295 } catch (NoSuchWorkspaceException e
) {
296 if (autocreateWorkspaces
&& workspaceName
!= null)
297 session
= createWorkspaceAndLogsIn(credentials
, workspaceName
);
301 processNewSession(session
);
305 public Session
login() throws LoginException
, RepositoryException
{
306 return login(null, null);
309 public Session
login(Credentials credentials
) throws LoginException
,
310 RepositoryException
{
311 return login(credentials
, null);
314 public Session
login(String workspaceName
) throws LoginException
,
315 NoSuchWorkspaceException
, RepositoryException
{
316 return login(null, workspaceName
);
319 /** Called after a session has been created, does nothing by default. */
320 protected void processNewSession(Session session
) {
323 public Boolean
isRemote() {
327 /** Wraps access to the repository, making sure it is available. */
328 protected Repository
getRepository() {
329 if (repository
== null) {
330 throw new ArgeoException(
331 "No repository initialized."
332 + " Was the init() method called?"
333 + " The dispose() method should also be called on shutdown.");
339 * Logs in to the default workspace, creates the required workspace, logs
340 * out, logs in to the required workspace.
342 protected Session
createWorkspaceAndLogsIn(Credentials credentials
,
343 String workspaceName
) throws RepositoryException
{
344 if (workspaceName
== null)
345 throw new ArgeoException("No workspace specified.");
346 Session session
= getRepository().login(credentials
);
347 session
.getWorkspace().createWorkspace(workspaceName
);
349 return getRepository().login(credentials
, workspaceName
);
352 public boolean isStandardDescriptor(String key
) {
353 return getRepository().isStandardDescriptor(key
);
356 public boolean isSingleValueDescriptor(String key
) {
357 return getRepository().isSingleValueDescriptor(key
);
360 public Value
getDescriptorValue(String key
) {
361 return getRepository().getDescriptorValue(key
);
364 public Value
[] getDescriptorValues(String key
) {
365 return getRepository().getDescriptorValues(key
);
372 public void setHomeDirectory(File homeDirectory
) {
373 this.homeDirectory
= homeDirectory
;
376 public void setInMemory(Boolean inMemory
) {
377 this.inMemory
= inMemory
;
380 public void setUri(String uri
) {
384 public void setRepository(Repository repository
) {
385 this.repository
= repository
;