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
.jcr
;
19 import java
.text
.DateFormat
;
20 import java
.text
.ParseException
;
21 import java
.util
.Calendar
;
22 import java
.util
.Date
;
23 import java
.util
.GregorianCalendar
;
24 import java
.util
.Iterator
;
25 import java
.util
.List
;
27 import java
.util
.StringTokenizer
;
28 import java
.util
.TreeMap
;
30 import javax
.jcr
.NamespaceRegistry
;
31 import javax
.jcr
.Node
;
32 import javax
.jcr
.NodeIterator
;
33 import javax
.jcr
.Property
;
34 import javax
.jcr
.PropertyIterator
;
35 import javax
.jcr
.RepositoryException
;
36 import javax
.jcr
.Session
;
37 import javax
.jcr
.Value
;
38 import javax
.jcr
.nodetype
.NodeType
;
39 import javax
.jcr
.query
.Query
;
40 import javax
.jcr
.query
.QueryResult
;
42 import org
.apache
.commons
.logging
.Log
;
43 import org
.apache
.commons
.logging
.LogFactory
;
44 import org
.argeo
.ArgeoException
;
46 /** Utility methods to simplify common JCR operations. */
47 public class JcrUtils
{
48 private final static Log log
= LogFactory
.getLog(JcrUtils
.class);
51 * Queries one single node.
53 * @return one single node or null if none was found
54 * @throws ArgeoException
55 * if more than one node was found
57 public static Node
querySingleNode(Query query
) {
58 NodeIterator nodeIterator
;
60 QueryResult queryResult
= query
.execute();
61 nodeIterator
= queryResult
.getNodes();
62 } catch (RepositoryException e
) {
63 throw new ArgeoException("Cannot execute query " + query
, e
);
66 if (nodeIterator
.hasNext())
67 node
= nodeIterator
.nextNode();
71 if (nodeIterator
.hasNext())
72 throw new ArgeoException("Query returned more than one node.");
76 /** Removes forbidden characters from a path, replacing them with '_' */
77 public static String
removeForbiddenCharacters(String str
) {
78 return str
.replace('[', '_').replace(']', '_').replace('/', '_')
83 /** Retrieves the parent path of the provided path */
84 public static String
parentPath(String path
) {
86 throw new ArgeoException("Root path '/' has no parent path");
87 if (path
.charAt(0) != '/')
88 throw new ArgeoException("Path " + path
+ " must start with a '/'");
90 if (pathT
.charAt(pathT
.length() - 1) == '/')
91 pathT
= pathT
.substring(0, pathT
.length() - 2);
93 int index
= pathT
.lastIndexOf('/');
94 return pathT
.substring(0, index
);
97 /** The provided data as a path ('/' at the end, not the beginning) */
98 public static String
dateAsPath(Calendar cal
) {
99 return dateAsPath(cal
, false);
103 * The provided data as a path ('/' at the end, not the beginning)
108 * whether to add hour as well
110 public static String
dateAsPath(Calendar cal
, Boolean addHour
) {
111 StringBuffer buf
= new StringBuffer(14);
112 buf
.append('Y').append(cal
.get(Calendar
.YEAR
));// 5
114 int month
= cal
.get(Calendar
.MONTH
) + 1;
118 buf
.append(month
);// 3
120 int day
= cal
.get(Calendar
.DAY_OF_MONTH
);
123 buf
.append('D').append(day
);// 3
126 int hour
= cal
.get(Calendar
.HOUR_OF_DAY
);
129 buf
.append('H').append(hour
);// 3
132 return buf
.toString();
136 /** Converts in one call a string into a gregorian calendar. */
137 public static Calendar
parseCalendar(DateFormat dateFormat
, String value
) {
139 Date date
= dateFormat
.parse(value
);
140 Calendar calendar
= new GregorianCalendar();
141 calendar
.setTime(date
);
143 } catch (ParseException e
) {
144 throw new ArgeoException("Cannot parse " + value
145 + " with date format " + dateFormat
, e
);
150 /** Converts the FQDN of an host into a path (converts '.' into '/'). */
151 public static String
hostAsPath(String host
) {
152 // TODO : inverse order of the elements (to have org/argeo/test IO
154 return host
.replace('.', '/');
157 /** The last element of a path. */
158 public static String
lastPathElement(String path
) {
159 if (path
.charAt(path
.length() - 1) == '/')
160 throw new ArgeoException("Path " + path
+ " cannot end with '/'");
161 int index
= path
.lastIndexOf('/');
163 throw new ArgeoException("Cannot find last path element for "
165 return path
.substring(index
+ 1);
168 /** Creates the nodes making path, if they don't exist. */
169 public static Node
mkdirs(Session session
, String path
) {
170 return mkdirs(session
, path
, null, false);
173 /** Creates the nodes making path, if they don't exist. */
174 public static Node
mkdirs(Session session
, String path
, String type
,
175 Boolean versioning
) {
177 if (path
.equals('/'))
178 return session
.getRootNode();
180 if (session
.itemExists(path
)) {
181 Node node
= session
.getNode(path
);
184 && !type
.equals(node
.getPrimaryNodeType().getName()))
185 throw new ArgeoException("Node " + node
186 + " exists but is of type "
187 + node
.getPrimaryNodeType().getName()
188 + " not of type " + type
);
189 // TODO: check versioning
193 StringTokenizer st
= new StringTokenizer(path
, "/");
194 StringBuffer current
= new StringBuffer("/");
195 Node currentNode
= session
.getRootNode();
196 while (st
.hasMoreTokens()) {
197 String part
= st
.nextToken();
198 current
.append(part
).append('/');
199 if (!session
.itemExists(current
.toString())) {
201 currentNode
= currentNode
.addNode(part
, type
);
203 currentNode
= currentNode
.addNode(part
);
205 currentNode
.addMixin(NodeType
.MIX_VERSIONABLE
);
206 if (log
.isTraceEnabled())
207 log
.debug("Added folder " + part
+ " as " + current
);
209 currentNode
= (Node
) session
.getItem(current
.toString());
214 } catch (RepositoryException e
) {
215 throw new ArgeoException("Cannot mkdirs " + path
, e
);
220 * Safe and repository implementation independent registration of a
223 public static void registerNamespaceSafely(Session session
, String prefix
,
226 registerNamespaceSafely(session
.getWorkspace()
227 .getNamespaceRegistry(), prefix
, uri
);
228 } catch (RepositoryException e
) {
229 throw new ArgeoException("Cannot find namespace registry", e
);
234 * Safe and repository implementation independent registration of a
237 public static void registerNamespaceSafely(NamespaceRegistry nr
,
238 String prefix
, String uri
) {
240 String
[] prefixes
= nr
.getPrefixes();
241 for (String pref
: prefixes
)
242 if (pref
.equals(prefix
)) {
243 String registeredUri
= nr
.getURI(pref
);
244 if (!registeredUri
.equals(uri
))
245 throw new ArgeoException("Prefix " + pref
246 + " already registered for URI "
248 + " which is different from provided URI "
253 nr
.registerNamespace(prefix
, uri
);
254 } catch (RepositoryException e
) {
255 throw new ArgeoException("Cannot register namespace " + uri
256 + " under prefix " + prefix
, e
);
260 /** Recursively outputs the contents of the given node. */
261 public static void debug(Node node
) {
263 // First output the node path
264 log
.debug(node
.getPath());
265 // Skip the virtual (and large!) jcr:system subtree
266 if (node
.getName().equals("jcr:system")) {
270 // Then the children nodes (recursive)
271 NodeIterator it
= node
.getNodes();
272 while (it
.hasNext()) {
273 Node childNode
= it
.nextNode();
277 // Then output the properties
278 PropertyIterator properties
= node
.getProperties();
279 // log.debug("Property are : ");
281 while (properties
.hasNext()) {
282 Property property
= properties
.nextProperty();
283 if (property
.getDefinition().isMultiple()) {
284 // A multi-valued property, print all values
285 Value
[] values
= property
.getValues();
286 for (int i
= 0; i
< values
.length
; i
++) {
287 log
.debug(property
.getPath() + "="
288 + values
[i
].getString());
291 // A single-valued property
292 log
.debug(property
.getPath() + "=" + property
.getString());
295 } catch (Exception e
) {
296 log
.error("Could not debug " + node
, e
);
302 * Copies recursively the content of a node to another one. Mixin are NOT
305 public static void copy(Node fromNode
, Node toNode
) {
307 PropertyIterator pit
= fromNode
.getProperties();
308 properties
: while (pit
.hasNext()) {
309 Property fromProperty
= pit
.nextProperty();
310 String propertyName
= fromProperty
.getName();
311 if (toNode
.hasProperty(propertyName
)
312 && toNode
.getProperty(propertyName
).getDefinition()
316 toNode
.setProperty(fromProperty
.getName(),
317 fromProperty
.getValue());
320 NodeIterator nit
= fromNode
.getNodes();
321 while (nit
.hasNext()) {
322 Node fromChild
= nit
.nextNode();
323 Integer index
= fromChild
.getIndex();
324 String nodeRelPath
= fromChild
.getName() + "[" + index
+ "]";
326 if (toNode
.hasNode(nodeRelPath
))
327 toChild
= toNode
.getNode(nodeRelPath
);
329 toChild
= toNode
.addNode(fromChild
.getName(), fromChild
330 .getPrimaryNodeType().getName());
331 copy(fromChild
, toChild
);
333 } catch (RepositoryException e
) {
334 throw new ArgeoException("Cannot copy " + fromNode
+ " to "
340 * Check whether all first-level properties (except jcr:* properties) are
341 * equal. Skip jcr:* properties
343 public static Boolean
allPropertiesEquals(Node reference
, Node observed
,
344 Boolean onlyCommonProperties
) {
346 PropertyIterator pit
= reference
.getProperties();
347 props
: while (pit
.hasNext()) {
348 Property propReference
= pit
.nextProperty();
349 String propName
= propReference
.getName();
350 if (propName
.startsWith("jcr:"))
353 if (!observed
.hasProperty(propName
))
354 if (onlyCommonProperties
)
358 // TODO: deal with multiple property values?
359 if (!observed
.getProperty(propName
).getValue()
360 .equals(propReference
.getValue()))
364 } catch (RepositoryException e
) {
365 throw new ArgeoException("Cannot check all properties equals of "
366 + reference
+ " and " + observed
, e
);
370 public static Map
<String
, PropertyDiff
> diffProperties(Node reference
,
372 Map
<String
, PropertyDiff
> diffs
= new TreeMap
<String
, PropertyDiff
>();
373 diffPropertiesLevel(diffs
, null, reference
, observed
);
378 * Compare the properties of two nodes. Recursivity to child nodes is not
379 * yet supported. Skip jcr:* properties.
381 static void diffPropertiesLevel(Map
<String
, PropertyDiff
> diffs
,
382 String baseRelPath
, Node reference
, Node observed
) {
384 // check removed and modified
385 PropertyIterator pit
= reference
.getProperties();
386 props
: while (pit
.hasNext()) {
387 Property p
= pit
.nextProperty();
388 String name
= p
.getName();
389 if (name
.startsWith("jcr:"))
392 if (!observed
.hasProperty(name
)) {
393 String relPath
= propertyRelPath(baseRelPath
, name
);
394 PropertyDiff pDiff
= new PropertyDiff(PropertyDiff
.REMOVED
,
395 relPath
, p
.getValue(), null);
396 diffs
.put(relPath
, pDiff
);
400 Value referenceValue
= p
.getValue();
401 Value newValue
= observed
.getProperty(name
).getValue();
402 if (!referenceValue
.equals(newValue
)) {
403 String relPath
= propertyRelPath(baseRelPath
, name
);
404 PropertyDiff pDiff
= new PropertyDiff(
405 PropertyDiff
.MODIFIED
, relPath
, referenceValue
,
407 diffs
.put(relPath
, pDiff
);
412 pit
= observed
.getProperties();
413 props
: while (pit
.hasNext()) {
414 Property p
= pit
.nextProperty();
415 String name
= p
.getName();
416 if (name
.startsWith("jcr:"))
418 if (!reference
.hasProperty(name
)) {
419 String relPath
= propertyRelPath(baseRelPath
, name
);
420 PropertyDiff pDiff
= new PropertyDiff(PropertyDiff
.ADDED
,
421 relPath
, null, p
.getValue());
422 diffs
.put(relPath
, pDiff
);
425 } catch (RepositoryException e
) {
426 throw new ArgeoException("Cannot diff " + reference
+ " and "
432 * Compare only a restricted list of properties of two nodes. No
436 public static Map
<String
, PropertyDiff
> diffProperties(Node reference
,
437 Node observed
, List
<String
> properties
) {
438 Map
<String
, PropertyDiff
> diffs
= new TreeMap
<String
, PropertyDiff
>();
440 Iterator
<String
> pit
= properties
.iterator();
442 props
: while (pit
.hasNext()) {
443 String name
= pit
.next();
444 if (!reference
.hasProperty(name
)) {
445 if (!observed
.hasProperty(name
))
447 Value val
= observed
.getProperty(name
).getValue();
449 // empty String but not null
450 if ("".equals(val
.getString()))
452 } catch (Exception e
) {
453 // not parseable as String, silent
455 PropertyDiff pDiff
= new PropertyDiff(PropertyDiff
.ADDED
,
457 diffs
.put(name
, pDiff
);
458 } else if (!observed
.hasProperty(name
)) {
459 PropertyDiff pDiff
= new PropertyDiff(PropertyDiff
.REMOVED
,
460 name
, reference
.getProperty(name
).getValue(), null);
461 diffs
.put(name
, pDiff
);
463 Value referenceValue
= reference
.getProperty(name
)
465 Value newValue
= observed
.getProperty(name
).getValue();
466 if (!referenceValue
.equals(newValue
)) {
467 PropertyDiff pDiff
= new PropertyDiff(
468 PropertyDiff
.MODIFIED
, name
, referenceValue
,
470 diffs
.put(name
, pDiff
);
474 } catch (RepositoryException e
) {
475 throw new ArgeoException("Cannot diff " + reference
+ " and "
481 /** Builds a property relPath to be used in the diff. */
482 private static String
propertyRelPath(String baseRelPath
,
483 String propertyName
) {
484 if (baseRelPath
== null)
487 return baseRelPath
+ '/' + propertyName
;