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
.OutputStream
;
10 import java
.io
.PipedInputStream
;
11 import java
.io
.PipedOutputStream
;
12 import java
.net
.MalformedURLException
;
14 import java
.nio
.file
.Files
;
15 import java
.nio
.file
.Path
;
16 import java
.security
.MessageDigest
;
17 import java
.security
.NoSuchAlgorithmException
;
18 import java
.security
.Principal
;
19 import java
.text
.DateFormat
;
20 import java
.text
.ParseException
;
21 import java
.time
.Instant
;
22 import java
.util
.ArrayList
;
23 import java
.util
.Calendar
;
24 import java
.util
.Collections
;
25 import java
.util
.Date
;
26 import java
.util
.GregorianCalendar
;
27 import java
.util
.Iterator
;
28 import java
.util
.List
;
30 import java
.util
.TreeMap
;
32 import javax
.jcr
.Binary
;
33 import javax
.jcr
.Credentials
;
34 import javax
.jcr
.ImportUUIDBehavior
;
35 import javax
.jcr
.NamespaceRegistry
;
36 import javax
.jcr
.NoSuchWorkspaceException
;
37 import javax
.jcr
.Node
;
38 import javax
.jcr
.NodeIterator
;
39 import javax
.jcr
.Property
;
40 import javax
.jcr
.PropertyIterator
;
41 import javax
.jcr
.Repository
;
42 import javax
.jcr
.RepositoryException
;
43 import javax
.jcr
.Session
;
44 import javax
.jcr
.Value
;
45 import javax
.jcr
.Workspace
;
46 import javax
.jcr
.nodetype
.NoSuchNodeTypeException
;
47 import javax
.jcr
.nodetype
.NodeType
;
48 import javax
.jcr
.observation
.EventListener
;
49 import javax
.jcr
.query
.Query
;
50 import javax
.jcr
.query
.QueryResult
;
51 import javax
.jcr
.security
.AccessControlEntry
;
52 import javax
.jcr
.security
.AccessControlList
;
53 import javax
.jcr
.security
.AccessControlManager
;
54 import javax
.jcr
.security
.AccessControlPolicy
;
55 import javax
.jcr
.security
.AccessControlPolicyIterator
;
56 import javax
.jcr
.security
.Privilege
;
58 import org
.apache
.commons
.io
.IOUtils
;
60 /** Utility methods to simplify common JCR operations. */
61 public class JcrUtils
{
63 // final private static Log log = LogFactory.getLog(JcrUtils.class);
66 * Not complete yet. See
67 * http://www.day.com/specs/jcr/2.0/3_Repository_Model.html#3.2.2%20Local
70 public final static char[] INVALID_NAME_CHARACTERS
= { '/', ':', '[', ']', '|', '*', /* invalid for XML: */ '<',
73 /** Prevents instantiation */
78 * Queries one single node.
80 * @return one single node or null if none was found
81 * @throws JcrException if more than one node was found
83 public static Node
querySingleNode(Query query
) {
84 NodeIterator nodeIterator
;
86 QueryResult queryResult
= query
.execute();
87 nodeIterator
= queryResult
.getNodes();
88 } catch (RepositoryException e
) {
89 throw new JcrException("Cannot execute query " + query
, e
);
92 if (nodeIterator
.hasNext())
93 node
= nodeIterator
.nextNode();
97 if (nodeIterator
.hasNext())
98 throw new IllegalArgumentException("Query returned more than one node.");
102 /** Retrieves the node name from the provided path */
103 public static String
nodeNameFromPath(String path
) {
104 if (path
.equals("/"))
106 if (path
.charAt(0) != '/')
107 throw new IllegalArgumentException("Path " + path
+ " must start with a '/'");
109 if (pathT
.charAt(pathT
.length() - 1) == '/')
110 pathT
= pathT
.substring(0, pathT
.length() - 2);
112 int index
= pathT
.lastIndexOf('/');
113 return pathT
.substring(index
+ 1);
116 /** Retrieves the parent path of the provided path */
117 public static String
parentPath(String path
) {
118 if (path
.equals("/"))
119 throw new IllegalArgumentException("Root path '/' has no parent path");
120 if (path
.charAt(0) != '/')
121 throw new IllegalArgumentException("Path " + path
+ " must start with a '/'");
123 if (pathT
.charAt(pathT
.length() - 1) == '/')
124 pathT
= pathT
.substring(0, pathT
.length() - 2);
126 int index
= pathT
.lastIndexOf('/');
127 return pathT
.substring(0, index
);
130 /** The provided data as a path ('/' at the end, not the beginning) */
131 public static String
dateAsPath(Calendar cal
) {
132 return dateAsPath(cal
, false);
136 * Creates a deep path based on a URL:
137 * http://subdomain.example.com/to/content?args becomes
138 * com/example/subdomain/to/content
140 public static String
urlAsPath(String url
) {
142 URL u
= new URL(url
);
143 StringBuffer path
= new StringBuffer(url
.length());
145 path
.append(hostAsPath(u
.getHost()));
146 // we don't put port since it may not always be there and may change
147 path
.append(u
.getPath());
148 return path
.toString();
149 } catch (MalformedURLException e
) {
150 throw new IllegalArgumentException("Cannot generate URL path for " + url
, e
);
154 /** Set the {@link NodeType#NT_ADDRESS} properties based on this URL. */
155 public static void urlToAddressProperties(Node node
, String url
) {
157 URL u
= new URL(url
);
158 node
.setProperty(Property
.JCR_PROTOCOL
, u
.getProtocol());
159 node
.setProperty(Property
.JCR_HOST
, u
.getHost());
160 node
.setProperty(Property
.JCR_PORT
, Integer
.toString(u
.getPort()));
161 node
.setProperty(Property
.JCR_PATH
, normalizePath(u
.getPath()));
162 } catch (RepositoryException e
) {
163 throw new JcrException("Cannot set URL " + url
+ " as nt:address properties", e
);
164 } catch (MalformedURLException e
) {
165 throw new IllegalArgumentException("Cannot set URL " + url
+ " as nt:address properties", e
);
169 /** Build URL based on the {@link NodeType#NT_ADDRESS} properties. */
170 public static String
urlFromAddressProperties(Node node
) {
172 URL u
= new URL(node
.getProperty(Property
.JCR_PROTOCOL
).getString(),
173 node
.getProperty(Property
.JCR_HOST
).getString(),
174 (int) node
.getProperty(Property
.JCR_PORT
).getLong(),
175 node
.getProperty(Property
.JCR_PATH
).getString());
177 } catch (RepositoryException e
) {
178 throw new JcrException("Cannot get URL from nt:address properties of " + node
, e
);
179 } catch (MalformedURLException e
) {
180 throw new IllegalArgumentException("Cannot get URL from nt:address properties of " + node
, e
);
189 * Make sure that: starts with '/', do not end with '/', do not have '//'
191 public static String
normalizePath(String path
) {
192 List
<String
> tokens
= tokenize(path
);
193 StringBuffer buf
= new StringBuffer(path
.length());
194 for (String token
: tokens
) {
198 return buf
.toString();
202 * Creates a path from a FQDN, inverting the order of the component:
203 * www.argeo.org becomes org.argeo.www
205 public static String
hostAsPath(String host
) {
206 StringBuffer path
= new StringBuffer(host
.length());
207 String
[] hostTokens
= host
.split("\\.");
208 for (int i
= hostTokens
.length
- 1; i
>= 0; i
--) {
209 path
.append(hostTokens
[i
]);
213 return path
.toString();
217 * Creates a path from a UUID (e.g. 6ebda899-217d-4bf1-abe4-2839085c8f3c becomes
218 * 6ebda899-217d/4bf1/abe4/2839085c8f3c/). '/' at the end, not the beginning
220 public static String
uuidAsPath(String uuid
) {
221 StringBuffer path
= new StringBuffer(uuid
.length());
222 String
[] tokens
= uuid
.split("-");
223 for (int i
= 0; i
< tokens
.length
; i
++) {
224 path
.append(tokens
[i
]);
228 return path
.toString();
232 * The provided data as a path ('/' at the end, not the beginning)
234 * @param cal the date
235 * @param addHour whether to add hour as well
237 public static String
dateAsPath(Calendar cal
, Boolean addHour
) {
238 StringBuffer buf
= new StringBuffer(14);
240 buf
.append(cal
.get(Calendar
.YEAR
));
243 int month
= cal
.get(Calendar
.MONTH
) + 1;
250 int day
= cal
.get(Calendar
.DAY_OF_MONTH
);
258 int hour
= cal
.get(Calendar
.HOUR_OF_DAY
);
265 return buf
.toString();
269 /** Converts in one call a string into a gregorian calendar. */
270 public static Calendar
parseCalendar(DateFormat dateFormat
, String value
) {
272 Date date
= dateFormat
.parse(value
);
273 Calendar calendar
= new GregorianCalendar();
274 calendar
.setTime(date
);
276 } catch (ParseException e
) {
277 throw new IllegalArgumentException("Cannot parse " + value
+ " with date format " + dateFormat
, e
);
282 /** The last element of a path. */
283 public static String
lastPathElement(String path
) {
284 if (path
.charAt(path
.length() - 1) == '/')
285 throw new IllegalArgumentException("Path " + path
+ " cannot end with '/'");
286 int index
= path
.lastIndexOf('/');
289 return path
.substring(index
+ 1);
293 * Call {@link Node#getName()} without exceptions (useful in super
296 public static String
getNameQuietly(Node node
) {
298 return node
.getName();
299 } catch (RepositoryException e
) {
300 throw new JcrException("Cannot get name from " + node
, e
);
305 * Call {@link Node#getProperty(String)} without exceptions (useful in super
308 public static String
getStringPropertyQuietly(Node node
, String propertyName
) {
310 return node
.getProperty(propertyName
).getString();
311 } catch (RepositoryException e
) {
312 throw new JcrException("Cannot get name from " + node
, e
);
317 // * Routine that get the child with this name, adding it if it does not already
320 // public static Node getOrAdd(Node parent, String name, String primaryNodeType) throws RepositoryException {
321 // return parent.hasNode(name) ? parent.getNode(name) : parent.addNode(name, primaryNodeType);
325 * Routine that get the child with this name, adding it if it does not already
328 public static Node
getOrAdd(Node parent
, String name
, String primaryNodeType
, String
... mixinNodeTypes
)
329 throws RepositoryException
{
331 if (parent
.hasNode(name
)) {
332 node
= parent
.getNode(name
);
333 if (primaryNodeType
!= null && !node
.isNodeType(primaryNodeType
))
334 throw new IllegalArgumentException("Node " + node
+ " exists but is of primary node type "
335 + node
.getPrimaryNodeType().getName() + ", not " + primaryNodeType
);
336 for (String mixin
: mixinNodeTypes
) {
337 if (!node
.isNodeType(mixin
))
338 node
.addMixin(mixin
);
342 node
= primaryNodeType
!= null ? parent
.addNode(name
, primaryNodeType
) : parent
.addNode(name
);
343 for (String mixin
: mixinNodeTypes
) {
344 node
.addMixin(mixin
);
351 * Routine that get the child with this name, adding it if it does not already
354 public static Node
getOrAdd(Node parent
, String name
) throws RepositoryException
{
355 return parent
.hasNode(name
) ? parent
.getNode(name
) : parent
.addNode(name
);
358 /** Convert a {@link NodeIterator} to a list of {@link Node} */
359 public static List
<Node
> nodeIteratorToList(NodeIterator nodeIterator
) {
360 List
<Node
> nodes
= new ArrayList
<Node
>();
361 while (nodeIterator
.hasNext()) {
362 nodes
.add(nodeIterator
.nextNode());
372 * Concisely get the string value of a property or null if this node doesn't
375 public static String
get(Node node
, String propertyName
) {
377 if (!node
.hasProperty(propertyName
))
379 return node
.getProperty(propertyName
).getString();
380 } catch (RepositoryException e
) {
381 throw new JcrException("Cannot get property " + propertyName
+ " of " + node
, e
);
385 /** Concisely get the path of the given node. */
386 public static String
getPath(Node node
) {
388 return node
.getPath();
389 } catch (RepositoryException e
) {
390 throw new JcrException("Cannot get path of " + node
, e
);
394 /** Concisely get the boolean value of a property */
395 public static Boolean
check(Node node
, String propertyName
) {
397 return node
.getProperty(propertyName
).getBoolean();
398 } catch (RepositoryException e
) {
399 throw new JcrException("Cannot get property " + propertyName
+ " of " + node
, e
);
403 /** Concisely get the bytes array value of a property */
404 public static byte[] getBytes(Node node
, String propertyName
) {
406 return getBinaryAsBytes(node
.getProperty(propertyName
));
407 } catch (RepositoryException e
) {
408 throw new JcrException("Cannot get property " + propertyName
+ " of " + node
, e
);
417 * Create sub nodes relative to a parent node
419 public static Node
mkdirs(Node parentNode
, String relativePath
) {
420 return mkdirs(parentNode
, relativePath
, null, null);
424 * Create sub nodes relative to a parent node
426 * @param nodeType the type of the leaf node
428 public static Node
mkdirs(Node parentNode
, String relativePath
, String nodeType
) {
429 return mkdirs(parentNode
, relativePath
, nodeType
, null);
433 * Create sub nodes relative to a parent node
435 * @param nodeType the type of the leaf node
437 public static Node
mkdirs(Node parentNode
, String relativePath
, String nodeType
, String intermediaryNodeType
) {
438 List
<String
> tokens
= tokenize(relativePath
);
439 Node currParent
= parentNode
;
441 for (int i
= 0; i
< tokens
.size(); i
++) {
442 String name
= tokens
.get(i
);
443 if (currParent
.hasNode(name
)) {
444 currParent
= currParent
.getNode(name
);
446 if (i
!= (tokens
.size() - 1)) {// intermediary
447 currParent
= currParent
.addNode(name
, intermediaryNodeType
);
449 currParent
= currParent
.addNode(name
, nodeType
);
454 } catch (RepositoryException e
) {
455 throw new JcrException("Cannot mkdirs relative path " + relativePath
+ " from " + parentNode
, e
);
460 * Synchronized and save is performed, to avoid race conditions in initializers
461 * leading to duplicate nodes.
463 public synchronized static Node
mkdirsSafe(Session session
, String path
, String type
) {
465 if (session
.hasPendingChanges())
466 throw new IllegalStateException("Session has pending changes, save them first.");
467 Node node
= mkdirs(session
, path
, type
);
470 } catch (RepositoryException e
) {
471 discardQuietly(session
);
472 throw new JcrException("Cannot safely make directories", e
);
476 public synchronized static Node
mkdirsSafe(Session session
, String path
) {
477 return mkdirsSafe(session
, path
, null);
480 /** Creates the nodes making path, if they don't exist. */
481 public static Node
mkdirs(Session session
, String path
) {
482 return mkdirs(session
, path
, null, null, false);
486 * @param type the type of the leaf node
488 public static Node
mkdirs(Session session
, String path
, String type
) {
489 return mkdirs(session
, path
, type
, null, false);
493 * Creates the nodes making path, if they don't exist. This is up to the caller
494 * to save the session. Use with caution since it can create duplicate nodes if
495 * used concurrently. Requires read access to the root node of the workspace.
497 public static Node
mkdirs(Session session
, String path
, String type
, String intermediaryNodeType
,
498 Boolean versioning
) {
500 if (path
.equals("/"))
501 return session
.getRootNode();
503 if (session
.itemExists(path
)) {
504 Node node
= session
.getNode(path
);
506 if (type
!= null && !node
.isNodeType(type
) && !node
.getPath().equals("/"))
507 throw new IllegalArgumentException("Node " + node
+ " exists but is of type "
508 + node
.getPrimaryNodeType().getName() + " not of type " + type
);
509 // TODO: check versioning
513 // StringBuffer current = new StringBuffer("/");
514 // Node currentNode = session.getRootNode();
516 Node currentNode
= findClosestExistingParent(session
, path
);
517 String closestExistingParentPath
= currentNode
.getPath();
518 StringBuffer current
= new StringBuffer(closestExistingParentPath
);
519 if (!closestExistingParentPath
.endsWith("/"))
521 Iterator
<String
> it
= tokenize(path
.substring(closestExistingParentPath
.length())).iterator();
522 while (it
.hasNext()) {
523 String part
= it
.next();
524 current
.append(part
).append('/');
525 if (!session
.itemExists(current
.toString())) {
526 if (!it
.hasNext() && type
!= null)
527 currentNode
= currentNode
.addNode(part
, type
);
528 else if (it
.hasNext() && intermediaryNodeType
!= null)
529 currentNode
= currentNode
.addNode(part
, intermediaryNodeType
);
531 currentNode
= currentNode
.addNode(part
);
533 currentNode
.addMixin(NodeType
.MIX_VERSIONABLE
);
534 // if (log.isTraceEnabled())
535 // log.debug("Added folder " + part + " as " + current);
537 currentNode
= (Node
) session
.getItem(current
.toString());
541 } catch (RepositoryException e
) {
542 discardQuietly(session
);
543 throw new JcrException("Cannot mkdirs " + path
, e
);
548 private static Node
findClosestExistingParent(Session session
, String path
) throws RepositoryException
{
549 int idx
= path
.lastIndexOf('/');
551 return session
.getRootNode();
552 String parentPath
= path
.substring(0, idx
);
553 if (session
.itemExists(parentPath
))
554 return session
.getNode(parentPath
);
556 return findClosestExistingParent(session
, parentPath
);
559 /** Convert a path to the list of its tokens */
560 public static List
<String
> tokenize(String path
) {
561 List
<String
> tokens
= new ArrayList
<String
>();
562 boolean optimized
= false;
564 String
[] rawTokens
= path
.split("/");
565 for (String token
: rawTokens
) {
566 if (!token
.equals(""))
570 StringBuffer curr
= new StringBuffer();
571 char[] arr
= path
.toCharArray();
572 chars
: for (int i
= 0; i
< arr
.length
; i
++) {
575 if (i
== 0 || (i
== arr
.length
- 1))
577 if (curr
.length() > 0) {
578 tokens
.add(curr
.toString());
579 curr
= new StringBuffer();
584 if (curr
.length() > 0) {
585 tokens
.add(curr
.toString());
586 curr
= new StringBuffer();
589 return Collections
.unmodifiableList(tokens
);
593 // * use {@link #mkdirs(Session, String, String, String, Boolean)} instead.
598 // public static Node mkdirs(Session session, String path, String type,
599 // Boolean versioning) {
600 // return mkdirs(session, path, type, type, false);
604 * Safe and repository implementation independent registration of a namespace.
606 public static void registerNamespaceSafely(Session session
, String prefix
, String uri
) {
608 registerNamespaceSafely(session
.getWorkspace().getNamespaceRegistry(), prefix
, uri
);
609 } catch (RepositoryException e
) {
610 throw new JcrException("Cannot find namespace registry", e
);
615 * Safe and repository implementation independent registration of a namespace.
617 public static void registerNamespaceSafely(NamespaceRegistry nr
, String prefix
, String uri
) {
619 String
[] prefixes
= nr
.getPrefixes();
620 for (String pref
: prefixes
)
621 if (pref
.equals(prefix
)) {
622 String registeredUri
= nr
.getURI(pref
);
623 if (!registeredUri
.equals(uri
))
624 throw new IllegalArgumentException("Prefix " + pref
+ " already registered for URI "
625 + registeredUri
+ " which is different from provided URI " + uri
);
629 nr
.registerNamespace(prefix
, uri
);
630 } catch (RepositoryException e
) {
631 throw new JcrException("Cannot register namespace " + uri
+ " under prefix " + prefix
, e
);
635 // /** Recursively outputs the contents of the given node. */
636 // public static void debug(Node node) {
640 // /** Recursively outputs the contents of the given node. */
641 // public static void debug(Node node, Log log) {
643 // // First output the node path
644 // log.debug(node.getPath());
645 // // Skip the virtual (and large!) jcr:system subtree
646 // if (node.getName().equals("jcr:system")) {
650 // // Then the children nodes (recursive)
651 // NodeIterator it = node.getNodes();
652 // while (it.hasNext()) {
653 // Node childNode = it.nextNode();
654 // debug(childNode, log);
657 // // Then output the properties
658 // PropertyIterator properties = node.getProperties();
659 // // log.debug("Property are : ");
661 // properties: while (properties.hasNext()) {
662 // Property property = properties.nextProperty();
663 // if (property.getType() == PropertyType.BINARY)
664 // continue properties;// skip
665 // if (property.getDefinition().isMultiple()) {
666 // // A multi-valued property, print all values
667 // Value[] values = property.getValues();
668 // for (int i = 0; i < values.length; i++) {
669 // log.debug(property.getPath() + "=" + values[i].getString());
672 // // A single-valued property
673 // log.debug(property.getPath() + "=" + property.getString());
676 // } catch (Exception e) {
677 // log.error("Could not debug " + node, e);
682 // /** Logs the effective access control policies */
683 // public static void logEffectiveAccessPolicies(Node node) {
685 // logEffectiveAccessPolicies(node.getSession(), node.getPath());
686 // } catch (RepositoryException e) {
687 // log.error("Cannot log effective access policies of " + node, e);
691 // /** Logs the effective access control policies */
692 // public static void logEffectiveAccessPolicies(Session session, String path) {
693 // if (!log.isDebugEnabled())
697 // AccessControlPolicy[] effectivePolicies = session.getAccessControlManager().getEffectivePolicies(path);
698 // if (effectivePolicies.length > 0) {
699 // for (AccessControlPolicy policy : effectivePolicies) {
700 // if (policy instanceof AccessControlList) {
701 // AccessControlList acl = (AccessControlList) policy;
702 // log.debug("Access control list for " + path + "\n" + accessControlListSummary(acl));
706 // log.debug("No effective access control policy for " + path);
708 // } catch (RepositoryException e) {
709 // log.error("Cannot log effective access policies of " + path, e);
713 /** Returns a human-readable summary of this access control list. */
714 public static String
accessControlListSummary(AccessControlList acl
) {
715 StringBuffer buf
= new StringBuffer("");
717 for (AccessControlEntry ace
: acl
.getAccessControlEntries()) {
718 buf
.append('\t').append(ace
.getPrincipal().getName()).append('\n');
719 for (Privilege priv
: ace
.getPrivileges())
720 buf
.append("\t\t").append(priv
.getName()).append('\n');
722 return buf
.toString();
723 } catch (RepositoryException e
) {
724 throw new JcrException("Cannot write summary of " + acl
, e
);
728 /** Copy the whole workspace via a system view XML. */
729 public static void copyWorkspaceXml(Session fromSession
, Session toSession
) {
730 Workspace fromWorkspace
= fromSession
.getWorkspace();
731 Workspace toWorkspace
= toSession
.getWorkspace();
732 String errorMsg
= "Cannot copy workspace " + fromWorkspace
+ " to " + toWorkspace
+ " via XML.";
734 try (PipedInputStream in
= new PipedInputStream(1024 * 1024);) {
736 try (PipedOutputStream out
= new PipedOutputStream(in
)) {
737 fromSession
.exportSystemView("/", out
, false, false);
739 } catch (IOException e
) {
740 throw new RuntimeException(errorMsg
, e
);
741 } catch (RepositoryException e
) {
742 throw new JcrException(errorMsg
, e
);
744 }, "Copy workspace" + fromWorkspace
+ " to " + toWorkspace
).start();
746 toSession
.importXML("/", in
, ImportUUIDBehavior
.IMPORT_UUID_COLLISION_REPLACE_EXISTING
);
748 } catch (IOException e
) {
749 throw new RuntimeException(errorMsg
, e
);
750 } catch (RepositoryException e
) {
751 throw new JcrException(errorMsg
, e
);
756 * Copies recursively the content of a node to another one. Do NOT copy the
757 * property values of {@link NodeType#MIX_CREATED} and
758 * {@link NodeType#MIX_LAST_MODIFIED}, but update the
759 * {@link Property#JCR_LAST_MODIFIED} and {@link Property#JCR_LAST_MODIFIED_BY}
760 * properties if the target node has the {@link NodeType#MIX_LAST_MODIFIED}
763 public static void copy(Node fromNode
, Node toNode
) {
765 if (toNode
.getDefinition().isProtected())
769 for (NodeType mixinType
: fromNode
.getMixinNodeTypes()) {
771 toNode
.addMixin(mixinType
.getName());
772 } catch (NoSuchNodeTypeException e
) {
773 // ignore unknown mixins
778 // process properties
779 PropertyIterator pit
= fromNode
.getProperties();
780 properties
: while (pit
.hasNext()) {
781 Property fromProperty
= pit
.nextProperty();
782 String propertyName
= fromProperty
.getName();
783 if (toNode
.hasProperty(propertyName
) && toNode
.getProperty(propertyName
).getDefinition().isProtected())
786 if (fromProperty
.getDefinition().isProtected())
789 if (propertyName
.equals("jcr:created") || propertyName
.equals("jcr:createdBy")
790 || propertyName
.equals("jcr:lastModified") || propertyName
.equals("jcr:lastModifiedBy"))
793 if (fromProperty
.isMultiple()) {
794 toNode
.setProperty(propertyName
, fromProperty
.getValues());
796 toNode
.setProperty(propertyName
, fromProperty
.getValue());
800 // update jcr:lastModified and jcr:lastModifiedBy in toNode in case
801 // they existed, before adding the mixins
802 updateLastModified(toNode
, true);
804 // process children nodes
805 NodeIterator nit
= fromNode
.getNodes();
806 while (nit
.hasNext()) {
807 Node fromChild
= nit
.nextNode();
808 Integer index
= fromChild
.getIndex();
809 String nodeRelPath
= fromChild
.getName() + "[" + index
+ "]";
811 if (toNode
.hasNode(nodeRelPath
))
812 toChild
= toNode
.getNode(nodeRelPath
);
815 toChild
= toNode
.addNode(fromChild
.getName(), fromChild
.getPrimaryNodeType().getName());
816 } catch (NoSuchNodeTypeException e
) {
817 // ignore unknown primary types
822 copy(fromChild
, toChild
);
824 } catch (RepositoryException e
) {
825 throw new JcrException("Cannot copy " + fromNode
+ " to " + toNode
, e
);
830 * Check whether all first-level properties (except jcr:* properties) are equal.
831 * Skip jcr:* properties
833 public static Boolean
allPropertiesEquals(Node reference
, Node observed
, Boolean onlyCommonProperties
) {
835 PropertyIterator pit
= reference
.getProperties();
836 props
: while (pit
.hasNext()) {
837 Property propReference
= pit
.nextProperty();
838 String propName
= propReference
.getName();
839 if (propName
.startsWith("jcr:"))
842 if (!observed
.hasProperty(propName
))
843 if (onlyCommonProperties
)
847 // TODO: deal with multiple property values?
848 if (!observed
.getProperty(propName
).getValue().equals(propReference
.getValue()))
852 } catch (RepositoryException e
) {
853 throw new JcrException("Cannot check all properties equals of " + reference
+ " and " + observed
, e
);
857 public static Map
<String
, PropertyDiff
> diffProperties(Node reference
, Node observed
) {
858 Map
<String
, PropertyDiff
> diffs
= new TreeMap
<String
, PropertyDiff
>();
859 diffPropertiesLevel(diffs
, null, reference
, observed
);
864 * Compare the properties of two nodes. Recursivity to child nodes is not yet
865 * supported. Skip jcr:* properties.
867 static void diffPropertiesLevel(Map
<String
, PropertyDiff
> diffs
, String baseRelPath
, Node reference
,
870 // check removed and modified
871 PropertyIterator pit
= reference
.getProperties();
872 props
: while (pit
.hasNext()) {
873 Property p
= pit
.nextProperty();
874 String name
= p
.getName();
875 if (name
.startsWith("jcr:"))
878 if (!observed
.hasProperty(name
)) {
879 String relPath
= propertyRelPath(baseRelPath
, name
);
880 PropertyDiff pDiff
= new PropertyDiff(PropertyDiff
.REMOVED
, relPath
, p
.getValue(), null);
881 diffs
.put(relPath
, pDiff
);
883 if (p
.isMultiple()) {
884 // FIXME implement multiple
886 Value referenceValue
= p
.getValue();
887 Value newValue
= observed
.getProperty(name
).getValue();
888 if (!referenceValue
.equals(newValue
)) {
889 String relPath
= propertyRelPath(baseRelPath
, name
);
890 PropertyDiff pDiff
= new PropertyDiff(PropertyDiff
.MODIFIED
, relPath
, referenceValue
,
892 diffs
.put(relPath
, pDiff
);
898 pit
= observed
.getProperties();
899 props
: while (pit
.hasNext()) {
900 Property p
= pit
.nextProperty();
901 String name
= p
.getName();
902 if (name
.startsWith("jcr:"))
904 if (!reference
.hasProperty(name
)) {
905 if (p
.isMultiple()) {
906 // FIXME implement multiple
908 String relPath
= propertyRelPath(baseRelPath
, name
);
909 PropertyDiff pDiff
= new PropertyDiff(PropertyDiff
.ADDED
, relPath
, null, p
.getValue());
910 diffs
.put(relPath
, pDiff
);
914 } catch (RepositoryException e
) {
915 throw new JcrException("Cannot diff " + reference
+ " and " + observed
, e
);
920 * Compare only a restricted list of properties of two nodes. No recursivity.
923 public static Map
<String
, PropertyDiff
> diffProperties(Node reference
, Node observed
, List
<String
> properties
) {
924 Map
<String
, PropertyDiff
> diffs
= new TreeMap
<String
, PropertyDiff
>();
926 Iterator
<String
> pit
= properties
.iterator();
928 props
: while (pit
.hasNext()) {
929 String name
= pit
.next();
930 if (!reference
.hasProperty(name
)) {
931 if (!observed
.hasProperty(name
))
933 Value val
= observed
.getProperty(name
).getValue();
935 // empty String but not null
936 if ("".equals(val
.getString()))
938 } catch (Exception e
) {
939 // not parseable as String, silent
941 PropertyDiff pDiff
= new PropertyDiff(PropertyDiff
.ADDED
, name
, null, val
);
942 diffs
.put(name
, pDiff
);
943 } else if (!observed
.hasProperty(name
)) {
944 PropertyDiff pDiff
= new PropertyDiff(PropertyDiff
.REMOVED
, name
,
945 reference
.getProperty(name
).getValue(), null);
946 diffs
.put(name
, pDiff
);
948 Value referenceValue
= reference
.getProperty(name
).getValue();
949 Value newValue
= observed
.getProperty(name
).getValue();
950 if (!referenceValue
.equals(newValue
)) {
951 PropertyDiff pDiff
= new PropertyDiff(PropertyDiff
.MODIFIED
, name
, referenceValue
, newValue
);
952 diffs
.put(name
, pDiff
);
956 } catch (RepositoryException e
) {
957 throw new JcrException("Cannot diff " + reference
+ " and " + observed
, e
);
962 /** Builds a property relPath to be used in the diff. */
963 private static String
propertyRelPath(String baseRelPath
, String propertyName
) {
964 if (baseRelPath
== null)
967 return baseRelPath
+ '/' + propertyName
;
971 * Normalizes a name so that it can be stored in contexts not supporting names
972 * with ':' (typically databases). Replaces ':' by '_'.
974 public static String
normalize(String name
) {
975 return name
.replace(':', '_');
979 * Replaces characters which are invalid in a JCR name by '_'. Currently not
982 * @see JcrUtils#INVALID_NAME_CHARACTERS
984 public static String
replaceInvalidChars(String name
) {
985 return replaceInvalidChars(name
, '_');
989 * Replaces characters which are invalid in a JCR name. Currently not
992 * @see JcrUtils#INVALID_NAME_CHARACTERS
994 public static String
replaceInvalidChars(String name
, char replacement
) {
995 boolean modified
= false;
996 char[] arr
= name
.toCharArray();
997 for (int i
= 0; i
< arr
.length
; i
++) {
999 invalid
: for (char invalid
: INVALID_NAME_CHARACTERS
) {
1001 arr
[i
] = replacement
;
1008 return new String(arr
);
1010 // do not create new object if unnecessary
1015 // * Removes forbidden characters from a path, replacing them with '_'
1017 // * @deprecated use {@link #replaceInvalidChars(String)} instead
1019 // public static String removeForbiddenCharacters(String str) {
1020 // return str.replace('[', '_').replace(']', '_').replace('/', '_').replace('*',
1025 /** Cleanly disposes a {@link Binary} even if it is null. */
1026 public static void closeQuietly(Binary binary
) {
1032 /** Retrieve a {@link Binary} as a byte array */
1033 public static byte[] getBinaryAsBytes(Property property
) {
1034 try (ByteArrayOutputStream out
= new ByteArrayOutputStream();
1035 Bin binary
= new Bin(property
);
1036 InputStream in
= binary
.getStream()) {
1037 IOUtils
.copy(in
, out
);
1038 return out
.toByteArray();
1039 } catch (RepositoryException e
) {
1040 throw new JcrException("Cannot read binary " + property
+ " as bytes", e
);
1041 } catch (IOException e
) {
1042 throw new RuntimeException("Cannot read binary " + property
+ " as bytes", e
);
1046 /** Writes a {@link Binary} from a byte array */
1047 public static void setBinaryAsBytes(Node node
, String property
, byte[] bytes
) {
1048 Binary binary
= null;
1049 try (InputStream in
= new ByteArrayInputStream(bytes
)) {
1050 binary
= node
.getSession().getValueFactory().createBinary(in
);
1051 node
.setProperty(property
, binary
);
1052 } catch (RepositoryException e
) {
1053 throw new JcrException("Cannot set binary " + property
+ " as bytes", e
);
1054 } catch (IOException e
) {
1055 throw new RuntimeException("Cannot set binary " + property
+ " as bytes", e
);
1057 closeQuietly(binary
);
1061 /** Writes a {@link Binary} from a byte array */
1062 public static void setBinaryAsBytes(Property prop
, byte[] bytes
) {
1063 Binary binary
= null;
1064 try (InputStream in
= new ByteArrayInputStream(bytes
)) {
1065 binary
= prop
.getSession().getValueFactory().createBinary(in
);
1066 prop
.setValue(binary
);
1067 } catch (RepositoryException e
) {
1068 throw new JcrException("Cannot set binary " + prop
+ " as bytes", e
);
1069 } catch (IOException e
) {
1070 throw new RuntimeException("Cannot set binary " + prop
+ " as bytes", e
);
1072 closeQuietly(binary
);
1077 * Creates depth from a string (typically a username) by adding levels based on
1078 * its first characters: "aBcD",2 becomes a/aB
1080 public static String
firstCharsToPath(String str
, Integer nbrOfChars
) {
1081 if (str
.length() < nbrOfChars
)
1082 throw new IllegalArgumentException("String " + str
+ " length must be greater or equal than " + nbrOfChars
);
1083 StringBuffer path
= new StringBuffer("");
1084 StringBuffer curr
= new StringBuffer("");
1085 for (int i
= 0; i
< nbrOfChars
; i
++) {
1086 curr
.append(str
.charAt(i
));
1088 if (i
< nbrOfChars
- 1)
1091 return path
.toString();
1095 * Discards the current changes in the session attached to this node. To be used
1096 * typically in a catch block.
1098 * @see #discardQuietly(Session)
1100 public static void discardUnderlyingSessionQuietly(Node node
) {
1102 discardQuietly(node
.getSession());
1103 } catch (RepositoryException e
) {
1109 * Discards the current changes in a session by calling
1110 * {@link Session#refresh(boolean)} with <code>false</code>, only logging
1111 * potential errors when doing so. To be used typically in a catch block.
1113 public static void discardQuietly(Session session
) {
1115 if (session
!= null)
1116 session
.refresh(false);
1117 } catch (RepositoryException e
) {
1123 * Login to a workspace with implicit credentials, creates the workspace with
1124 * these credentials if it does not already exist.
1126 public static Session
loginOrCreateWorkspace(Repository repository
, String workspaceName
)
1127 throws RepositoryException
{
1128 return loginOrCreateWorkspace(repository
, workspaceName
, null);
1132 * Login to a workspace with implicit credentials, creates the workspace with
1133 * these credentials if it does not already exist.
1135 public static Session
loginOrCreateWorkspace(Repository repository
, String workspaceName
, Credentials credentials
)
1136 throws RepositoryException
{
1137 Session workspaceSession
= null;
1138 Session defaultSession
= null;
1141 workspaceSession
= repository
.login(credentials
, workspaceName
);
1142 } catch (NoSuchWorkspaceException e
) {
1143 // try to create workspace
1144 defaultSession
= repository
.login(credentials
);
1145 defaultSession
.getWorkspace().createWorkspace(workspaceName
);
1146 workspaceSession
= repository
.login(credentials
, workspaceName
);
1148 return workspaceSession
;
1150 logoutQuietly(defaultSession
);
1155 * Logs out the session, not throwing any exception, even if it is null.
1156 * {@link Jcr#logout(Session)} should rather be used.
1158 public static void logoutQuietly(Session session
) {
1159 Jcr
.logout(session
);
1161 // if (session != null)
1162 // if (session.isLive())
1163 // session.logout();
1164 // } catch (Exception e) {
1170 * Convenient method to add a listener. uuids passed as null, deep=true,
1171 * local=true, only one node type
1173 public static void addListener(Session session
, EventListener listener
, int eventTypes
, String basePath
,
1176 session
.getWorkspace().getObservationManager().addEventListener(listener
, eventTypes
, basePath
, true, null,
1177 nodeType
== null ?
null : new String
[] { nodeType
}, true);
1178 } catch (RepositoryException e
) {
1179 throw new JcrException("Cannot add JCR listener " + listener
+ " to session " + session
, e
);
1183 /** Removes a listener without throwing exception */
1184 public static void removeListenerQuietly(Session session
, EventListener listener
) {
1185 if (session
== null || !session
.isLive())
1188 session
.getWorkspace().getObservationManager().removeEventListener(listener
);
1189 } catch (RepositoryException e
) {
1195 * Quietly unregisters an {@link EventListener} from the udnerlying workspace of
1198 public static void unregisterQuietly(Node node
, EventListener eventListener
) {
1200 unregisterQuietly(node
.getSession().getWorkspace(), eventListener
);
1201 } catch (RepositoryException e
) {
1206 /** Quietly unregisters an {@link EventListener} from this workspace */
1207 public static void unregisterQuietly(Workspace workspace
, EventListener eventListener
) {
1208 if (eventListener
== null)
1211 workspace
.getObservationManager().removeEventListener(eventListener
);
1212 } catch (RepositoryException e
) {
1218 * Checks whether {@link Property#JCR_LAST_MODIFIED} or (afterwards)
1219 * {@link Property#JCR_CREATED} are set and returns it as an {@link Instant}.
1221 public static Instant
getModified(Node node
) {
1222 Calendar calendar
= null;
1224 if (node
.hasProperty(Property
.JCR_LAST_MODIFIED
))
1225 calendar
= node
.getProperty(Property
.JCR_LAST_MODIFIED
).getDate();
1226 else if (node
.hasProperty(Property
.JCR_CREATED
))
1227 calendar
= node
.getProperty(Property
.JCR_CREATED
).getDate();
1229 throw new IllegalArgumentException("No modification time found in " + node
);
1230 return calendar
.toInstant();
1231 } catch (RepositoryException e
) {
1232 throw new JcrException("Cannot get modification time for " + node
, e
);
1238 * Get {@link Property#JCR_CREATED} as an {@link Instant}, if it is set.
1240 public static Instant
getCreated(Node node
) {
1241 Calendar calendar
= null;
1243 if (node
.hasProperty(Property
.JCR_CREATED
))
1244 calendar
= node
.getProperty(Property
.JCR_CREATED
).getDate();
1246 throw new IllegalArgumentException("No created time found in " + node
);
1247 return calendar
.toInstant();
1248 } catch (RepositoryException e
) {
1249 throw new JcrException("Cannot get created time for " + node
, e
);
1255 * Updates the {@link Property#JCR_LAST_MODIFIED} property with the current time
1256 * and the {@link Property#JCR_LAST_MODIFIED_BY} property with the underlying
1259 public static void updateLastModified(Node node
) {
1260 updateLastModified(node
, false);
1264 * Updates the {@link Property#JCR_LAST_MODIFIED} property with the current time
1265 * and the {@link Property#JCR_LAST_MODIFIED_BY} property with the underlying
1266 * session user id. In Jackrabbit 2.x,
1267 * <a href="https://issues.apache.org/jira/browse/JCR-2233">these properties are
1268 * not automatically updated</a>, hence the need for manual update. The session
1271 public static void updateLastModified(Node node
, boolean addMixin
) {
1273 if (addMixin
&& !node
.isNodeType(NodeType
.MIX_LAST_MODIFIED
))
1274 node
.addMixin(NodeType
.MIX_LAST_MODIFIED
);
1275 node
.setProperty(Property
.JCR_LAST_MODIFIED
, new GregorianCalendar());
1276 node
.setProperty(Property
.JCR_LAST_MODIFIED_BY
, node
.getSession().getUserID());
1277 } catch (RepositoryException e
) {
1278 throw new JcrException("Cannot update last modified on " + node
, e
);
1283 * Update lastModified recursively until this parent.
1285 * @param node the node
1286 * @param untilPath the base path, null is equivalent to "/"
1288 public static void updateLastModifiedAndParents(Node node
, String untilPath
) {
1289 updateLastModifiedAndParents(node
, untilPath
, true);
1293 * Update lastModified recursively until this parent.
1295 * @param node the node
1296 * @param untilPath the base path, null is equivalent to "/"
1298 public static void updateLastModifiedAndParents(Node node
, String untilPath
, boolean addMixin
) {
1300 if (untilPath
!= null && !node
.getPath().startsWith(untilPath
))
1301 throw new IllegalArgumentException(node
+ " is not under " + untilPath
);
1302 updateLastModified(node
, addMixin
);
1303 if (untilPath
== null) {
1304 if (!node
.getPath().equals("/"))
1305 updateLastModifiedAndParents(node
.getParent(), untilPath
, addMixin
);
1307 if (!node
.getPath().equals(untilPath
))
1308 updateLastModifiedAndParents(node
.getParent(), untilPath
, addMixin
);
1310 } catch (RepositoryException e
) {
1311 throw new JcrException("Cannot update lastModified from " + node
+ " until " + untilPath
, e
);
1316 * Returns a String representing the short version (see
1317 * <a href="http://jackrabbit.apache.org/node-type-notation.html"> Node type
1318 * Notation </a> attributes grammar) of the main business attributes of this
1319 * property definition
1323 public static String
getPropertyDefinitionAsString(Property prop
) {
1324 StringBuffer sbuf
= new StringBuffer();
1326 if (prop
.getDefinition().isAutoCreated())
1328 if (prop
.getDefinition().isMandatory())
1330 if (prop
.getDefinition().isProtected())
1332 if (prop
.getDefinition().isMultiple())
1334 } catch (RepositoryException re
) {
1335 throw new JcrException("unexpected error while getting property definition as String", re
);
1337 return sbuf
.toString();
1341 * Estimate the sub tree size from current node. Computation is based on the Jcr
1342 * {@link Property#getLength()} method. Note : it is not the exact size used on
1343 * the disk by the current part of the JCR Tree.
1346 public static long getNodeApproxSize(Node node
) {
1347 long curNodeSize
= 0;
1349 PropertyIterator pi
= node
.getProperties();
1350 while (pi
.hasNext()) {
1351 Property prop
= pi
.nextProperty();
1352 if (prop
.isMultiple()) {
1353 int nb
= prop
.getLengths().length
;
1354 for (int i
= 0; i
< nb
; i
++) {
1355 curNodeSize
+= (prop
.getLengths()[i
] > 0 ? prop
.getLengths()[i
] : 0);
1358 curNodeSize
+= (prop
.getLength() > 0 ? prop
.getLength() : 0);
1361 NodeIterator ni
= node
.getNodes();
1362 while (ni
.hasNext())
1363 curNodeSize
+= getNodeApproxSize(ni
.nextNode());
1365 } catch (RepositoryException re
) {
1366 throw new JcrException("Unexpected error while recursively determining node size.", re
);
1375 * Convenience method for adding a single privilege to a principal (user or
1376 * role), typically jcr:all
1378 public synchronized static void addPrivilege(Session session
, String path
, String principal
, String privilege
)
1379 throws RepositoryException
{
1380 List
<Privilege
> privileges
= new ArrayList
<Privilege
>();
1381 privileges
.add(session
.getAccessControlManager().privilegeFromName(privilege
));
1382 addPrivileges(session
, path
, new SimplePrincipal(principal
), privileges
);
1386 * Add privileges on a path to a {@link Principal}. The path must already exist.
1387 * Session is saved. Synchronized to prevent concurrent modifications of the
1390 public synchronized static Boolean
addPrivileges(Session session
, String path
, Principal principal
,
1391 List
<Privilege
> privs
) throws RepositoryException
{
1392 // make sure the session is in line with the persisted state
1393 session
.refresh(false);
1394 AccessControlManager acm
= session
.getAccessControlManager();
1395 AccessControlList acl
= getAccessControlList(acm
, path
);
1397 accessControlEntries
: for (AccessControlEntry ace
: acl
.getAccessControlEntries()) {
1398 Principal currentPrincipal
= ace
.getPrincipal();
1399 if (currentPrincipal
.getName().equals(principal
.getName())) {
1400 Privilege
[] currentPrivileges
= ace
.getPrivileges();
1401 if (currentPrivileges
.length
!= privs
.size())
1402 break accessControlEntries
;
1403 for (int i
= 0; i
< currentPrivileges
.length
; i
++) {
1404 Privilege currP
= currentPrivileges
[i
];
1405 Privilege p
= privs
.get(i
);
1406 if (!currP
.getName().equals(p
.getName())) {
1407 break accessControlEntries
;
1414 Privilege
[] privileges
= privs
.toArray(new Privilege
[privs
.size()]);
1415 acl
.addAccessControlEntry(principal
, privileges
);
1416 acm
.setPolicy(path
, acl
);
1417 // if (log.isDebugEnabled()) {
1418 // StringBuffer privBuf = new StringBuffer();
1419 // for (Privilege priv : privs)
1420 // privBuf.append(priv.getName());
1421 // log.debug("Added privileges " + privBuf + " to " + principal.getName() + " on " + path + " in '"
1422 // + session.getWorkspace().getName() + "'");
1424 session
.refresh(true);
1430 * Gets the first available access control list for this path, throws exception
1433 public synchronized static AccessControlList
getAccessControlList(AccessControlManager acm
, String path
)
1434 throws RepositoryException
{
1435 // search for an access control list
1436 AccessControlList acl
= null;
1437 AccessControlPolicyIterator policyIterator
= acm
.getApplicablePolicies(path
);
1438 applicablePolicies
: if (policyIterator
.hasNext()) {
1439 while (policyIterator
.hasNext()) {
1440 AccessControlPolicy acp
= policyIterator
.nextAccessControlPolicy();
1441 if (acp
instanceof AccessControlList
) {
1442 acl
= ((AccessControlList
) acp
);
1443 break applicablePolicies
;
1447 AccessControlPolicy
[] existingPolicies
= acm
.getPolicies(path
);
1448 existingPolicies
: for (AccessControlPolicy acp
: existingPolicies
) {
1449 if (acp
instanceof AccessControlList
) {
1450 acl
= ((AccessControlList
) acp
);
1451 break existingPolicies
;
1458 throw new IllegalArgumentException("ACL not found at " + path
);
1461 /** Clear authorizations for a user at this path */
1462 public synchronized static void clearAccessControList(Session session
, String path
, String username
)
1463 throws RepositoryException
{
1464 AccessControlManager acm
= session
.getAccessControlManager();
1465 AccessControlList acl
= getAccessControlList(acm
, path
);
1466 for (AccessControlEntry ace
: acl
.getAccessControlEntries()) {
1467 if (ace
.getPrincipal().getName().equals(username
)) {
1468 acl
.removeAccessControlEntry(ace
);
1471 // the new access control list must be applied otherwise this call:
1472 // acl.removeAccessControlEntry(ace); has no effect
1473 acm
.setPolicy(path
, acl
);
1474 session
.refresh(true);
1482 * Creates the nodes making the path as {@link NodeType#NT_FOLDER}
1484 public static Node
mkfolders(Session session
, String path
) {
1485 return mkdirs(session
, path
, NodeType
.NT_FOLDER
, NodeType
.NT_FOLDER
, false);
1489 * Copy only nt:folder and nt:file, without their additional types and
1492 * @param recursive if true copies folders as well, otherwise only first level
1494 * @return how many files were copied
1496 public static Long
copyFiles(Node fromNode
, Node toNode
, Boolean recursive
, JcrMonitor monitor
, boolean onlyAdd
) {
1499 // Binary binary = null;
1500 // InputStream in = null;
1502 NodeIterator fromChildren
= fromNode
.getNodes();
1503 children
: while (fromChildren
.hasNext()) {
1504 if (monitor
!= null && monitor
.isCanceled())
1505 throw new IllegalStateException("Copy cancelled before it was completed");
1507 Node fromChild
= fromChildren
.nextNode();
1508 String fileName
= fromChild
.getName();
1509 if (fromChild
.isNodeType(NodeType
.NT_FILE
)) {
1510 if (onlyAdd
&& toNode
.hasNode(fileName
)) {
1511 monitor
.subTask("Skip existing " + fileName
);
1515 if (monitor
!= null)
1516 monitor
.subTask("Copy " + fileName
);
1517 try (Bin binary
= new Bin(fromChild
.getNode(Node
.JCR_CONTENT
).getProperty(Property
.JCR_DATA
));
1518 InputStream in
= binary
.getStream();) {
1519 copyStreamAsFile(toNode
, fileName
, in
);
1520 } catch (IOException e
) {
1521 throw new RuntimeException("Cannot copy " + fileName
+ " to " + toNode
, e
);
1525 toNode
.getSession().save();
1528 // if (log.isDebugEnabled())
1529 // log.debug("Copied file " + fromChild.getPath());
1530 if (monitor
!= null)
1532 } else if (fromChild
.isNodeType(NodeType
.NT_FOLDER
) && recursive
) {
1534 if (toNode
.hasNode(fileName
)) {
1535 toChildFolder
= toNode
.getNode(fileName
);
1536 if (!toChildFolder
.isNodeType(NodeType
.NT_FOLDER
))
1537 throw new IllegalArgumentException(toChildFolder
+ " is not of type nt:folder");
1539 toChildFolder
= toNode
.addNode(fileName
, NodeType
.NT_FOLDER
);
1542 toNode
.getSession().save();
1544 count
= count
+ copyFiles(fromChild
, toChildFolder
, recursive
, monitor
, onlyAdd
);
1548 } catch (RepositoryException e
) {
1549 throw new JcrException("Cannot copy files between " + fromNode
+ " and " + toNode
, e
);
1551 // in case there was an exception
1552 // IOUtils.closeQuietly(in);
1553 // closeQuietly(binary);
1558 * Iteratively count all file nodes in subtree, inefficient but can be useful
1559 * when query are poorly supported, such as in remoting.
1561 public static Long
countFiles(Node node
) {
1562 Long localCount
= 0l;
1564 for (NodeIterator nit
= node
.getNodes(); nit
.hasNext();) {
1565 Node child
= nit
.nextNode();
1566 if (child
.isNodeType(NodeType
.NT_FOLDER
))
1567 localCount
= localCount
+ countFiles(child
);
1568 else if (child
.isNodeType(NodeType
.NT_FILE
))
1569 localCount
= localCount
+ 1;
1571 } catch (RepositoryException e
) {
1572 throw new JcrException("Cannot count all children of " + node
, e
);
1578 * Copy a file as an nt:file, assuming an nt:folder hierarchy. The session is
1581 * @return the created file node
1584 public static Node
copyFile(Node folderNode
, File file
) {
1585 try (InputStream in
= new FileInputStream(file
)) {
1586 return copyStreamAsFile(folderNode
, file
.getName(), in
);
1587 } catch (IOException e
) {
1588 throw new RuntimeException("Cannot copy file " + file
+ " under " + folderNode
, e
);
1592 /** Copy bytes as an nt:file */
1593 public static Node
copyBytesAsFile(Node folderNode
, String fileName
, byte[] bytes
) {
1594 // InputStream in = null;
1595 try (InputStream in
= new ByteArrayInputStream(bytes
)) {
1596 // in = new ByteArrayInputStream(bytes);
1597 return copyStreamAsFile(folderNode
, fileName
, in
);
1598 } catch (IOException e
) {
1599 throw new RuntimeException("Cannot copy file " + fileName
+ " under " + folderNode
, e
);
1601 // IOUtils.closeQuietly(in);
1606 * Copy a stream as an nt:file, assuming an nt:folder hierarchy. The session is
1609 * @return the created file node
1611 public static Node
copyStreamAsFile(Node folderNode
, String fileName
, InputStream in
) {
1612 Binary binary
= null;
1616 if (folderNode
.hasNode(fileName
)) {
1617 fileNode
= folderNode
.getNode(fileName
);
1618 if (!fileNode
.isNodeType(NodeType
.NT_FILE
))
1619 throw new IllegalArgumentException(fileNode
+ " is not of type nt:file");
1620 // we assume that the content node is already there
1621 contentNode
= fileNode
.getNode(Node
.JCR_CONTENT
);
1623 fileNode
= folderNode
.addNode(fileName
, NodeType
.NT_FILE
);
1624 contentNode
= fileNode
.addNode(Node
.JCR_CONTENT
, NodeType
.NT_UNSTRUCTURED
);
1626 binary
= contentNode
.getSession().getValueFactory().createBinary(in
);
1627 contentNode
.setProperty(Property
.JCR_DATA
, binary
);
1628 updateLastModified(contentNode
);
1630 } catch (RepositoryException e
) {
1631 throw new JcrException("Cannot create file node " + fileName
+ " under " + folderNode
, e
);
1633 closeQuietly(binary
);
1637 /** Read an an nt:file as an {@link InputStream}. */
1638 public static InputStream
getFileAsStream(Node fileNode
) throws RepositoryException
{
1639 return fileNode
.getNode(Node
.JCR_CONTENT
).getProperty(Property
.JCR_DATA
).getBinary().getStream();
1643 * Set the properties of {@link NodeType#MIX_MIMETYPE} on the content of this
1646 public static void setFileMimeType(Node fileNode
, String mimeType
, String encoding
) throws RepositoryException
{
1647 Node contentNode
= fileNode
.getNode(Node
.JCR_CONTENT
);
1648 if (mimeType
!= null)
1649 contentNode
.setProperty(Property
.JCR_MIMETYPE
, mimeType
);
1650 if (encoding
!= null)
1651 contentNode
.setProperty(Property
.JCR_ENCODING
, encoding
);
1652 // TODO remove properties if args are null?
1655 public static void copyFilesToFs(Node baseNode
, Path targetDir
, boolean recursive
) {
1657 Files
.createDirectories(targetDir
);
1658 for (NodeIterator nit
= baseNode
.getNodes(); nit
.hasNext();) {
1659 Node node
= nit
.nextNode();
1660 if (node
.isNodeType(NodeType
.NT_FILE
)) {
1661 Path filePath
= targetDir
.resolve(node
.getName());
1662 try (OutputStream out
= Files
.newOutputStream(filePath
); InputStream in
= getFileAsStream(node
)) {
1663 IOUtils
.copy(in
, out
);
1665 } else if (recursive
&& node
.isNodeType(NodeType
.NT_FOLDER
)) {
1666 Path dirPath
= targetDir
.resolve(node
.getName());
1667 copyFilesToFs(node
, dirPath
, true);
1670 } catch (RepositoryException e
) {
1671 throw new JcrException("Cannot copy " + baseNode
+ " to " + targetDir
, e
);
1672 } catch (IOException e
) {
1673 throw new RuntimeException("Cannot copy " + baseNode
+ " to " + targetDir
, e
);
1678 * Computes the checksum of an nt:file.
1680 * @deprecated use separate digest utilities
1683 public static String
checksumFile(Node fileNode
, String algorithm
) {
1684 try (InputStream in
= fileNode
.getNode(Node
.JCR_CONTENT
).getProperty(Property
.JCR_DATA
).getBinary()
1686 return digest(algorithm
, in
);
1687 } catch (IOException e
) {
1688 throw new RuntimeException("Cannot checksum file " + fileNode
+ " with algorithm " + algorithm
, e
);
1689 } catch (RepositoryException e
) {
1690 throw new JcrException("Cannot checksum file " + fileNode
+ " with algorithm " + algorithm
, e
);
1695 private static String
digest(String algorithm
, InputStream in
) {
1696 final Integer byteBufferCapacity
= 100 * 1024;// 100 KB
1698 MessageDigest digest
= MessageDigest
.getInstance(algorithm
);
1699 byte[] buffer
= new byte[byteBufferCapacity
];
1701 while ((read
= in
.read(buffer
)) > 0) {
1702 digest
.update(buffer
, 0, read
);
1705 byte[] checksum
= digest
.digest();
1706 String res
= encodeHexString(checksum
);
1708 } catch (IOException e
) {
1709 throw new RuntimeException("Cannot digest with algorithm " + algorithm
, e
);
1710 } catch (NoSuchAlgorithmException e
) {
1711 throw new IllegalArgumentException("Cannot digest with algorithm " + algorithm
, e
);
1717 * http://stackoverflow.com/questions/9655181/how-to-convert-a-byte-array-to
1718 * -a-hex-string-in-java
1721 private static String
encodeHexString(byte[] bytes
) {
1722 final char[] hexArray
= "0123456789abcdef".toCharArray();
1723 char[] hexChars
= new char[bytes
.length
* 2];
1724 for (int j
= 0; j
< bytes
.length
; j
++) {
1725 int v
= bytes
[j
] & 0xFF;
1726 hexChars
[j
* 2] = hexArray
[v
>>> 4];
1727 hexChars
[j
* 2 + 1] = hexArray
[v
& 0x0F];
1729 return new String(hexChars
);