2 * Copyright (C) 2007-2012 Argeo GmbH
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.
16 package org
.argeo
.jcr
;
18 import java
.io
.ByteArrayInputStream
;
19 import java
.io
.ByteArrayOutputStream
;
21 import java
.io
.FileInputStream
;
22 import java
.io
.IOException
;
23 import java
.io
.InputStream
;
24 import java
.net
.MalformedURLException
;
26 import java
.security
.Principal
;
27 import java
.text
.DateFormat
;
28 import java
.text
.ParseException
;
29 import java
.util
.ArrayList
;
30 import java
.util
.Calendar
;
31 import java
.util
.Collections
;
32 import java
.util
.Date
;
33 import java
.util
.GregorianCalendar
;
34 import java
.util
.Iterator
;
35 import java
.util
.List
;
37 import java
.util
.TreeMap
;
39 import javax
.jcr
.Binary
;
40 import javax
.jcr
.NamespaceRegistry
;
41 import javax
.jcr
.NoSuchWorkspaceException
;
42 import javax
.jcr
.Node
;
43 import javax
.jcr
.NodeIterator
;
44 import javax
.jcr
.Property
;
45 import javax
.jcr
.PropertyIterator
;
46 import javax
.jcr
.PropertyType
;
47 import javax
.jcr
.Repository
;
48 import javax
.jcr
.RepositoryException
;
49 import javax
.jcr
.Session
;
50 import javax
.jcr
.Value
;
51 import javax
.jcr
.Workspace
;
52 import javax
.jcr
.nodetype
.NodeType
;
53 import javax
.jcr
.observation
.EventListener
;
54 import javax
.jcr
.query
.Query
;
55 import javax
.jcr
.query
.QueryResult
;
56 import javax
.jcr
.security
.AccessControlEntry
;
57 import javax
.jcr
.security
.AccessControlList
;
58 import javax
.jcr
.security
.AccessControlManager
;
59 import javax
.jcr
.security
.AccessControlPolicy
;
60 import javax
.jcr
.security
.AccessControlPolicyIterator
;
61 import javax
.jcr
.security
.Privilege
;
63 import org
.apache
.commons
.io
.IOUtils
;
64 import org
.apache
.commons
.logging
.Log
;
65 import org
.apache
.commons
.logging
.LogFactory
;
66 import org
.argeo
.ArgeoException
;
67 import org
.argeo
.ArgeoMonitor
;
68 import org
.argeo
.util
.security
.DigestUtils
;
69 import org
.argeo
.util
.security
.SimplePrincipal
;
71 /** Utility methods to simplify common JCR operations. */
72 public class JcrUtils
implements ArgeoJcrConstants
{
74 final private static Log log
= LogFactory
.getLog(JcrUtils
.class);
77 * Not complete yet. See
78 * http://www.day.com/specs/jcr/2.0/3_Repository_Model.html#3.2.2%20Local
81 public final static char[] INVALID_NAME_CHARACTERS
= { '/', ':', '[', ']',
87 /** Prevents instantiation */
92 * Queries one single node.
94 * @return one single node or null if none was found
95 * @throws ArgeoException
96 * if more than one node was found
98 public static Node
querySingleNode(Query query
) {
99 NodeIterator nodeIterator
;
101 QueryResult queryResult
= query
.execute();
102 nodeIterator
= queryResult
.getNodes();
103 } catch (RepositoryException e
) {
104 throw new ArgeoException("Cannot execute query " + query
, e
);
107 if (nodeIterator
.hasNext())
108 node
= nodeIterator
.nextNode();
112 if (nodeIterator
.hasNext())
113 throw new ArgeoException("Query returned more than one node.");
117 /** Retrieves the node name from the provided path */
118 public static String
nodeNameFromPath(String path
) {
119 if (path
.equals("/"))
121 if (path
.charAt(0) != '/')
122 throw new ArgeoException("Path " + path
+ " must start with a '/'");
124 if (pathT
.charAt(pathT
.length() - 1) == '/')
125 pathT
= pathT
.substring(0, pathT
.length() - 2);
127 int index
= pathT
.lastIndexOf('/');
128 return pathT
.substring(index
+ 1);
131 /** Retrieves the parent path of the provided path */
132 public static String
parentPath(String path
) {
133 if (path
.equals("/"))
134 throw new ArgeoException("Root path '/' has no parent path");
135 if (path
.charAt(0) != '/')
136 throw new ArgeoException("Path " + path
+ " must start with a '/'");
138 if (pathT
.charAt(pathT
.length() - 1) == '/')
139 pathT
= pathT
.substring(0, pathT
.length() - 2);
141 int index
= pathT
.lastIndexOf('/');
142 return pathT
.substring(0, index
);
145 /** The provided data as a path ('/' at the end, not the beginning) */
146 public static String
dateAsPath(Calendar cal
) {
147 return dateAsPath(cal
, false);
151 * Creates a deep path based on a URL:
152 * http://subdomain.example.com/to/content?args =>
153 * com/example/subdomain/to/content
155 public static String
urlAsPath(String url
) {
157 URL u
= new URL(url
);
158 StringBuffer path
= new StringBuffer(url
.length());
160 path
.append(hostAsPath(u
.getHost()));
161 // we don't put port since it may not always be there and may change
162 path
.append(u
.getPath());
163 return path
.toString();
164 } catch (MalformedURLException e
) {
165 throw new ArgeoException("Cannot generate URL path for " + url
, e
);
169 /** Set the {@link NodeType#NT_ADDRESS} properties based on this URL. */
170 public static void urlToAddressProperties(Node node
, String url
) {
172 URL u
= new URL(url
);
173 node
.setProperty(Property
.JCR_PROTOCOL
, u
.getProtocol());
174 node
.setProperty(Property
.JCR_HOST
, u
.getHost());
175 node
.setProperty(Property
.JCR_PORT
, Integer
.toString(u
.getPort()));
176 node
.setProperty(Property
.JCR_PATH
, normalizePath(u
.getPath()));
177 } catch (Exception e
) {
178 throw new ArgeoException("Cannot set URL " + url
179 + " as nt:address properties", e
);
183 /** Build URL based on the {@link NodeType#NT_ADDRESS} properties. */
184 public static String
urlFromAddressProperties(Node node
) {
187 node
.getProperty(Property
.JCR_PROTOCOL
).getString(), node
188 .getProperty(Property
.JCR_HOST
).getString(),
189 (int) node
.getProperty(Property
.JCR_PORT
).getLong(), node
190 .getProperty(Property
.JCR_PATH
).getString());
192 } catch (Exception e
) {
193 throw new ArgeoException(
194 "Cannot get URL from nt:address properties of " + node
, e
);
202 /** Make sure that: starts with '/', do not end with '/', do not have '//' */
203 public static String
normalizePath(String path
) {
204 List
<String
> tokens
= tokenize(path
);
205 StringBuffer buf
= new StringBuffer(path
.length());
206 for (String token
: tokens
) {
210 return buf
.toString();
214 * Creates a path from a FQDN, inverting the order of the component:
215 * www.argeo.org => org.argeo.www
217 public static String
hostAsPath(String host
) {
218 StringBuffer path
= new StringBuffer(host
.length());
219 String
[] hostTokens
= host
.split("\\.");
220 for (int i
= hostTokens
.length
- 1; i
>= 0; i
--) {
221 path
.append(hostTokens
[i
]);
225 return path
.toString();
229 * Creates a path from a UUID (e.g. 6ebda899-217d-4bf1-abe4-2839085c8f3c =>
230 * 6ebda899-217d/4bf1/abe4/2839085c8f3c/). '/' at the end, not the beginning
232 public static String
uuidAsPath(String uuid
) {
233 StringBuffer path
= new StringBuffer(uuid
.length());
234 String
[] tokens
= uuid
.split("-");
235 for (int i
= 0; i
< tokens
.length
; i
++) {
236 path
.append(tokens
[i
]);
240 return path
.toString();
244 * The provided data as a path ('/' at the end, not the beginning)
249 * whether to add hour as well
251 public static String
dateAsPath(Calendar cal
, Boolean addHour
) {
252 StringBuffer buf
= new StringBuffer(14);
254 buf
.append(cal
.get(Calendar
.YEAR
));
257 int month
= cal
.get(Calendar
.MONTH
) + 1;
264 int day
= cal
.get(Calendar
.DAY_OF_MONTH
);
272 int hour
= cal
.get(Calendar
.HOUR_OF_DAY
);
279 return buf
.toString();
283 /** Converts in one call a string into a gregorian calendar. */
284 public static Calendar
parseCalendar(DateFormat dateFormat
, String value
) {
286 Date date
= dateFormat
.parse(value
);
287 Calendar calendar
= new GregorianCalendar();
288 calendar
.setTime(date
);
290 } catch (ParseException e
) {
291 throw new ArgeoException("Cannot parse " + value
292 + " with date format " + dateFormat
, e
);
297 /** The last element of a path. */
298 public static String
lastPathElement(String path
) {
299 if (path
.charAt(path
.length() - 1) == '/')
300 throw new ArgeoException("Path " + path
+ " cannot end with '/'");
301 int index
= path
.lastIndexOf('/');
304 return path
.substring(index
+ 1);
308 * Call {@link Node#getName()} without exceptions (useful in super
311 public static String
getNameQuietly(Node node
) {
313 return node
.getName();
314 } catch (RepositoryException e
) {
315 throw new ArgeoException("Cannot get name from " + node
, e
);
320 * Call {@link Node#getProperty(String)} without exceptions (useful in super
323 public static String
getStringPropertyQuietly(Node node
, String propertyName
) {
325 return node
.getProperty(propertyName
).getString();
326 } catch (RepositoryException e
) {
327 throw new ArgeoException("Cannot get name from " + node
, e
);
332 * Routine that get the child with this name, adding id it does not already
335 public static Node
getOrAdd(Node parent
, String childName
,
336 String childPrimaryNodeType
) throws RepositoryException
{
337 return parent
.hasNode(childName
) ? parent
.getNode(childName
) : parent
338 .addNode(childName
, childPrimaryNodeType
);
342 * Routine that get the child with this name, adding id it does not already
345 public static Node
getOrAdd(Node parent
, String childName
)
346 throws RepositoryException
{
347 return parent
.hasNode(childName
) ? parent
.getNode(childName
) : parent
351 /** Convert a {@link NodeIterator} to a list of {@link Node} */
352 public static List
<Node
> nodeIteratorToList(NodeIterator nodeIterator
) {
353 List
<Node
> nodes
= new ArrayList
<Node
>();
354 while (nodeIterator
.hasNext()) {
355 nodes
.add(nodeIterator
.nextNode());
365 * Concisely get the string value of a property or null if this node doesn't
368 public static String
get(Node node
, String propertyName
) {
370 if (!node
.hasProperty(propertyName
))
372 return node
.getProperty(propertyName
).getString();
373 } catch (RepositoryException e
) {
374 throw new ArgeoException("Cannot get property " + propertyName
379 /** Concisely get the boolean value of a property */
380 public static Boolean
check(Node node
, String propertyName
) {
382 return node
.getProperty(propertyName
).getBoolean();
383 } catch (RepositoryException e
) {
384 throw new ArgeoException("Cannot get property " + propertyName
389 /** Concisely get the bytes array value of a property */
390 public static byte[] getBytes(Node node
, String propertyName
) {
392 return getBinaryAsBytes(node
.getProperty(propertyName
));
393 } catch (RepositoryException e
) {
394 throw new ArgeoException("Cannot get property " + propertyName
399 /** Creates the nodes making path, if they don't exist. */
400 public static Node
mkdirs(Session session
, String path
) {
401 return mkdirs(session
, path
, null, null, false);
405 * use {@link #mkdirs(Session, String, String, String, Boolean)} instead.
410 public static Node
mkdirs(Session session
, String path
, String type
,
411 Boolean versioning
) {
412 return mkdirs(session
, path
, type
, type
, false);
417 * the type of the leaf node
419 public static Node
mkdirs(Session session
, String path
, String type
) {
420 return mkdirs(session
, path
, type
, null, false);
424 * Create sub nodes relative to a parent node
427 * the type of the leaf node
429 public static Node
mkdirs(Node parentNode
, String relativePath
,
431 return mkdirs(parentNode
, relativePath
, nodeType
, null);
435 * Create sub nodes relative to a parent node
438 * the type of the leaf node
440 public static Node
mkdirs(Node parentNode
, String relativePath
,
441 String nodeType
, String intermediaryNodeType
) {
442 List
<String
> tokens
= tokenize(relativePath
);
443 Node currParent
= parentNode
;
445 for (int i
= 0; i
< tokens
.size(); i
++) {
446 String name
= tokens
.get(i
);
447 if (currParent
.hasNode(name
)) {
448 currParent
= currParent
.getNode(name
);
450 if (i
!= (tokens
.size() - 1)) {// intermediary
451 currParent
= currParent
.addNode(name
,
452 intermediaryNodeType
);
454 currParent
= currParent
.addNode(name
, nodeType
);
459 } catch (RepositoryException e
) {
460 throw new ArgeoException("Cannot mkdirs relative path "
461 + relativePath
+ " from " + parentNode
, e
);
466 * Synchronized and save is performed, to avoid race conditions in
467 * initializers leading to duplicate nodes.
469 public synchronized static Node
mkdirsSafe(Session session
, String path
,
472 if (session
.hasPendingChanges())
473 throw new ArgeoException(
474 "Session has pending changes, save them first.");
475 Node node
= mkdirs(session
, path
, type
);
478 } catch (RepositoryException e
) {
479 discardQuietly(session
);
480 throw new ArgeoException("Cannot safely make directories", e
);
484 public synchronized static Node
mkdirsSafe(Session session
, String path
) {
485 return mkdirsSafe(session
, path
, null);
489 * Creates the nodes making path, if they don't exist. This is up to the
490 * caller to save the session. Use with caution since it can create
491 * duplicate nodes if used concurrently.
493 public static Node
mkdirs(Session session
, String path
, String type
,
494 String intermediaryNodeType
, Boolean versioning
) {
496 if (path
.equals('/'))
497 return session
.getRootNode();
499 if (session
.itemExists(path
)) {
500 Node node
= session
.getNode(path
);
502 if (type
!= null && !node
.isNodeType(type
)
503 && !node
.getPath().equals("/"))
504 throw new ArgeoException("Node " + node
505 + " exists but is of type "
506 + node
.getPrimaryNodeType().getName()
507 + " not of type " + type
);
508 // TODO: check versioning
512 StringBuffer current
= new StringBuffer("/");
513 Node currentNode
= session
.getRootNode();
514 Iterator
<String
> it
= tokenize(path
).iterator();
515 while (it
.hasNext()) {
516 String part
= it
.next();
517 current
.append(part
).append('/');
518 if (!session
.itemExists(current
.toString())) {
519 if (!it
.hasNext() && type
!= null)
520 currentNode
= currentNode
.addNode(part
, type
);
521 else if (it
.hasNext() && intermediaryNodeType
!= null)
522 currentNode
= currentNode
.addNode(part
,
523 intermediaryNodeType
);
525 currentNode
= currentNode
.addNode(part
);
527 currentNode
.addMixin(NodeType
.MIX_VERSIONABLE
);
528 if (log
.isTraceEnabled())
529 log
.debug("Added folder " + part
+ " as " + current
);
531 currentNode
= (Node
) session
.getItem(current
.toString());
535 } catch (RepositoryException e
) {
536 discardQuietly(session
);
537 throw new ArgeoException("Cannot mkdirs " + path
, e
);
542 /** Convert a path to the list of its tokens */
543 public static List
<String
> tokenize(String path
) {
544 List
<String
> tokens
= new ArrayList
<String
>();
545 boolean optimized
= false;
547 String
[] rawTokens
= path
.split("/");
548 for (String token
: rawTokens
) {
549 if (!token
.equals(""))
553 StringBuffer curr
= new StringBuffer();
554 char[] arr
= path
.toCharArray();
555 chars
: for (int i
= 0; i
< arr
.length
; i
++) {
558 if (i
== 0 || (i
== arr
.length
- 1))
560 if (curr
.length() > 0) {
561 tokens
.add(curr
.toString());
562 curr
= new StringBuffer();
567 if (curr
.length() > 0) {
568 tokens
.add(curr
.toString());
569 curr
= new StringBuffer();
572 return Collections
.unmodifiableList(tokens
);
576 * Safe and repository implementation independent registration of a
579 public static void registerNamespaceSafely(Session session
, String prefix
,
582 registerNamespaceSafely(session
.getWorkspace()
583 .getNamespaceRegistry(), prefix
, uri
);
584 } catch (RepositoryException e
) {
585 throw new ArgeoException("Cannot find namespace registry", e
);
590 * Safe and repository implementation independent registration of a
593 public static void registerNamespaceSafely(NamespaceRegistry nr
,
594 String prefix
, String uri
) {
596 String
[] prefixes
= nr
.getPrefixes();
597 for (String pref
: prefixes
)
598 if (pref
.equals(prefix
)) {
599 String registeredUri
= nr
.getURI(pref
);
600 if (!registeredUri
.equals(uri
))
601 throw new ArgeoException("Prefix " + pref
602 + " already registered for URI "
604 + " which is different from provided URI "
609 nr
.registerNamespace(prefix
, uri
);
610 } catch (RepositoryException e
) {
611 throw new ArgeoException("Cannot register namespace " + uri
612 + " under prefix " + prefix
, e
);
616 /** Recursively outputs the contents of the given node. */
617 public static void debug(Node node
) {
621 /** Recursively outputs the contents of the given node. */
622 public static void debug(Node node
, Log log
) {
624 // First output the node path
625 log
.debug(node
.getPath());
626 // Skip the virtual (and large!) jcr:system subtree
627 if (node
.getName().equals("jcr:system")) {
631 // Then the children nodes (recursive)
632 NodeIterator it
= node
.getNodes();
633 while (it
.hasNext()) {
634 Node childNode
= it
.nextNode();
635 debug(childNode
, log
);
638 // Then output the properties
639 PropertyIterator properties
= node
.getProperties();
640 // log.debug("Property are : ");
642 properties
: while (properties
.hasNext()) {
643 Property property
= properties
.nextProperty();
644 if (property
.getType() == PropertyType
.BINARY
)
645 continue properties
;// skip
646 if (property
.getDefinition().isMultiple()) {
647 // A multi-valued property, print all values
648 Value
[] values
= property
.getValues();
649 for (int i
= 0; i
< values
.length
; i
++) {
650 log
.debug(property
.getPath() + "="
651 + values
[i
].getString());
654 // A single-valued property
655 log
.debug(property
.getPath() + "=" + property
.getString());
658 } catch (Exception e
) {
659 log
.error("Could not debug " + node
, e
);
664 /** Logs the effective access control policies */
665 public static void logEffectiveAccessPolicies(Node node
) {
667 logEffectiveAccessPolicies(node
.getSession(), node
.getPath());
668 } catch (RepositoryException e
) {
669 log
.error("Cannot log effective access policies of " + node
, e
);
673 /** Logs the effective access control policies */
674 public static void logEffectiveAccessPolicies(Session session
, String path
) {
675 if (!log
.isDebugEnabled())
679 AccessControlPolicy
[] effectivePolicies
= session
680 .getAccessControlManager().getEffectivePolicies(path
);
681 if (effectivePolicies
.length
> 0) {
682 for (AccessControlPolicy policy
: effectivePolicies
) {
683 if (policy
instanceof AccessControlList
) {
684 AccessControlList acl
= (AccessControlList
) policy
;
685 log
.debug("Access control list for " + path
+ "\n"
686 + accessControlListSummary(acl
));
690 log
.debug("No effective access control policy for " + path
);
692 } catch (RepositoryException e
) {
693 log
.error("Cannot log effective access policies of " + path
, e
);
697 /** Returns a human-readable summary of this access control list. */
698 public static String
accessControlListSummary(AccessControlList acl
) {
699 StringBuffer buf
= new StringBuffer("");
701 for (AccessControlEntry ace
: acl
.getAccessControlEntries()) {
702 buf
.append('\t').append(ace
.getPrincipal().getName())
704 for (Privilege priv
: ace
.getPrivileges())
705 buf
.append("\t\t").append(priv
.getName()).append('\n');
707 return buf
.toString();
708 } catch (RepositoryException e
) {
709 throw new ArgeoException("Cannot write summary of " + acl
, e
);
714 * Copies recursively the content of a node to another one. Do NOT copy the
715 * property values of {@link NodeType#MIX_CREATED} and
716 * {@link NodeType#MIX_LAST_MODIFIED}, but update the
717 * {@link Property#JCR_LAST_MODIFIED} and
718 * {@link Property#JCR_LAST_MODIFIED_BY} properties if the target node has
719 * the {@link NodeType#MIX_LAST_MODIFIED} mixin.
721 public static void copy(Node fromNode
, Node toNode
) {
723 if (toNode
.getDefinition().isProtected())
726 // process properties
727 PropertyIterator pit
= fromNode
.getProperties();
728 properties
: while (pit
.hasNext()) {
729 Property fromProperty
= pit
.nextProperty();
730 String propertyName
= fromProperty
.getName();
731 if (toNode
.hasProperty(propertyName
)
732 && toNode
.getProperty(propertyName
).getDefinition()
736 if (fromProperty
.getDefinition().isProtected())
739 if (propertyName
.equals("jcr:created")
740 || propertyName
.equals("jcr:createdBy")
741 || propertyName
.equals("jcr:lastModified")
742 || propertyName
.equals("jcr:lastModifiedBy"))
745 if (fromProperty
.isMultiple()) {
746 toNode
.setProperty(propertyName
, fromProperty
.getValues());
748 toNode
.setProperty(propertyName
, fromProperty
.getValue());
752 // update jcr:lastModified and jcr:lastModifiedBy in toNode in case
753 // they existed, before adding the mixins
754 updateLastModified(toNode
);
757 for (NodeType mixinType
: fromNode
.getMixinNodeTypes()) {
758 toNode
.addMixin(mixinType
.getName());
761 // process children nodes
762 NodeIterator nit
= fromNode
.getNodes();
763 while (nit
.hasNext()) {
764 Node fromChild
= nit
.nextNode();
765 Integer index
= fromChild
.getIndex();
766 String nodeRelPath
= fromChild
.getName() + "[" + index
+ "]";
768 if (toNode
.hasNode(nodeRelPath
))
769 toChild
= toNode
.getNode(nodeRelPath
);
771 toChild
= toNode
.addNode(fromChild
.getName(), fromChild
772 .getPrimaryNodeType().getName());
773 copy(fromChild
, toChild
);
775 } catch (RepositoryException e
) {
776 throw new ArgeoException("Cannot copy " + fromNode
+ " to "
782 * Check whether all first-level properties (except jcr:* properties) are
783 * equal. Skip jcr:* properties
785 public static Boolean
allPropertiesEquals(Node reference
, Node observed
,
786 Boolean onlyCommonProperties
) {
788 PropertyIterator pit
= reference
.getProperties();
789 props
: while (pit
.hasNext()) {
790 Property propReference
= pit
.nextProperty();
791 String propName
= propReference
.getName();
792 if (propName
.startsWith("jcr:"))
795 if (!observed
.hasProperty(propName
))
796 if (onlyCommonProperties
)
800 // TODO: deal with multiple property values?
801 if (!observed
.getProperty(propName
).getValue()
802 .equals(propReference
.getValue()))
806 } catch (RepositoryException e
) {
807 throw new ArgeoException("Cannot check all properties equals of "
808 + reference
+ " and " + observed
, e
);
812 public static Map
<String
, PropertyDiff
> diffProperties(Node reference
,
814 Map
<String
, PropertyDiff
> diffs
= new TreeMap
<String
, PropertyDiff
>();
815 diffPropertiesLevel(diffs
, null, reference
, observed
);
820 * Compare the properties of two nodes. Recursivity to child nodes is not
821 * yet supported. Skip jcr:* properties.
823 static void diffPropertiesLevel(Map
<String
, PropertyDiff
> diffs
,
824 String baseRelPath
, Node reference
, Node observed
) {
826 // check removed and modified
827 PropertyIterator pit
= reference
.getProperties();
828 props
: while (pit
.hasNext()) {
829 Property p
= pit
.nextProperty();
830 String name
= p
.getName();
831 if (name
.startsWith("jcr:"))
834 if (!observed
.hasProperty(name
)) {
835 String relPath
= propertyRelPath(baseRelPath
, name
);
836 PropertyDiff pDiff
= new PropertyDiff(PropertyDiff
.REMOVED
,
837 relPath
, p
.getValue(), null);
838 diffs
.put(relPath
, pDiff
);
840 if (p
.isMultiple()) {
841 // FIXME implement multiple
843 Value referenceValue
= p
.getValue();
844 Value newValue
= observed
.getProperty(name
).getValue();
845 if (!referenceValue
.equals(newValue
)) {
846 String relPath
= propertyRelPath(baseRelPath
, name
);
847 PropertyDiff pDiff
= new PropertyDiff(
848 PropertyDiff
.MODIFIED
, relPath
,
849 referenceValue
, newValue
);
850 diffs
.put(relPath
, pDiff
);
856 pit
= observed
.getProperties();
857 props
: while (pit
.hasNext()) {
858 Property p
= pit
.nextProperty();
859 String name
= p
.getName();
860 if (name
.startsWith("jcr:"))
862 if (!reference
.hasProperty(name
)) {
863 if (p
.isMultiple()) {
864 // FIXME implement multiple
866 String relPath
= propertyRelPath(baseRelPath
, name
);
867 PropertyDiff pDiff
= new PropertyDiff(
868 PropertyDiff
.ADDED
, relPath
, null, p
.getValue());
869 diffs
.put(relPath
, pDiff
);
873 } catch (RepositoryException e
) {
874 throw new ArgeoException("Cannot diff " + reference
+ " and "
880 * Compare only a restricted list of properties of two nodes. No
884 public static Map
<String
, PropertyDiff
> diffProperties(Node reference
,
885 Node observed
, List
<String
> properties
) {
886 Map
<String
, PropertyDiff
> diffs
= new TreeMap
<String
, PropertyDiff
>();
888 Iterator
<String
> pit
= properties
.iterator();
890 props
: while (pit
.hasNext()) {
891 String name
= pit
.next();
892 if (!reference
.hasProperty(name
)) {
893 if (!observed
.hasProperty(name
))
895 Value val
= observed
.getProperty(name
).getValue();
897 // empty String but not null
898 if ("".equals(val
.getString()))
900 } catch (Exception e
) {
901 // not parseable as String, silent
903 PropertyDiff pDiff
= new PropertyDiff(PropertyDiff
.ADDED
,
905 diffs
.put(name
, pDiff
);
906 } else if (!observed
.hasProperty(name
)) {
907 PropertyDiff pDiff
= new PropertyDiff(PropertyDiff
.REMOVED
,
908 name
, reference
.getProperty(name
).getValue(), null);
909 diffs
.put(name
, pDiff
);
911 Value referenceValue
= reference
.getProperty(name
)
913 Value newValue
= observed
.getProperty(name
).getValue();
914 if (!referenceValue
.equals(newValue
)) {
915 PropertyDiff pDiff
= new PropertyDiff(
916 PropertyDiff
.MODIFIED
, name
, referenceValue
,
918 diffs
.put(name
, pDiff
);
922 } catch (RepositoryException e
) {
923 throw new ArgeoException("Cannot diff " + reference
+ " and "
929 /** Builds a property relPath to be used in the diff. */
930 private static String
propertyRelPath(String baseRelPath
,
931 String propertyName
) {
932 if (baseRelPath
== null)
935 return baseRelPath
+ '/' + propertyName
;
939 * Normalizes a name so that it can be stored in contexts not supporting
940 * names with ':' (typically databases). Replaces ':' by '_'.
942 public static String
normalize(String name
) {
943 return name
.replace(':', '_');
947 * Replaces characters which are invalid in a JCR name by '_'. Currently not
950 * @see JcrUtils#INVALID_NAME_CHARACTERS
952 public static String
replaceInvalidChars(String name
) {
953 return replaceInvalidChars(name
, '_');
957 * Replaces characters which are invalid in a JCR name. Currently not
960 * @see JcrUtils#INVALID_NAME_CHARACTERS
962 public static String
replaceInvalidChars(String name
, char replacement
) {
963 boolean modified
= false;
964 char[] arr
= name
.toCharArray();
965 for (int i
= 0; i
< arr
.length
; i
++) {
967 invalid
: for (char invalid
: INVALID_NAME_CHARACTERS
) {
969 arr
[i
] = replacement
;
976 return new String(arr
);
978 // do not create new object if unnecessary
983 * Removes forbidden characters from a path, replacing them with '_'
985 * @deprecated use {@link #replaceInvalidChars(String)} instead
987 public static String
removeForbiddenCharacters(String str
) {
988 return str
.replace('[', '_').replace(']', '_').replace('/', '_')
993 /** Cleanly disposes a {@link Binary} even if it is null. */
994 public static void closeQuietly(Binary binary
) {
1000 /** Retrieve a {@link Binary} as a byte array */
1001 public static byte[] getBinaryAsBytes(Property property
) {
1002 ByteArrayOutputStream out
= new ByteArrayOutputStream();
1003 InputStream in
= null;
1004 Binary binary
= null;
1006 binary
= property
.getBinary();
1007 in
= binary
.getStream();
1008 IOUtils
.copy(in
, out
);
1009 return out
.toByteArray();
1010 } catch (Exception e
) {
1011 throw new ArgeoException("Cannot read binary " + property
1014 IOUtils
.closeQuietly(out
);
1015 IOUtils
.closeQuietly(in
);
1016 closeQuietly(binary
);
1020 /** Writes a {@link Binary} from a byte array */
1021 public static void setBinaryAsBytes(Node node
, String property
, byte[] bytes
) {
1022 InputStream in
= null;
1023 Binary binary
= null;
1025 in
= new ByteArrayInputStream(bytes
);
1026 binary
= node
.getSession().getValueFactory().createBinary(in
);
1027 node
.setProperty(property
, binary
);
1028 } catch (Exception e
) {
1029 throw new ArgeoException("Cannot read binary " + property
1032 IOUtils
.closeQuietly(in
);
1033 closeQuietly(binary
);
1038 * Creates depth from a string (typically a username) by adding levels based
1039 * on its first characters: "aBcD",2 => a/aB
1041 public static String
firstCharsToPath(String str
, Integer nbrOfChars
) {
1042 if (str
.length() < nbrOfChars
)
1043 throw new ArgeoException("String " + str
1044 + " length must be greater or equal than " + nbrOfChars
);
1045 StringBuffer path
= new StringBuffer("");
1046 StringBuffer curr
= new StringBuffer("");
1047 for (int i
= 0; i
< nbrOfChars
; i
++) {
1048 curr
.append(str
.charAt(i
));
1050 if (i
< nbrOfChars
- 1)
1053 return path
.toString();
1057 * Discards the current changes in the session attached to this node. To be
1058 * used typically in a catch block.
1060 * @see #discardQuietly(Session)
1062 public static void discardUnderlyingSessionQuietly(Node node
) {
1064 discardQuietly(node
.getSession());
1065 } catch (RepositoryException e
) {
1066 log
.warn("Cannot quietly discard session of node " + node
+ ": "
1072 * Discards the current changes in a session by calling
1073 * {@link Session#refresh(boolean)} with <code>false</code>, only logging
1074 * potential errors when doing so. To be used typically in a catch block.
1076 public static void discardQuietly(Session session
) {
1078 if (session
!= null)
1079 session
.refresh(false);
1080 } catch (RepositoryException e
) {
1081 log
.warn("Cannot quietly discard session " + session
+ ": "
1087 * Login to a workspace with implicit credentials, creates the workspace
1088 * with these credentials if it does not already exist.
1090 public static Session
loginOrCreateWorkspace(Repository repository
,
1091 String workspaceName
) throws RepositoryException
{
1092 Session workspaceSession
= null;
1093 Session defaultSession
= null;
1096 workspaceSession
= repository
.login(workspaceName
);
1097 } catch (NoSuchWorkspaceException e
) {
1098 // try to create workspace
1099 defaultSession
= repository
.login();
1100 defaultSession
.getWorkspace().createWorkspace(workspaceName
);
1101 workspaceSession
= repository
.login(workspaceName
);
1103 return workspaceSession
;
1105 logoutQuietly(defaultSession
);
1109 /** Logs out the session, not throwing any exception, even if it is null. */
1110 public static void logoutQuietly(Session session
) {
1112 if (session
!= null)
1113 if (session
.isLive())
1115 } catch (Exception e
) {
1121 * Convenient method to add a listener. uuids passed as null, deep=true,
1122 * local=true, only one node type
1124 public static void addListener(Session session
, EventListener listener
,
1125 int eventTypes
, String basePath
, String nodeType
) {
1127 session
.getWorkspace()
1128 .getObservationManager()
1135 nodeType
== null ?
null : new String
[] { nodeType
},
1137 } catch (RepositoryException e
) {
1138 throw new ArgeoException("Cannot add JCR listener " + listener
1139 + " to session " + session
, e
);
1143 /** Removes a listener without throwing exception */
1144 public static void removeListenerQuietly(Session session
,
1145 EventListener listener
) {
1146 if (session
== null || !session
.isLive())
1149 session
.getWorkspace().getObservationManager()
1150 .removeEventListener(listener
);
1151 } catch (RepositoryException e
) {
1157 * Quietly unregisters an {@link EventListener} from the udnerlying
1158 * workspace of this node.
1160 public static void unregisterQuietly(Node node
, EventListener eventListener
) {
1162 unregisterQuietly(node
.getSession().getWorkspace(), eventListener
);
1163 } catch (RepositoryException e
) {
1165 if (log
.isTraceEnabled())
1166 log
.trace("Could not unregister event listener "
1171 /** Quietly unregisters an {@link EventListener} from this workspace */
1172 public static void unregisterQuietly(Workspace workspace
,
1173 EventListener eventListener
) {
1174 if (eventListener
== null)
1177 workspace
.getObservationManager()
1178 .removeEventListener(eventListener
);
1179 } catch (RepositoryException e
) {
1181 if (log
.isTraceEnabled())
1182 log
.trace("Could not unregister event listener "
1188 * If this node is has the {@link NodeType#MIX_LAST_MODIFIED} mixin, it
1189 * updates the {@link Property#JCR_LAST_MODIFIED} property with the current
1190 * time and the {@link Property#JCR_LAST_MODIFIED_BY} property with the
1191 * underlying session user id. In Jackrabbit 2.x, <a
1192 * href="https://issues.apache.org/jira/browse/JCR-2233">these properties
1193 * are not automatically updated</a>, hence the need for manual update. The
1194 * session is not saved.
1196 public static void updateLastModified(Node node
) {
1198 if (!node
.isNodeType(NodeType
.MIX_LAST_MODIFIED
))
1199 node
.addMixin(NodeType
.MIX_LAST_MODIFIED
);
1200 node
.setProperty(Property
.JCR_LAST_MODIFIED
,
1201 new GregorianCalendar());
1202 node
.setProperty(Property
.JCR_LAST_MODIFIED_BY
, node
.getSession()
1204 } catch (RepositoryException e
) {
1205 throw new ArgeoException("Cannot update last modified on " + node
,
1210 /** Update lastModified recursively until this parent. */
1211 public static void updateLastModifiedAndParents(Node node
, String untilPath
) {
1213 if (!node
.getPath().startsWith(untilPath
))
1214 throw new ArgeoException(node
+ " is not under " + untilPath
);
1215 updateLastModified(node
);
1216 if (!node
.getPath().equals(untilPath
))
1217 updateLastModifiedAndParents(node
.getParent(), untilPath
);
1218 } catch (RepositoryException e
) {
1219 throw new ArgeoException("Cannot update lastModified from " + node
1220 + " until " + untilPath
, e
);
1225 * Returns a String representing the short version (see <a
1226 * href="http://jackrabbit.apache.org/node-type-notation.html"> Node type
1227 * Notation </a> attributes grammar) of the main business attributes of this
1228 * property definition
1232 public static String
getPropertyDefinitionAsString(Property prop
) {
1233 StringBuffer sbuf
= new StringBuffer();
1235 if (prop
.getDefinition().isAutoCreated())
1237 if (prop
.getDefinition().isMandatory())
1239 if (prop
.getDefinition().isProtected())
1241 if (prop
.getDefinition().isMultiple())
1243 } catch (RepositoryException re
) {
1244 throw new ArgeoException(
1245 "unexpected error while getting property definition as String",
1248 return sbuf
.toString();
1252 * Estimate the sub tree size from current node. Computation is based on the
1253 * Jcr {@link Property.getLength()} method. Note : it is not the exact size
1254 * used on the disk by the current part of the JCR Tree.
1257 public static long getNodeApproxSize(Node node
) {
1258 long curNodeSize
= 0;
1260 PropertyIterator pi
= node
.getProperties();
1261 while (pi
.hasNext()) {
1262 Property prop
= pi
.nextProperty();
1263 if (prop
.isMultiple()) {
1264 int nb
= prop
.getLengths().length
;
1265 for (int i
= 0; i
< nb
; i
++) {
1266 curNodeSize
+= (prop
.getLengths()[i
] > 0 ? prop
1267 .getLengths()[i
] : 0);
1270 curNodeSize
+= (prop
.getLength() > 0 ? prop
.getLength() : 0);
1273 NodeIterator ni
= node
.getNodes();
1274 while (ni
.hasNext())
1275 curNodeSize
+= getNodeApproxSize(ni
.nextNode());
1277 } catch (RepositoryException re
) {
1278 throw new ArgeoException(
1279 "Unexpected error while recursively determining node size.",
1289 * Convenience method for adding a single privilege to a principal (user or
1290 * role), typically jcr:all
1292 public synchronized static void addPrivilege(Session session
, String path
,
1293 String principal
, String privilege
) throws RepositoryException
{
1294 List
<Privilege
> privileges
= new ArrayList
<Privilege
>();
1295 privileges
.add(session
.getAccessControlManager().privilegeFromName(
1297 addPrivileges(session
, path
, new SimplePrincipal(principal
), privileges
);
1301 * Add privileges on a path to a {@link Principal}. The path must already
1302 * exist. Session is saved. Synchronized to prevent concurrent modifications
1305 public synchronized static Boolean
addPrivileges(Session session
,
1306 String path
, Principal principal
, List
<Privilege
> privs
)
1307 throws RepositoryException
{
1308 // make sure the session is in line with the persisted state
1309 session
.refresh(false);
1310 AccessControlManager acm
= session
.getAccessControlManager();
1311 AccessControlList acl
= getAccessControlList(acm
, path
);
1313 accessControlEntries
: for (AccessControlEntry ace
: acl
1314 .getAccessControlEntries()) {
1315 Principal currentPrincipal
= ace
.getPrincipal();
1316 if (currentPrincipal
.getName().equals(principal
.getName())) {
1317 Privilege
[] currentPrivileges
= ace
.getPrivileges();
1318 if (currentPrivileges
.length
!= privs
.size())
1319 break accessControlEntries
;
1320 for (int i
= 0; i
< currentPrivileges
.length
; i
++) {
1321 Privilege currP
= currentPrivileges
[i
];
1322 Privilege p
= privs
.get(i
);
1323 if (!currP
.getName().equals(p
.getName())) {
1324 break accessControlEntries
;
1331 Privilege
[] privileges
= privs
.toArray(new Privilege
[privs
.size()]);
1332 acl
.addAccessControlEntry(principal
, privileges
);
1333 acm
.setPolicy(path
, acl
);
1334 if (log
.isDebugEnabled()) {
1335 StringBuffer privBuf
= new StringBuffer();
1336 for (Privilege priv
: privs
)
1337 privBuf
.append(priv
.getName());
1338 log
.debug("Added privileges " + privBuf
+ " to "
1339 + principal
.getName() + " on " + path
+ " in '"
1340 + session
.getWorkspace().getName() + "'");
1342 session
.refresh(true);
1347 /** Gets access control list for this path, throws exception if not found */
1348 public synchronized static AccessControlList
getAccessControlList(
1349 AccessControlManager acm
, String path
) throws RepositoryException
{
1350 // search for an access control list
1351 AccessControlList acl
= null;
1352 AccessControlPolicyIterator policyIterator
= acm
1353 .getApplicablePolicies(path
);
1354 if (policyIterator
.hasNext()) {
1355 while (policyIterator
.hasNext()) {
1356 AccessControlPolicy acp
= policyIterator
1357 .nextAccessControlPolicy();
1358 if (acp
instanceof AccessControlList
)
1359 acl
= ((AccessControlList
) acp
);
1362 AccessControlPolicy
[] existingPolicies
= acm
.getPolicies(path
);
1363 for (AccessControlPolicy acp
: existingPolicies
) {
1364 if (acp
instanceof AccessControlList
)
1365 acl
= ((AccessControlList
) acp
);
1371 throw new ArgeoException("ACL not found at " + path
);
1374 /** Clear authorizations for a user at this path */
1375 public synchronized static void clearAccessControList(Session session
,
1376 String path
, String username
) throws RepositoryException
{
1377 AccessControlManager acm
= session
.getAccessControlManager();
1378 AccessControlList acl
= getAccessControlList(acm
, path
);
1379 for (AccessControlEntry ace
: acl
.getAccessControlEntries()) {
1380 if (ace
.getPrincipal().getName().equals(username
)) {
1381 acl
.removeAccessControlEntry(ace
);
1390 * Creates the nodes making the path as {@link NodeType#NT_FOLDER}
1392 public static Node
mkfolders(Session session
, String path
) {
1393 return mkdirs(session
, path
, NodeType
.NT_FOLDER
, NodeType
.NT_FOLDER
,
1398 * Copy only nt:folder and nt:file, without their additional types and
1402 * if true copies folders as well, otherwise only first level
1404 * @return how many files were copied
1406 public static Long
copyFiles(Node fromNode
, Node toNode
, Boolean recursive
,
1407 ArgeoMonitor monitor
) {
1410 Binary binary
= null;
1411 InputStream in
= null;
1413 NodeIterator fromChildren
= fromNode
.getNodes();
1414 while (fromChildren
.hasNext()) {
1415 if (monitor
!= null && monitor
.isCanceled())
1416 throw new ArgeoException(
1417 "Copy cancelled before it was completed");
1419 Node fromChild
= fromChildren
.nextNode();
1420 String fileName
= fromChild
.getName();
1421 if (fromChild
.isNodeType(NodeType
.NT_FILE
)) {
1422 if (monitor
!= null)
1423 monitor
.subTask("Copy " + fileName
);
1424 binary
= fromChild
.getNode(Node
.JCR_CONTENT
)
1425 .getProperty(Property
.JCR_DATA
).getBinary();
1426 in
= binary
.getStream();
1427 copyStreamAsFile(toNode
, fileName
, in
);
1428 IOUtils
.closeQuietly(in
);
1429 closeQuietly(binary
);
1432 toNode
.getSession().save();
1435 if (log
.isDebugEnabled())
1436 log
.debug("Copied file " + fromChild
.getPath());
1437 if (monitor
!= null)
1439 } else if (fromChild
.isNodeType(NodeType
.NT_FOLDER
)
1442 if (toNode
.hasNode(fileName
)) {
1443 toChildFolder
= toNode
.getNode(fileName
);
1444 if (!toChildFolder
.isNodeType(NodeType
.NT_FOLDER
))
1445 throw new ArgeoException(toChildFolder
1446 + " is not of type nt:folder");
1448 toChildFolder
= toNode
.addNode(fileName
,
1449 NodeType
.NT_FOLDER
);
1452 toNode
.getSession().save();
1455 + copyFiles(fromChild
, toChildFolder
, recursive
,
1460 } catch (RepositoryException e
) {
1461 throw new ArgeoException("Cannot copy files between " + fromNode
1462 + " and " + toNode
);
1464 // in case there was an exception
1465 IOUtils
.closeQuietly(in
);
1466 closeQuietly(binary
);
1471 * Iteratively count all file nodes in subtree, inefficient but can be
1472 * useful when query are poorly supported, such as in remoting.
1474 public static Long
countFiles(Node node
) {
1475 Long localCount
= 0l;
1477 for (NodeIterator nit
= node
.getNodes(); nit
.hasNext();) {
1478 Node child
= nit
.nextNode();
1479 if (child
.isNodeType(NodeType
.NT_FOLDER
))
1480 localCount
= localCount
+ countFiles(child
);
1481 else if (child
.isNodeType(NodeType
.NT_FILE
))
1482 localCount
= localCount
+ 1;
1484 } catch (RepositoryException e
) {
1485 throw new ArgeoException("Cannot count all children of " + node
);
1491 * Copy a file as an nt:file, assuming an nt:folder hierarchy. The session
1494 * @return the created file node
1496 public static Node
copyFile(Node folderNode
, File file
) {
1497 InputStream in
= null;
1499 in
= new FileInputStream(file
);
1500 return copyStreamAsFile(folderNode
, file
.getName(), in
);
1501 } catch (IOException e
) {
1502 throw new ArgeoException("Cannot copy file " + file
+ " under "
1505 IOUtils
.closeQuietly(in
);
1509 /** Copy bytes as an nt:file */
1510 public static Node
copyBytesAsFile(Node folderNode
, String fileName
,
1512 InputStream in
= null;
1514 in
= new ByteArrayInputStream(bytes
);
1515 return copyStreamAsFile(folderNode
, fileName
, in
);
1516 } catch (Exception e
) {
1517 throw new ArgeoException("Cannot copy file " + fileName
+ " under "
1520 IOUtils
.closeQuietly(in
);
1525 * Copy a stream as an nt:file, assuming an nt:folder hierarchy. The session
1528 * @return the created file node
1530 public static Node
copyStreamAsFile(Node folderNode
, String fileName
,
1532 Binary binary
= null;
1536 if (folderNode
.hasNode(fileName
)) {
1537 fileNode
= folderNode
.getNode(fileName
);
1538 if (!fileNode
.isNodeType(NodeType
.NT_FILE
))
1539 throw new ArgeoException(fileNode
1540 + " is not of type nt:file");
1541 // we assume that the content node is already there
1542 contentNode
= fileNode
.getNode(Node
.JCR_CONTENT
);
1544 fileNode
= folderNode
.addNode(fileName
, NodeType
.NT_FILE
);
1545 contentNode
= fileNode
.addNode(Node
.JCR_CONTENT
,
1546 NodeType
.NT_RESOURCE
);
1548 binary
= contentNode
.getSession().getValueFactory()
1550 contentNode
.setProperty(Property
.JCR_DATA
, binary
);
1552 } catch (Exception e
) {
1553 throw new ArgeoException("Cannot create file node " + fileName
1554 + " under " + folderNode
, e
);
1556 closeQuietly(binary
);
1560 /** Computes the checksum of an nt:file */
1561 public static String
checksumFile(Node fileNode
, String algorithm
) {
1563 InputStream in
= null;
1565 data
= fileNode
.getNode(Node
.JCR_CONTENT
)
1566 .getProperty(Property
.JCR_DATA
).getBinary();
1567 in
= data
.getStream();
1568 return DigestUtils
.digest(algorithm
, in
);
1569 } catch (RepositoryException e
) {
1570 throw new ArgeoException("Cannot checksum file " + fileNode
, e
);
1572 IOUtils
.closeQuietly(in
);