3 import java
.io
.ByteArrayInputStream
;
4 import java
.io
.ByteArrayOutputStream
;
6 import java
.io
.FileInputStream
;
7 import java
.io
.IOException
;
8 import java
.io
.InputStream
;
9 import java
.io
.PipedInputStream
;
10 import java
.io
.PipedOutputStream
;
11 import java
.net
.MalformedURLException
;
13 import java
.security
.MessageDigest
;
14 import java
.security
.NoSuchAlgorithmException
;
15 import java
.security
.Principal
;
16 import java
.text
.DateFormat
;
17 import java
.text
.ParseException
;
18 import java
.time
.Instant
;
19 import java
.util
.ArrayList
;
20 import java
.util
.Calendar
;
21 import java
.util
.Collections
;
22 import java
.util
.Date
;
23 import java
.util
.GregorianCalendar
;
24 import java
.util
.Iterator
;
25 import java
.util
.List
;
27 import java
.util
.TreeMap
;
29 import javax
.jcr
.Binary
;
30 import javax
.jcr
.Credentials
;
31 import javax
.jcr
.ImportUUIDBehavior
;
32 import javax
.jcr
.NamespaceRegistry
;
33 import javax
.jcr
.NoSuchWorkspaceException
;
34 import javax
.jcr
.Node
;
35 import javax
.jcr
.NodeIterator
;
36 import javax
.jcr
.Property
;
37 import javax
.jcr
.PropertyIterator
;
38 import javax
.jcr
.Repository
;
39 import javax
.jcr
.RepositoryException
;
40 import javax
.jcr
.Session
;
41 import javax
.jcr
.Value
;
42 import javax
.jcr
.Workspace
;
43 import javax
.jcr
.nodetype
.NoSuchNodeTypeException
;
44 import javax
.jcr
.nodetype
.NodeType
;
45 import javax
.jcr
.observation
.EventListener
;
46 import javax
.jcr
.query
.Query
;
47 import javax
.jcr
.query
.QueryResult
;
48 import javax
.jcr
.security
.AccessControlEntry
;
49 import javax
.jcr
.security
.AccessControlList
;
50 import javax
.jcr
.security
.AccessControlManager
;
51 import javax
.jcr
.security
.AccessControlPolicy
;
52 import javax
.jcr
.security
.AccessControlPolicyIterator
;
53 import javax
.jcr
.security
.Privilege
;
55 import org
.apache
.commons
.io
.IOUtils
;
57 /** Utility methods to simplify common JCR operations. */
58 public class JcrUtils
{
60 // final private static Log log = LogFactory.getLog(JcrUtils.class);
63 * Not complete yet. See
64 * http://www.day.com/specs/jcr/2.0/3_Repository_Model.html#3.2.2%20Local
67 public final static char[] INVALID_NAME_CHARACTERS
= { '/', ':', '[', ']', '|', '*', /* invalid for XML: */ '<',
70 /** Prevents instantiation */
75 * Queries one single node.
77 * @return one single node or null if none was found
78 * @throws JcrException if more than one node was found
80 public static Node
querySingleNode(Query query
) {
81 NodeIterator nodeIterator
;
83 QueryResult queryResult
= query
.execute();
84 nodeIterator
= queryResult
.getNodes();
85 } catch (RepositoryException e
) {
86 throw new JcrException("Cannot execute query " + query
, e
);
89 if (nodeIterator
.hasNext())
90 node
= nodeIterator
.nextNode();
94 if (nodeIterator
.hasNext())
95 throw new IllegalArgumentException("Query returned more than one node.");
99 /** Retrieves the node name from the provided path */
100 public static String
nodeNameFromPath(String path
) {
101 if (path
.equals("/"))
103 if (path
.charAt(0) != '/')
104 throw new IllegalArgumentException("Path " + path
+ " must start with a '/'");
106 if (pathT
.charAt(pathT
.length() - 1) == '/')
107 pathT
= pathT
.substring(0, pathT
.length() - 2);
109 int index
= pathT
.lastIndexOf('/');
110 return pathT
.substring(index
+ 1);
113 /** Retrieves the parent path of the provided path */
114 public static String
parentPath(String path
) {
115 if (path
.equals("/"))
116 throw new IllegalArgumentException("Root path '/' has no parent path");
117 if (path
.charAt(0) != '/')
118 throw new IllegalArgumentException("Path " + path
+ " must start with a '/'");
120 if (pathT
.charAt(pathT
.length() - 1) == '/')
121 pathT
= pathT
.substring(0, pathT
.length() - 2);
123 int index
= pathT
.lastIndexOf('/');
124 return pathT
.substring(0, index
);
127 /** The provided data as a path ('/' at the end, not the beginning) */
128 public static String
dateAsPath(Calendar cal
) {
129 return dateAsPath(cal
, false);
133 * Creates a deep path based on a URL:
134 * http://subdomain.example.com/to/content?args becomes
135 * com/example/subdomain/to/content
137 public static String
urlAsPath(String url
) {
139 URL u
= new URL(url
);
140 StringBuffer path
= new StringBuffer(url
.length());
142 path
.append(hostAsPath(u
.getHost()));
143 // we don't put port since it may not always be there and may change
144 path
.append(u
.getPath());
145 return path
.toString();
146 } catch (MalformedURLException e
) {
147 throw new IllegalArgumentException("Cannot generate URL path for " + url
, e
);
151 /** Set the {@link NodeType#NT_ADDRESS} properties based on this URL. */
152 public static void urlToAddressProperties(Node node
, String url
) {
154 URL u
= new URL(url
);
155 node
.setProperty(Property
.JCR_PROTOCOL
, u
.getProtocol());
156 node
.setProperty(Property
.JCR_HOST
, u
.getHost());
157 node
.setProperty(Property
.JCR_PORT
, Integer
.toString(u
.getPort()));
158 node
.setProperty(Property
.JCR_PATH
, normalizePath(u
.getPath()));
159 } catch (RepositoryException e
) {
160 throw new JcrException("Cannot set URL " + url
+ " as nt:address properties", e
);
161 } catch (MalformedURLException e
) {
162 throw new IllegalArgumentException("Cannot set URL " + url
+ " as nt:address properties", e
);
166 /** Build URL based on the {@link NodeType#NT_ADDRESS} properties. */
167 public static String
urlFromAddressProperties(Node node
) {
169 URL u
= new URL(node
.getProperty(Property
.JCR_PROTOCOL
).getString(),
170 node
.getProperty(Property
.JCR_HOST
).getString(),
171 (int) node
.getProperty(Property
.JCR_PORT
).getLong(),
172 node
.getProperty(Property
.JCR_PATH
).getString());
174 } catch (RepositoryException e
) {
175 throw new JcrException("Cannot get URL from nt:address properties of " + node
, e
);
176 } catch (MalformedURLException e
) {
177 throw new IllegalArgumentException("Cannot get URL from nt:address properties of " + node
, e
);
186 * Make sure that: starts with '/', do not end with '/', do not have '//'
188 public static String
normalizePath(String path
) {
189 List
<String
> tokens
= tokenize(path
);
190 StringBuffer buf
= new StringBuffer(path
.length());
191 for (String token
: tokens
) {
195 return buf
.toString();
199 * Creates a path from a FQDN, inverting the order of the component:
200 * www.argeo.org becomes org.argeo.www
202 public static String
hostAsPath(String host
) {
203 StringBuffer path
= new StringBuffer(host
.length());
204 String
[] hostTokens
= host
.split("\\.");
205 for (int i
= hostTokens
.length
- 1; i
>= 0; i
--) {
206 path
.append(hostTokens
[i
]);
210 return path
.toString();
214 * Creates a path from a UUID (e.g. 6ebda899-217d-4bf1-abe4-2839085c8f3c becomes
215 * 6ebda899-217d/4bf1/abe4/2839085c8f3c/). '/' at the end, not the beginning
217 public static String
uuidAsPath(String uuid
) {
218 StringBuffer path
= new StringBuffer(uuid
.length());
219 String
[] tokens
= uuid
.split("-");
220 for (int i
= 0; i
< tokens
.length
; i
++) {
221 path
.append(tokens
[i
]);
225 return path
.toString();
229 * The provided data as a path ('/' at the end, not the beginning)
231 * @param cal the date
232 * @param addHour whether to add hour as well
234 public static String
dateAsPath(Calendar cal
, Boolean addHour
) {
235 StringBuffer buf
= new StringBuffer(14);
237 buf
.append(cal
.get(Calendar
.YEAR
));
240 int month
= cal
.get(Calendar
.MONTH
) + 1;
247 int day
= cal
.get(Calendar
.DAY_OF_MONTH
);
255 int hour
= cal
.get(Calendar
.HOUR_OF_DAY
);
262 return buf
.toString();
266 /** Converts in one call a string into a gregorian calendar. */
267 public static Calendar
parseCalendar(DateFormat dateFormat
, String value
) {
269 Date date
= dateFormat
.parse(value
);
270 Calendar calendar
= new GregorianCalendar();
271 calendar
.setTime(date
);
273 } catch (ParseException e
) {
274 throw new IllegalArgumentException("Cannot parse " + value
+ " with date format " + dateFormat
, e
);
279 /** The last element of a path. */
280 public static String
lastPathElement(String path
) {
281 if (path
.charAt(path
.length() - 1) == '/')
282 throw new IllegalArgumentException("Path " + path
+ " cannot end with '/'");
283 int index
= path
.lastIndexOf('/');
286 return path
.substring(index
+ 1);
290 * Call {@link Node#getName()} without exceptions (useful in super
293 public static String
getNameQuietly(Node node
) {
295 return node
.getName();
296 } catch (RepositoryException e
) {
297 throw new JcrException("Cannot get name from " + node
, e
);
302 * Call {@link Node#getProperty(String)} without exceptions (useful in super
305 public static String
getStringPropertyQuietly(Node node
, String propertyName
) {
307 return node
.getProperty(propertyName
).getString();
308 } catch (RepositoryException e
) {
309 throw new JcrException("Cannot get name from " + node
, e
);
314 // * Routine that get the child with this name, adding it if it does not already
317 // public static Node getOrAdd(Node parent, String name, String primaryNodeType) throws RepositoryException {
318 // return parent.hasNode(name) ? parent.getNode(name) : parent.addNode(name, primaryNodeType);
322 * Routine that get the child with this name, adding it if it does not already
325 public static Node
getOrAdd(Node parent
, String name
, String primaryNodeType
, String
... mixinNodeTypes
)
326 throws RepositoryException
{
328 if (parent
.hasNode(name
)) {
329 node
= parent
.getNode(name
);
330 if (primaryNodeType
!= null && !node
.isNodeType(primaryNodeType
))
331 throw new IllegalArgumentException("Node " + node
+ " exists but is of primary node type "
332 + node
.getPrimaryNodeType().getName() + ", not " + primaryNodeType
);
333 for (String mixin
: mixinNodeTypes
) {
334 if (!node
.isNodeType(mixin
))
335 node
.addMixin(mixin
);
339 node
= primaryNodeType
!= null ? parent
.addNode(name
, primaryNodeType
) : parent
.addNode(name
);
340 for (String mixin
: mixinNodeTypes
) {
341 node
.addMixin(mixin
);
348 * Routine that get the child with this name, adding it if it does not already
351 public static Node
getOrAdd(Node parent
, String name
) throws RepositoryException
{
352 return parent
.hasNode(name
) ? parent
.getNode(name
) : parent
.addNode(name
);
355 /** Convert a {@link NodeIterator} to a list of {@link Node} */
356 public static List
<Node
> nodeIteratorToList(NodeIterator nodeIterator
) {
357 List
<Node
> nodes
= new ArrayList
<Node
>();
358 while (nodeIterator
.hasNext()) {
359 nodes
.add(nodeIterator
.nextNode());
369 * Concisely get the string value of a property or null if this node doesn't
372 public static String
get(Node node
, String propertyName
) {
374 if (!node
.hasProperty(propertyName
))
376 return node
.getProperty(propertyName
).getString();
377 } catch (RepositoryException e
) {
378 throw new JcrException("Cannot get property " + propertyName
+ " of " + node
, e
);
382 /** Concisely get the path of the given node. */
383 public static String
getPath(Node node
) {
385 return node
.getPath();
386 } catch (RepositoryException e
) {
387 throw new JcrException("Cannot get path of " + node
, e
);
391 /** Concisely get the boolean value of a property */
392 public static Boolean
check(Node node
, String propertyName
) {
394 return node
.getProperty(propertyName
).getBoolean();
395 } catch (RepositoryException e
) {
396 throw new JcrException("Cannot get property " + propertyName
+ " of " + node
, e
);
400 /** Concisely get the bytes array value of a property */
401 public static byte[] getBytes(Node node
, String propertyName
) {
403 return getBinaryAsBytes(node
.getProperty(propertyName
));
404 } catch (RepositoryException e
) {
405 throw new JcrException("Cannot get property " + propertyName
+ " of " + node
, e
);
414 * Create sub nodes relative to a parent node
416 public static Node
mkdirs(Node parentNode
, String relativePath
) {
417 return mkdirs(parentNode
, relativePath
, null, null);
421 * Create sub nodes relative to a parent node
423 * @param nodeType the type of the leaf node
425 public static Node
mkdirs(Node parentNode
, String relativePath
, String nodeType
) {
426 return mkdirs(parentNode
, relativePath
, nodeType
, null);
430 * Create sub nodes relative to a parent node
432 * @param nodeType the type of the leaf node
434 public static Node
mkdirs(Node parentNode
, String relativePath
, String nodeType
, String intermediaryNodeType
) {
435 List
<String
> tokens
= tokenize(relativePath
);
436 Node currParent
= parentNode
;
438 for (int i
= 0; i
< tokens
.size(); i
++) {
439 String name
= tokens
.get(i
);
440 if (currParent
.hasNode(name
)) {
441 currParent
= currParent
.getNode(name
);
443 if (i
!= (tokens
.size() - 1)) {// intermediary
444 currParent
= currParent
.addNode(name
, intermediaryNodeType
);
446 currParent
= currParent
.addNode(name
, nodeType
);
451 } catch (RepositoryException e
) {
452 throw new JcrException("Cannot mkdirs relative path " + relativePath
+ " from " + parentNode
, e
);
457 * Synchronized and save is performed, to avoid race conditions in initializers
458 * leading to duplicate nodes.
460 public synchronized static Node
mkdirsSafe(Session session
, String path
, String type
) {
462 if (session
.hasPendingChanges())
463 throw new IllegalStateException("Session has pending changes, save them first.");
464 Node node
= mkdirs(session
, path
, type
);
467 } catch (RepositoryException e
) {
468 discardQuietly(session
);
469 throw new JcrException("Cannot safely make directories", e
);
473 public synchronized static Node
mkdirsSafe(Session session
, String path
) {
474 return mkdirsSafe(session
, path
, null);
477 /** Creates the nodes making path, if they don't exist. */
478 public static Node
mkdirs(Session session
, String path
) {
479 return mkdirs(session
, path
, null, null, false);
483 * @param type the type of the leaf node
485 public static Node
mkdirs(Session session
, String path
, String type
) {
486 return mkdirs(session
, path
, type
, null, false);
490 * Creates the nodes making path, if they don't exist. This is up to the caller
491 * to save the session. Use with caution since it can create duplicate nodes if
492 * used concurrently. Requires read access to the root node of the workspace.
494 public static Node
mkdirs(Session session
, String path
, String type
, String intermediaryNodeType
,
495 Boolean versioning
) {
497 if (path
.equals("/"))
498 return session
.getRootNode();
500 if (session
.itemExists(path
)) {
501 Node node
= session
.getNode(path
);
503 if (type
!= null && !node
.isNodeType(type
) && !node
.getPath().equals("/"))
504 throw new IllegalArgumentException("Node " + node
+ " exists but is of type "
505 + node
.getPrimaryNodeType().getName() + " not of type " + type
);
506 // TODO: check versioning
510 // StringBuffer current = new StringBuffer("/");
511 // Node currentNode = session.getRootNode();
513 Node currentNode
= findClosestExistingParent(session
, path
);
514 String closestExistingParentPath
= currentNode
.getPath();
515 StringBuffer current
= new StringBuffer(closestExistingParentPath
);
516 if (!closestExistingParentPath
.endsWith("/"))
518 Iterator
<String
> it
= tokenize(path
.substring(closestExistingParentPath
.length())).iterator();
519 while (it
.hasNext()) {
520 String part
= it
.next();
521 current
.append(part
).append('/');
522 if (!session
.itemExists(current
.toString())) {
523 if (!it
.hasNext() && type
!= null)
524 currentNode
= currentNode
.addNode(part
, type
);
525 else if (it
.hasNext() && intermediaryNodeType
!= null)
526 currentNode
= currentNode
.addNode(part
, intermediaryNodeType
);
528 currentNode
= currentNode
.addNode(part
);
530 currentNode
.addMixin(NodeType
.MIX_VERSIONABLE
);
531 // if (log.isTraceEnabled())
532 // log.debug("Added folder " + part + " as " + current);
534 currentNode
= (Node
) session
.getItem(current
.toString());
538 } catch (RepositoryException e
) {
539 discardQuietly(session
);
540 throw new JcrException("Cannot mkdirs " + path
, e
);
545 private static Node
findClosestExistingParent(Session session
, String path
) throws RepositoryException
{
546 int idx
= path
.lastIndexOf('/');
548 return session
.getRootNode();
549 String parentPath
= path
.substring(0, idx
);
550 if (session
.itemExists(parentPath
))
551 return session
.getNode(parentPath
);
553 return findClosestExistingParent(session
, parentPath
);
556 /** Convert a path to the list of its tokens */
557 public static List
<String
> tokenize(String path
) {
558 List
<String
> tokens
= new ArrayList
<String
>();
559 boolean optimized
= false;
561 String
[] rawTokens
= path
.split("/");
562 for (String token
: rawTokens
) {
563 if (!token
.equals(""))
567 StringBuffer curr
= new StringBuffer();
568 char[] arr
= path
.toCharArray();
569 chars
: for (int i
= 0; i
< arr
.length
; i
++) {
572 if (i
== 0 || (i
== arr
.length
- 1))
574 if (curr
.length() > 0) {
575 tokens
.add(curr
.toString());
576 curr
= new StringBuffer();
581 if (curr
.length() > 0) {
582 tokens
.add(curr
.toString());
583 curr
= new StringBuffer();
586 return Collections
.unmodifiableList(tokens
);
590 // * use {@link #mkdirs(Session, String, String, String, Boolean)} instead.
595 // public static Node mkdirs(Session session, String path, String type,
596 // Boolean versioning) {
597 // return mkdirs(session, path, type, type, false);
601 * Safe and repository implementation independent registration of a namespace.
603 public static void registerNamespaceSafely(Session session
, String prefix
, String uri
) {
605 registerNamespaceSafely(session
.getWorkspace().getNamespaceRegistry(), prefix
, uri
);
606 } catch (RepositoryException e
) {
607 throw new JcrException("Cannot find namespace registry", e
);
612 * Safe and repository implementation independent registration of a namespace.
614 public static void registerNamespaceSafely(NamespaceRegistry nr
, String prefix
, String uri
) {
616 String
[] prefixes
= nr
.getPrefixes();
617 for (String pref
: prefixes
)
618 if (pref
.equals(prefix
)) {
619 String registeredUri
= nr
.getURI(pref
);
620 if (!registeredUri
.equals(uri
))
621 throw new IllegalArgumentException("Prefix " + pref
+ " already registered for URI "
622 + registeredUri
+ " which is different from provided URI " + uri
);
626 nr
.registerNamespace(prefix
, uri
);
627 } catch (RepositoryException e
) {
628 throw new JcrException("Cannot register namespace " + uri
+ " under prefix " + prefix
, e
);
632 // /** Recursively outputs the contents of the given node. */
633 // public static void debug(Node node) {
637 // /** Recursively outputs the contents of the given node. */
638 // public static void debug(Node node, Log log) {
640 // // First output the node path
641 // log.debug(node.getPath());
642 // // Skip the virtual (and large!) jcr:system subtree
643 // if (node.getName().equals("jcr:system")) {
647 // // Then the children nodes (recursive)
648 // NodeIterator it = node.getNodes();
649 // while (it.hasNext()) {
650 // Node childNode = it.nextNode();
651 // debug(childNode, log);
654 // // Then output the properties
655 // PropertyIterator properties = node.getProperties();
656 // // log.debug("Property are : ");
658 // properties: while (properties.hasNext()) {
659 // Property property = properties.nextProperty();
660 // if (property.getType() == PropertyType.BINARY)
661 // continue properties;// skip
662 // if (property.getDefinition().isMultiple()) {
663 // // A multi-valued property, print all values
664 // Value[] values = property.getValues();
665 // for (int i = 0; i < values.length; i++) {
666 // log.debug(property.getPath() + "=" + values[i].getString());
669 // // A single-valued property
670 // log.debug(property.getPath() + "=" + property.getString());
673 // } catch (Exception e) {
674 // log.error("Could not debug " + node, e);
679 // /** Logs the effective access control policies */
680 // public static void logEffectiveAccessPolicies(Node node) {
682 // logEffectiveAccessPolicies(node.getSession(), node.getPath());
683 // } catch (RepositoryException e) {
684 // log.error("Cannot log effective access policies of " + node, e);
688 // /** Logs the effective access control policies */
689 // public static void logEffectiveAccessPolicies(Session session, String path) {
690 // if (!log.isDebugEnabled())
694 // AccessControlPolicy[] effectivePolicies = session.getAccessControlManager().getEffectivePolicies(path);
695 // if (effectivePolicies.length > 0) {
696 // for (AccessControlPolicy policy : effectivePolicies) {
697 // if (policy instanceof AccessControlList) {
698 // AccessControlList acl = (AccessControlList) policy;
699 // log.debug("Access control list for " + path + "\n" + accessControlListSummary(acl));
703 // log.debug("No effective access control policy for " + path);
705 // } catch (RepositoryException e) {
706 // log.error("Cannot log effective access policies of " + path, e);
710 /** Returns a human-readable summary of this access control list. */
711 public static String
accessControlListSummary(AccessControlList acl
) {
712 StringBuffer buf
= new StringBuffer("");
714 for (AccessControlEntry ace
: acl
.getAccessControlEntries()) {
715 buf
.append('\t').append(ace
.getPrincipal().getName()).append('\n');
716 for (Privilege priv
: ace
.getPrivileges())
717 buf
.append("\t\t").append(priv
.getName()).append('\n');
719 return buf
.toString();
720 } catch (RepositoryException e
) {
721 throw new JcrException("Cannot write summary of " + acl
, e
);
725 /** Copy the whole workspace via a system view XML. */
726 public static void copyWorkspaceXml(Session fromSession
, Session toSession
) {
727 Workspace fromWorkspace
= fromSession
.getWorkspace();
728 Workspace toWorkspace
= toSession
.getWorkspace();
729 String errorMsg
= "Cannot copy workspace " + fromWorkspace
+ " to " + toWorkspace
+ " via XML.";
731 try (PipedInputStream in
= new PipedInputStream(1024 * 1024);) {
733 try (PipedOutputStream out
= new PipedOutputStream(in
)) {
734 fromSession
.exportSystemView("/", out
, false, false);
736 } catch (IOException e
) {
737 throw new RuntimeException(errorMsg
, e
);
738 } catch (RepositoryException e
) {
739 throw new JcrException(errorMsg
, e
);
741 }, "Copy workspace" + fromWorkspace
+ " to " + toWorkspace
).start();
743 toSession
.importXML("/", in
, ImportUUIDBehavior
.IMPORT_UUID_COLLISION_REPLACE_EXISTING
);
745 } catch (IOException e
) {
746 throw new RuntimeException(errorMsg
, e
);
747 } catch (RepositoryException e
) {
748 throw new JcrException(errorMsg
, e
);
753 * Copies recursively the content of a node to another one. Do NOT copy the
754 * property values of {@link NodeType#MIX_CREATED} and
755 * {@link NodeType#MIX_LAST_MODIFIED}, but update the
756 * {@link Property#JCR_LAST_MODIFIED} and {@link Property#JCR_LAST_MODIFIED_BY}
757 * properties if the target node has the {@link NodeType#MIX_LAST_MODIFIED}
760 public static void copy(Node fromNode
, Node toNode
) {
762 if (toNode
.getDefinition().isProtected())
766 for (NodeType mixinType
: fromNode
.getMixinNodeTypes()) {
768 toNode
.addMixin(mixinType
.getName());
769 } catch (NoSuchNodeTypeException e
) {
770 // ignore unknown mixins
775 // process properties
776 PropertyIterator pit
= fromNode
.getProperties();
777 properties
: while (pit
.hasNext()) {
778 Property fromProperty
= pit
.nextProperty();
779 String propertyName
= fromProperty
.getName();
780 if (toNode
.hasProperty(propertyName
) && toNode
.getProperty(propertyName
).getDefinition().isProtected())
783 if (fromProperty
.getDefinition().isProtected())
786 if (propertyName
.equals("jcr:created") || propertyName
.equals("jcr:createdBy")
787 || propertyName
.equals("jcr:lastModified") || propertyName
.equals("jcr:lastModifiedBy"))
790 if (fromProperty
.isMultiple()) {
791 toNode
.setProperty(propertyName
, fromProperty
.getValues());
793 toNode
.setProperty(propertyName
, fromProperty
.getValue());
797 // update jcr:lastModified and jcr:lastModifiedBy in toNode in case
798 // they existed, before adding the mixins
799 updateLastModified(toNode
, true);
801 // process children nodes
802 NodeIterator nit
= fromNode
.getNodes();
803 while (nit
.hasNext()) {
804 Node fromChild
= nit
.nextNode();
805 Integer index
= fromChild
.getIndex();
806 String nodeRelPath
= fromChild
.getName() + "[" + index
+ "]";
808 if (toNode
.hasNode(nodeRelPath
))
809 toChild
= toNode
.getNode(nodeRelPath
);
812 toChild
= toNode
.addNode(fromChild
.getName(), fromChild
.getPrimaryNodeType().getName());
813 } catch (NoSuchNodeTypeException e
) {
814 // ignore unknown primary types
819 copy(fromChild
, toChild
);
821 } catch (RepositoryException e
) {
822 throw new JcrException("Cannot copy " + fromNode
+ " to " + toNode
, e
);
827 * Check whether all first-level properties (except jcr:* properties) are equal.
828 * Skip jcr:* properties
830 public static Boolean
allPropertiesEquals(Node reference
, Node observed
, Boolean onlyCommonProperties
) {
832 PropertyIterator pit
= reference
.getProperties();
833 props
: while (pit
.hasNext()) {
834 Property propReference
= pit
.nextProperty();
835 String propName
= propReference
.getName();
836 if (propName
.startsWith("jcr:"))
839 if (!observed
.hasProperty(propName
))
840 if (onlyCommonProperties
)
844 // TODO: deal with multiple property values?
845 if (!observed
.getProperty(propName
).getValue().equals(propReference
.getValue()))
849 } catch (RepositoryException e
) {
850 throw new JcrException("Cannot check all properties equals of " + reference
+ " and " + observed
, e
);
854 public static Map
<String
, PropertyDiff
> diffProperties(Node reference
, Node observed
) {
855 Map
<String
, PropertyDiff
> diffs
= new TreeMap
<String
, PropertyDiff
>();
856 diffPropertiesLevel(diffs
, null, reference
, observed
);
861 * Compare the properties of two nodes. Recursivity to child nodes is not yet
862 * supported. Skip jcr:* properties.
864 static void diffPropertiesLevel(Map
<String
, PropertyDiff
> diffs
, String baseRelPath
, Node reference
,
867 // check removed and modified
868 PropertyIterator pit
= reference
.getProperties();
869 props
: while (pit
.hasNext()) {
870 Property p
= pit
.nextProperty();
871 String name
= p
.getName();
872 if (name
.startsWith("jcr:"))
875 if (!observed
.hasProperty(name
)) {
876 String relPath
= propertyRelPath(baseRelPath
, name
);
877 PropertyDiff pDiff
= new PropertyDiff(PropertyDiff
.REMOVED
, relPath
, p
.getValue(), null);
878 diffs
.put(relPath
, pDiff
);
880 if (p
.isMultiple()) {
881 // FIXME implement multiple
883 Value referenceValue
= p
.getValue();
884 Value newValue
= observed
.getProperty(name
).getValue();
885 if (!referenceValue
.equals(newValue
)) {
886 String relPath
= propertyRelPath(baseRelPath
, name
);
887 PropertyDiff pDiff
= new PropertyDiff(PropertyDiff
.MODIFIED
, relPath
, referenceValue
,
889 diffs
.put(relPath
, pDiff
);
895 pit
= observed
.getProperties();
896 props
: while (pit
.hasNext()) {
897 Property p
= pit
.nextProperty();
898 String name
= p
.getName();
899 if (name
.startsWith("jcr:"))
901 if (!reference
.hasProperty(name
)) {
902 if (p
.isMultiple()) {
903 // FIXME implement multiple
905 String relPath
= propertyRelPath(baseRelPath
, name
);
906 PropertyDiff pDiff
= new PropertyDiff(PropertyDiff
.ADDED
, relPath
, null, p
.getValue());
907 diffs
.put(relPath
, pDiff
);
911 } catch (RepositoryException e
) {
912 throw new JcrException("Cannot diff " + reference
+ " and " + observed
, e
);
917 * Compare only a restricted list of properties of two nodes. No recursivity.
920 public static Map
<String
, PropertyDiff
> diffProperties(Node reference
, Node observed
, List
<String
> properties
) {
921 Map
<String
, PropertyDiff
> diffs
= new TreeMap
<String
, PropertyDiff
>();
923 Iterator
<String
> pit
= properties
.iterator();
925 props
: while (pit
.hasNext()) {
926 String name
= pit
.next();
927 if (!reference
.hasProperty(name
)) {
928 if (!observed
.hasProperty(name
))
930 Value val
= observed
.getProperty(name
).getValue();
932 // empty String but not null
933 if ("".equals(val
.getString()))
935 } catch (Exception e
) {
936 // not parseable as String, silent
938 PropertyDiff pDiff
= new PropertyDiff(PropertyDiff
.ADDED
, name
, null, val
);
939 diffs
.put(name
, pDiff
);
940 } else if (!observed
.hasProperty(name
)) {
941 PropertyDiff pDiff
= new PropertyDiff(PropertyDiff
.REMOVED
, name
,
942 reference
.getProperty(name
).getValue(), null);
943 diffs
.put(name
, pDiff
);
945 Value referenceValue
= reference
.getProperty(name
).getValue();
946 Value newValue
= observed
.getProperty(name
).getValue();
947 if (!referenceValue
.equals(newValue
)) {
948 PropertyDiff pDiff
= new PropertyDiff(PropertyDiff
.MODIFIED
, name
, referenceValue
, newValue
);
949 diffs
.put(name
, pDiff
);
953 } catch (RepositoryException e
) {
954 throw new JcrException("Cannot diff " + reference
+ " and " + observed
, e
);
959 /** Builds a property relPath to be used in the diff. */
960 private static String
propertyRelPath(String baseRelPath
, String propertyName
) {
961 if (baseRelPath
== null)
964 return baseRelPath
+ '/' + propertyName
;
968 * Normalizes a name so that it can be stored in contexts not supporting names
969 * with ':' (typically databases). Replaces ':' by '_'.
971 public static String
normalize(String name
) {
972 return name
.replace(':', '_');
976 * Replaces characters which are invalid in a JCR name by '_'. Currently not
979 * @see JcrUtils#INVALID_NAME_CHARACTERS
981 public static String
replaceInvalidChars(String name
) {
982 return replaceInvalidChars(name
, '_');
986 * Replaces characters which are invalid in a JCR name. Currently not
989 * @see JcrUtils#INVALID_NAME_CHARACTERS
991 public static String
replaceInvalidChars(String name
, char replacement
) {
992 boolean modified
= false;
993 char[] arr
= name
.toCharArray();
994 for (int i
= 0; i
< arr
.length
; i
++) {
996 invalid
: for (char invalid
: INVALID_NAME_CHARACTERS
) {
998 arr
[i
] = replacement
;
1005 return new String(arr
);
1007 // do not create new object if unnecessary
1012 // * Removes forbidden characters from a path, replacing them with '_'
1014 // * @deprecated use {@link #replaceInvalidChars(String)} instead
1016 // public static String removeForbiddenCharacters(String str) {
1017 // return str.replace('[', '_').replace(']', '_').replace('/', '_').replace('*',
1022 /** Cleanly disposes a {@link Binary} even if it is null. */
1023 public static void closeQuietly(Binary binary
) {
1029 /** Retrieve a {@link Binary} as a byte array */
1030 public static byte[] getBinaryAsBytes(Property property
) {
1031 try (ByteArrayOutputStream out
= new ByteArrayOutputStream();
1032 Bin binary
= new Bin(property
);
1033 InputStream in
= binary
.getStream()) {
1034 IOUtils
.copy(in
, out
);
1035 return out
.toByteArray();
1036 } catch (RepositoryException e
) {
1037 throw new JcrException("Cannot read binary " + property
+ " as bytes", e
);
1038 } catch (IOException e
) {
1039 throw new RuntimeException("Cannot read binary " + property
+ " as bytes", e
);
1043 /** Writes a {@link Binary} from a byte array */
1044 public static void setBinaryAsBytes(Node node
, String property
, byte[] bytes
) {
1045 Binary binary
= null;
1046 try (InputStream in
= new ByteArrayInputStream(bytes
)) {
1047 binary
= node
.getSession().getValueFactory().createBinary(in
);
1048 node
.setProperty(property
, binary
);
1049 } catch (RepositoryException e
) {
1050 throw new JcrException("Cannot set binary " + property
+ " as bytes", e
);
1051 } catch (IOException e
) {
1052 throw new RuntimeException("Cannot set binary " + property
+ " as bytes", e
);
1054 closeQuietly(binary
);
1058 /** Writes a {@link Binary} from a byte array */
1059 public static void setBinaryAsBytes(Property prop
, byte[] bytes
) {
1060 Binary binary
= null;
1061 try (InputStream in
= new ByteArrayInputStream(bytes
)) {
1062 binary
= prop
.getSession().getValueFactory().createBinary(in
);
1063 prop
.setValue(binary
);
1064 } catch (RepositoryException e
) {
1065 throw new JcrException("Cannot set binary " + prop
+ " as bytes", e
);
1066 } catch (IOException e
) {
1067 throw new RuntimeException("Cannot set binary " + prop
+ " as bytes", e
);
1069 closeQuietly(binary
);
1074 * Creates depth from a string (typically a username) by adding levels based on
1075 * its first characters: "aBcD",2 becomes a/aB
1077 public static String
firstCharsToPath(String str
, Integer nbrOfChars
) {
1078 if (str
.length() < nbrOfChars
)
1079 throw new IllegalArgumentException("String " + str
+ " length must be greater or equal than " + nbrOfChars
);
1080 StringBuffer path
= new StringBuffer("");
1081 StringBuffer curr
= new StringBuffer("");
1082 for (int i
= 0; i
< nbrOfChars
; i
++) {
1083 curr
.append(str
.charAt(i
));
1085 if (i
< nbrOfChars
- 1)
1088 return path
.toString();
1092 * Discards the current changes in the session attached to this node. To be used
1093 * typically in a catch block.
1095 * @see #discardQuietly(Session)
1097 public static void discardUnderlyingSessionQuietly(Node node
) {
1099 discardQuietly(node
.getSession());
1100 } catch (RepositoryException e
) {
1106 * Discards the current changes in a session by calling
1107 * {@link Session#refresh(boolean)} with <code>false</code>, only logging
1108 * potential errors when doing so. To be used typically in a catch block.
1110 public static void discardQuietly(Session session
) {
1112 if (session
!= null)
1113 session
.refresh(false);
1114 } catch (RepositoryException e
) {
1120 * Login to a workspace with implicit credentials, creates the workspace with
1121 * these credentials if it does not already exist.
1123 public static Session
loginOrCreateWorkspace(Repository repository
, String workspaceName
)
1124 throws RepositoryException
{
1125 return loginOrCreateWorkspace(repository
, workspaceName
, null);
1129 * Login to a workspace with implicit credentials, creates the workspace with
1130 * these credentials if it does not already exist.
1132 public static Session
loginOrCreateWorkspace(Repository repository
, String workspaceName
, Credentials credentials
)
1133 throws RepositoryException
{
1134 Session workspaceSession
= null;
1135 Session defaultSession
= null;
1138 workspaceSession
= repository
.login(credentials
, workspaceName
);
1139 } catch (NoSuchWorkspaceException e
) {
1140 // try to create workspace
1141 defaultSession
= repository
.login(credentials
);
1142 defaultSession
.getWorkspace().createWorkspace(workspaceName
);
1143 workspaceSession
= repository
.login(credentials
, workspaceName
);
1145 return workspaceSession
;
1147 logoutQuietly(defaultSession
);
1152 * Logs out the session, not throwing any exception, even if it is null.
1153 * {@link Jcr#logout(Session)} should rather be used.
1155 public static void logoutQuietly(Session session
) {
1156 Jcr
.logout(session
);
1158 // if (session != null)
1159 // if (session.isLive())
1160 // session.logout();
1161 // } catch (Exception e) {
1167 * Convenient method to add a listener. uuids passed as null, deep=true,
1168 * local=true, only one node type
1170 public static void addListener(Session session
, EventListener listener
, int eventTypes
, String basePath
,
1173 session
.getWorkspace().getObservationManager().addEventListener(listener
, eventTypes
, basePath
, true, null,
1174 nodeType
== null ?
null : new String
[] { nodeType
}, true);
1175 } catch (RepositoryException e
) {
1176 throw new JcrException("Cannot add JCR listener " + listener
+ " to session " + session
, e
);
1180 /** Removes a listener without throwing exception */
1181 public static void removeListenerQuietly(Session session
, EventListener listener
) {
1182 if (session
== null || !session
.isLive())
1185 session
.getWorkspace().getObservationManager().removeEventListener(listener
);
1186 } catch (RepositoryException e
) {
1192 * Quietly unregisters an {@link EventListener} from the udnerlying workspace of
1195 public static void unregisterQuietly(Node node
, EventListener eventListener
) {
1197 unregisterQuietly(node
.getSession().getWorkspace(), eventListener
);
1198 } catch (RepositoryException e
) {
1203 /** Quietly unregisters an {@link EventListener} from this workspace */
1204 public static void unregisterQuietly(Workspace workspace
, EventListener eventListener
) {
1205 if (eventListener
== null)
1208 workspace
.getObservationManager().removeEventListener(eventListener
);
1209 } catch (RepositoryException e
) {
1215 * Checks whether {@link Property#JCR_LAST_MODIFIED} or (afterwards)
1216 * {@link Property#JCR_CREATED} are set and returns it as an {@link Instant}.
1218 public static Instant
getModified(Node node
) {
1219 Calendar calendar
= null;
1221 if (node
.hasProperty(Property
.JCR_LAST_MODIFIED
))
1222 calendar
= node
.getProperty(Property
.JCR_LAST_MODIFIED
).getDate();
1223 else if (node
.hasProperty(Property
.JCR_CREATED
))
1224 calendar
= node
.getProperty(Property
.JCR_CREATED
).getDate();
1226 throw new IllegalArgumentException("No modification time found in " + node
);
1227 return calendar
.toInstant();
1228 } catch (RepositoryException e
) {
1229 throw new JcrException("Cannot get modification time for " + node
, e
);
1235 * Get {@link Property#JCR_CREATED} as an {@link Instant}, if it is set.
1237 public static Instant
getCreated(Node node
) {
1238 Calendar calendar
= null;
1240 if (node
.hasProperty(Property
.JCR_CREATED
))
1241 calendar
= node
.getProperty(Property
.JCR_CREATED
).getDate();
1243 throw new IllegalArgumentException("No created time found in " + node
);
1244 return calendar
.toInstant();
1245 } catch (RepositoryException e
) {
1246 throw new JcrException("Cannot get created time for " + node
, e
);
1252 * Updates the {@link Property#JCR_LAST_MODIFIED} property with the current time
1253 * and the {@link Property#JCR_LAST_MODIFIED_BY} property with the underlying
1256 public static void updateLastModified(Node node
) {
1257 updateLastModified(node
, false);
1261 * Updates the {@link Property#JCR_LAST_MODIFIED} property with the current time
1262 * and the {@link Property#JCR_LAST_MODIFIED_BY} property with the underlying
1263 * session user id. In Jackrabbit 2.x,
1264 * <a href="https://issues.apache.org/jira/browse/JCR-2233">these properties are
1265 * not automatically updated</a>, hence the need for manual update. The session
1268 public static void updateLastModified(Node node
, boolean addMixin
) {
1270 if (addMixin
&& !node
.isNodeType(NodeType
.MIX_LAST_MODIFIED
))
1271 node
.addMixin(NodeType
.MIX_LAST_MODIFIED
);
1272 node
.setProperty(Property
.JCR_LAST_MODIFIED
, new GregorianCalendar());
1273 node
.setProperty(Property
.JCR_LAST_MODIFIED_BY
, node
.getSession().getUserID());
1274 } catch (RepositoryException e
) {
1275 throw new JcrException("Cannot update last modified on " + node
, e
);
1280 * Update lastModified recursively until this parent.
1282 * @param node the node
1283 * @param untilPath the base path, null is equivalent to "/"
1285 public static void updateLastModifiedAndParents(Node node
, String untilPath
) {
1286 updateLastModifiedAndParents(node
, untilPath
, true);
1290 * Update lastModified recursively until this parent.
1292 * @param node the node
1293 * @param untilPath the base path, null is equivalent to "/"
1295 public static void updateLastModifiedAndParents(Node node
, String untilPath
, boolean addMixin
) {
1297 if (untilPath
!= null && !node
.getPath().startsWith(untilPath
))
1298 throw new IllegalArgumentException(node
+ " is not under " + untilPath
);
1299 updateLastModified(node
, addMixin
);
1300 if (untilPath
== null) {
1301 if (!node
.getPath().equals("/"))
1302 updateLastModifiedAndParents(node
.getParent(), untilPath
, addMixin
);
1304 if (!node
.getPath().equals(untilPath
))
1305 updateLastModifiedAndParents(node
.getParent(), untilPath
, addMixin
);
1307 } catch (RepositoryException e
) {
1308 throw new JcrException("Cannot update lastModified from " + node
+ " until " + untilPath
, e
);
1313 * Returns a String representing the short version (see
1314 * <a href="http://jackrabbit.apache.org/node-type-notation.html"> Node type
1315 * Notation </a> attributes grammar) of the main business attributes of this
1316 * property definition
1320 public static String
getPropertyDefinitionAsString(Property prop
) {
1321 StringBuffer sbuf
= new StringBuffer();
1323 if (prop
.getDefinition().isAutoCreated())
1325 if (prop
.getDefinition().isMandatory())
1327 if (prop
.getDefinition().isProtected())
1329 if (prop
.getDefinition().isMultiple())
1331 } catch (RepositoryException re
) {
1332 throw new JcrException("unexpected error while getting property definition as String", re
);
1334 return sbuf
.toString();
1338 * Estimate the sub tree size from current node. Computation is based on the Jcr
1339 * {@link Property#getLength()} method. Note : it is not the exact size used on
1340 * the disk by the current part of the JCR Tree.
1343 public static long getNodeApproxSize(Node node
) {
1344 long curNodeSize
= 0;
1346 PropertyIterator pi
= node
.getProperties();
1347 while (pi
.hasNext()) {
1348 Property prop
= pi
.nextProperty();
1349 if (prop
.isMultiple()) {
1350 int nb
= prop
.getLengths().length
;
1351 for (int i
= 0; i
< nb
; i
++) {
1352 curNodeSize
+= (prop
.getLengths()[i
] > 0 ? prop
.getLengths()[i
] : 0);
1355 curNodeSize
+= (prop
.getLength() > 0 ? prop
.getLength() : 0);
1358 NodeIterator ni
= node
.getNodes();
1359 while (ni
.hasNext())
1360 curNodeSize
+= getNodeApproxSize(ni
.nextNode());
1362 } catch (RepositoryException re
) {
1363 throw new JcrException("Unexpected error while recursively determining node size.", re
);
1372 * Convenience method for adding a single privilege to a principal (user or
1373 * role), typically jcr:all
1375 public synchronized static void addPrivilege(Session session
, String path
, String principal
, String privilege
)
1376 throws RepositoryException
{
1377 List
<Privilege
> privileges
= new ArrayList
<Privilege
>();
1378 privileges
.add(session
.getAccessControlManager().privilegeFromName(privilege
));
1379 addPrivileges(session
, path
, new SimplePrincipal(principal
), privileges
);
1383 * Add privileges on a path to a {@link Principal}. The path must already exist.
1384 * Session is saved. Synchronized to prevent concurrent modifications of the
1387 public synchronized static Boolean
addPrivileges(Session session
, String path
, Principal principal
,
1388 List
<Privilege
> privs
) throws RepositoryException
{
1389 // make sure the session is in line with the persisted state
1390 session
.refresh(false);
1391 AccessControlManager acm
= session
.getAccessControlManager();
1392 AccessControlList acl
= getAccessControlList(acm
, path
);
1394 accessControlEntries
: for (AccessControlEntry ace
: acl
.getAccessControlEntries()) {
1395 Principal currentPrincipal
= ace
.getPrincipal();
1396 if (currentPrincipal
.getName().equals(principal
.getName())) {
1397 Privilege
[] currentPrivileges
= ace
.getPrivileges();
1398 if (currentPrivileges
.length
!= privs
.size())
1399 break accessControlEntries
;
1400 for (int i
= 0; i
< currentPrivileges
.length
; i
++) {
1401 Privilege currP
= currentPrivileges
[i
];
1402 Privilege p
= privs
.get(i
);
1403 if (!currP
.getName().equals(p
.getName())) {
1404 break accessControlEntries
;
1411 Privilege
[] privileges
= privs
.toArray(new Privilege
[privs
.size()]);
1412 acl
.addAccessControlEntry(principal
, privileges
);
1413 acm
.setPolicy(path
, acl
);
1414 // if (log.isDebugEnabled()) {
1415 // StringBuffer privBuf = new StringBuffer();
1416 // for (Privilege priv : privs)
1417 // privBuf.append(priv.getName());
1418 // log.debug("Added privileges " + privBuf + " to " + principal.getName() + " on " + path + " in '"
1419 // + session.getWorkspace().getName() + "'");
1421 session
.refresh(true);
1427 * Gets the first available access control list for this path, throws exception
1430 public synchronized static AccessControlList
getAccessControlList(AccessControlManager acm
, String path
)
1431 throws RepositoryException
{
1432 // search for an access control list
1433 AccessControlList acl
= null;
1434 AccessControlPolicyIterator policyIterator
= acm
.getApplicablePolicies(path
);
1435 applicablePolicies
: if (policyIterator
.hasNext()) {
1436 while (policyIterator
.hasNext()) {
1437 AccessControlPolicy acp
= policyIterator
.nextAccessControlPolicy();
1438 if (acp
instanceof AccessControlList
) {
1439 acl
= ((AccessControlList
) acp
);
1440 break applicablePolicies
;
1444 AccessControlPolicy
[] existingPolicies
= acm
.getPolicies(path
);
1445 existingPolicies
: for (AccessControlPolicy acp
: existingPolicies
) {
1446 if (acp
instanceof AccessControlList
) {
1447 acl
= ((AccessControlList
) acp
);
1448 break existingPolicies
;
1455 throw new IllegalArgumentException("ACL not found at " + path
);
1458 /** Clear authorizations for a user at this path */
1459 public synchronized static void clearAccessControList(Session session
, String path
, String username
)
1460 throws RepositoryException
{
1461 AccessControlManager acm
= session
.getAccessControlManager();
1462 AccessControlList acl
= getAccessControlList(acm
, path
);
1463 for (AccessControlEntry ace
: acl
.getAccessControlEntries()) {
1464 if (ace
.getPrincipal().getName().equals(username
)) {
1465 acl
.removeAccessControlEntry(ace
);
1468 // the new access control list must be applied otherwise this call:
1469 // acl.removeAccessControlEntry(ace); has no effect
1470 acm
.setPolicy(path
, acl
);
1477 * Creates the nodes making the path as {@link NodeType#NT_FOLDER}
1479 public static Node
mkfolders(Session session
, String path
) {
1480 return mkdirs(session
, path
, NodeType
.NT_FOLDER
, NodeType
.NT_FOLDER
, false);
1484 * Copy only nt:folder and nt:file, without their additional types and
1487 * @param recursive if true copies folders as well, otherwise only first level
1489 * @return how many files were copied
1491 public static Long
copyFiles(Node fromNode
, Node toNode
, Boolean recursive
, JcrMonitor monitor
, boolean onlyAdd
) {
1494 // Binary binary = null;
1495 // InputStream in = null;
1497 NodeIterator fromChildren
= fromNode
.getNodes();
1498 children
: while (fromChildren
.hasNext()) {
1499 if (monitor
!= null && monitor
.isCanceled())
1500 throw new IllegalStateException("Copy cancelled before it was completed");
1502 Node fromChild
= fromChildren
.nextNode();
1503 String fileName
= fromChild
.getName();
1504 if (fromChild
.isNodeType(NodeType
.NT_FILE
)) {
1505 if (onlyAdd
&& toNode
.hasNode(fileName
)) {
1506 monitor
.subTask("Skip existing " + fileName
);
1510 if (monitor
!= null)
1511 monitor
.subTask("Copy " + fileName
);
1512 try (Bin binary
= new Bin(fromChild
.getNode(Node
.JCR_CONTENT
).getProperty(Property
.JCR_DATA
));
1513 InputStream in
= binary
.getStream();) {
1514 copyStreamAsFile(toNode
, fileName
, in
);
1515 } catch (IOException e
) {
1516 throw new RuntimeException("Cannot copy " + fileName
+ " to " + toNode
, e
);
1520 toNode
.getSession().save();
1523 // if (log.isDebugEnabled())
1524 // log.debug("Copied file " + fromChild.getPath());
1525 if (monitor
!= null)
1527 } else if (fromChild
.isNodeType(NodeType
.NT_FOLDER
) && recursive
) {
1529 if (toNode
.hasNode(fileName
)) {
1530 toChildFolder
= toNode
.getNode(fileName
);
1531 if (!toChildFolder
.isNodeType(NodeType
.NT_FOLDER
))
1532 throw new IllegalArgumentException(toChildFolder
+ " is not of type nt:folder");
1534 toChildFolder
= toNode
.addNode(fileName
, NodeType
.NT_FOLDER
);
1537 toNode
.getSession().save();
1539 count
= count
+ copyFiles(fromChild
, toChildFolder
, recursive
, monitor
, onlyAdd
);
1543 } catch (RepositoryException e
) {
1544 throw new JcrException("Cannot copy files between " + fromNode
+ " and " + toNode
, e
);
1546 // in case there was an exception
1547 // IOUtils.closeQuietly(in);
1548 // closeQuietly(binary);
1553 * Iteratively count all file nodes in subtree, inefficient but can be useful
1554 * when query are poorly supported, such as in remoting.
1556 public static Long
countFiles(Node node
) {
1557 Long localCount
= 0l;
1559 for (NodeIterator nit
= node
.getNodes(); nit
.hasNext();) {
1560 Node child
= nit
.nextNode();
1561 if (child
.isNodeType(NodeType
.NT_FOLDER
))
1562 localCount
= localCount
+ countFiles(child
);
1563 else if (child
.isNodeType(NodeType
.NT_FILE
))
1564 localCount
= localCount
+ 1;
1566 } catch (RepositoryException e
) {
1567 throw new JcrException("Cannot count all children of " + node
, e
);
1573 * Copy a file as an nt:file, assuming an nt:folder hierarchy. The session is
1576 * @return the created file node
1578 public static Node
copyFile(Node folderNode
, File file
) {
1579 try (InputStream in
= new FileInputStream(file
)) {
1580 return copyStreamAsFile(folderNode
, file
.getName(), in
);
1581 } catch (IOException e
) {
1582 throw new RuntimeException("Cannot copy file " + file
+ " under " + folderNode
, e
);
1586 /** Copy bytes as an nt:file */
1587 public static Node
copyBytesAsFile(Node folderNode
, String fileName
, byte[] bytes
) {
1588 // InputStream in = null;
1589 try (InputStream in
= new ByteArrayInputStream(bytes
)) {
1590 // in = new ByteArrayInputStream(bytes);
1591 return copyStreamAsFile(folderNode
, fileName
, in
);
1592 } catch (IOException e
) {
1593 throw new RuntimeException("Cannot copy file " + fileName
+ " under " + folderNode
, e
);
1595 // IOUtils.closeQuietly(in);
1600 * Copy a stream as an nt:file, assuming an nt:folder hierarchy. The session is
1603 * @return the created file node
1605 public static Node
copyStreamAsFile(Node folderNode
, String fileName
, InputStream in
) {
1606 Binary binary
= null;
1610 if (folderNode
.hasNode(fileName
)) {
1611 fileNode
= folderNode
.getNode(fileName
);
1612 if (!fileNode
.isNodeType(NodeType
.NT_FILE
))
1613 throw new IllegalArgumentException(fileNode
+ " is not of type nt:file");
1614 // we assume that the content node is already there
1615 contentNode
= fileNode
.getNode(Node
.JCR_CONTENT
);
1617 fileNode
= folderNode
.addNode(fileName
, NodeType
.NT_FILE
);
1618 contentNode
= fileNode
.addNode(Node
.JCR_CONTENT
, NodeType
.NT_UNSTRUCTURED
);
1620 binary
= contentNode
.getSession().getValueFactory().createBinary(in
);
1621 contentNode
.setProperty(Property
.JCR_DATA
, binary
);
1623 } catch (RepositoryException e
) {
1624 throw new JcrException("Cannot create file node " + fileName
+ " under " + folderNode
, e
);
1626 closeQuietly(binary
);
1630 /** Read an an nt:file as an {@link InputStream}. */
1631 public static InputStream
getFileAsStream(Node fileNode
) throws RepositoryException
{
1632 return fileNode
.getNode(Node
.JCR_CONTENT
).getProperty(Property
.JCR_DATA
).getBinary().getStream();
1636 * Computes the checksum of an nt:file.
1638 * @deprecated use separate digest utilities
1641 public static String
checksumFile(Node fileNode
, String algorithm
) {
1642 try (InputStream in
= fileNode
.getNode(Node
.JCR_CONTENT
).getProperty(Property
.JCR_DATA
).getBinary()
1644 return digest(algorithm
, in
);
1645 } catch (IOException e
) {
1646 throw new RuntimeException("Cannot checksum file " + fileNode
+ " with algorithm " + algorithm
, e
);
1647 } catch (RepositoryException e
) {
1648 throw new JcrException("Cannot checksum file " + fileNode
+ " with algorithm " + algorithm
, e
);
1653 private static String
digest(String algorithm
, InputStream in
) {
1654 final Integer byteBufferCapacity
= 100 * 1024;// 100 KB
1656 MessageDigest digest
= MessageDigest
.getInstance(algorithm
);
1657 byte[] buffer
= new byte[byteBufferCapacity
];
1659 while ((read
= in
.read(buffer
)) > 0) {
1660 digest
.update(buffer
, 0, read
);
1663 byte[] checksum
= digest
.digest();
1664 String res
= encodeHexString(checksum
);
1666 } catch (IOException e
) {
1667 throw new RuntimeException("Cannot digest with algorithm " + algorithm
, e
);
1668 } catch (NoSuchAlgorithmException e
) {
1669 throw new IllegalArgumentException("Cannot digest with algorithm " + algorithm
, e
);
1675 * http://stackoverflow.com/questions/9655181/how-to-convert-a-byte-array-to
1676 * -a-hex-string-in-java
1679 private static String
encodeHexString(byte[] bytes
) {
1680 final char[] hexArray
= "0123456789abcdef".toCharArray();
1681 char[] hexChars
= new char[bytes
.length
* 2];
1682 for (int j
= 0; j
< bytes
.length
; j
++) {
1683 int v
= bytes
[j
] & 0xFF;
1684 hexChars
[j
* 2] = hexArray
[v
>>> 4];
1685 hexChars
[j
* 2 + 1] = hexArray
[v
& 0x0F];
1687 return new String(hexChars
);