2 * Copyright (C) 2007-2012 Argeo GmbH
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 package org
.argeo
.jcr
;
18 import java
.io
.ByteArrayInputStream
;
19 import java
.io
.ByteArrayOutputStream
;
21 import java
.io
.FileInputStream
;
22 import java
.io
.IOException
;
23 import java
.io
.InputStream
;
24 import java
.net
.MalformedURLException
;
26 import java
.security
.MessageDigest
;
27 import java
.security
.Principal
;
28 import java
.text
.DateFormat
;
29 import java
.text
.ParseException
;
30 import java
.util
.ArrayList
;
31 import java
.util
.Calendar
;
32 import java
.util
.Collections
;
33 import java
.util
.Date
;
34 import java
.util
.GregorianCalendar
;
35 import java
.util
.Iterator
;
36 import java
.util
.List
;
38 import java
.util
.TreeMap
;
40 import javax
.jcr
.Binary
;
41 import javax
.jcr
.NamespaceRegistry
;
42 import javax
.jcr
.NoSuchWorkspaceException
;
43 import javax
.jcr
.Node
;
44 import javax
.jcr
.NodeIterator
;
45 import javax
.jcr
.Property
;
46 import javax
.jcr
.PropertyIterator
;
47 import javax
.jcr
.PropertyType
;
48 import javax
.jcr
.Repository
;
49 import javax
.jcr
.RepositoryException
;
50 import javax
.jcr
.Session
;
51 import javax
.jcr
.Value
;
52 import javax
.jcr
.Workspace
;
53 import javax
.jcr
.nodetype
.NodeType
;
54 import javax
.jcr
.observation
.EventListener
;
55 import javax
.jcr
.query
.Query
;
56 import javax
.jcr
.query
.QueryResult
;
57 import javax
.jcr
.security
.AccessControlEntry
;
58 import javax
.jcr
.security
.AccessControlList
;
59 import javax
.jcr
.security
.AccessControlManager
;
60 import javax
.jcr
.security
.AccessControlPolicy
;
61 import javax
.jcr
.security
.AccessControlPolicyIterator
;
62 import javax
.jcr
.security
.Privilege
;
64 import org
.apache
.commons
.io
.IOUtils
;
65 import org
.apache
.commons
.logging
.Log
;
66 import org
.apache
.commons
.logging
.LogFactory
;
68 /** Utility methods to simplify common JCR operations. */
69 public class JcrUtils
{
71 final private static Log log
= LogFactory
.getLog(JcrUtils
.class);
74 * Not complete yet. See
75 * http://www.day.com/specs/jcr/2.0/3_Repository_Model.html#3.2.2%20Local
78 public final static char[] INVALID_NAME_CHARACTERS
= { '/', ':', '[', ']', '|', '*', /* invalid for XML: */ '<',
81 /** Prevents instantiation */
86 * Queries one single node.
88 * @return one single node or null if none was found
89 * @throws ArgeoJcrException if more than one node was found
91 public static Node
querySingleNode(Query query
) {
92 NodeIterator nodeIterator
;
94 QueryResult queryResult
= query
.execute();
95 nodeIterator
= queryResult
.getNodes();
96 } catch (RepositoryException e
) {
97 throw new ArgeoJcrException("Cannot execute query " + query
, e
);
100 if (nodeIterator
.hasNext())
101 node
= nodeIterator
.nextNode();
105 if (nodeIterator
.hasNext())
106 throw new ArgeoJcrException("Query returned more than one node.");
110 /** Retrieves the node name from the provided path */
111 public static String
nodeNameFromPath(String path
) {
112 if (path
.equals("/"))
114 if (path
.charAt(0) != '/')
115 throw new ArgeoJcrException("Path " + path
+ " must start with a '/'");
117 if (pathT
.charAt(pathT
.length() - 1) == '/')
118 pathT
= pathT
.substring(0, pathT
.length() - 2);
120 int index
= pathT
.lastIndexOf('/');
121 return pathT
.substring(index
+ 1);
124 /** Retrieves the parent path of the provided path */
125 public static String
parentPath(String path
) {
126 if (path
.equals("/"))
127 throw new ArgeoJcrException("Root path '/' has no parent path");
128 if (path
.charAt(0) != '/')
129 throw new ArgeoJcrException("Path " + path
+ " must start with a '/'");
131 if (pathT
.charAt(pathT
.length() - 1) == '/')
132 pathT
= pathT
.substring(0, pathT
.length() - 2);
134 int index
= pathT
.lastIndexOf('/');
135 return pathT
.substring(0, index
);
138 /** The provided data as a path ('/' at the end, not the beginning) */
139 public static String
dateAsPath(Calendar cal
) {
140 return dateAsPath(cal
, false);
144 * Creates a deep path based on a URL:
145 * http://subdomain.example.com/to/content?args becomes
146 * com/example/subdomain/to/content
148 public static String
urlAsPath(String url
) {
150 URL u
= new URL(url
);
151 StringBuffer path
= new StringBuffer(url
.length());
153 path
.append(hostAsPath(u
.getHost()));
154 // we don't put port since it may not always be there and may change
155 path
.append(u
.getPath());
156 return path
.toString();
157 } catch (MalformedURLException e
) {
158 throw new ArgeoJcrException("Cannot generate URL path for " + url
, e
);
162 /** Set the {@link NodeType#NT_ADDRESS} properties based on this URL. */
163 public static void urlToAddressProperties(Node node
, String url
) {
165 URL u
= new URL(url
);
166 node
.setProperty(Property
.JCR_PROTOCOL
, u
.getProtocol());
167 node
.setProperty(Property
.JCR_HOST
, u
.getHost());
168 node
.setProperty(Property
.JCR_PORT
, Integer
.toString(u
.getPort()));
169 node
.setProperty(Property
.JCR_PATH
, normalizePath(u
.getPath()));
170 } catch (Exception e
) {
171 throw new ArgeoJcrException("Cannot set URL " + url
+ " as nt:address properties", e
);
175 /** Build URL based on the {@link NodeType#NT_ADDRESS} properties. */
176 public static String
urlFromAddressProperties(Node node
) {
178 URL u
= new URL(node
.getProperty(Property
.JCR_PROTOCOL
).getString(),
179 node
.getProperty(Property
.JCR_HOST
).getString(),
180 (int) node
.getProperty(Property
.JCR_PORT
).getLong(),
181 node
.getProperty(Property
.JCR_PATH
).getString());
183 } catch (Exception e
) {
184 throw new ArgeoJcrException("Cannot get URL from nt:address properties of " + node
, e
);
193 * Make sure that: starts with '/', do not end with '/', do not have '//'
195 public static String
normalizePath(String path
) {
196 List
<String
> tokens
= tokenize(path
);
197 StringBuffer buf
= new StringBuffer(path
.length());
198 for (String token
: tokens
) {
202 return buf
.toString();
206 * Creates a path from a FQDN, inverting the order of the component:
207 * www.argeo.org becomes org.argeo.www
209 public static String
hostAsPath(String host
) {
210 StringBuffer path
= new StringBuffer(host
.length());
211 String
[] hostTokens
= host
.split("\\.");
212 for (int i
= hostTokens
.length
- 1; i
>= 0; i
--) {
213 path
.append(hostTokens
[i
]);
217 return path
.toString();
221 * Creates a path from a UUID (e.g. 6ebda899-217d-4bf1-abe4-2839085c8f3c becomes
222 * 6ebda899-217d/4bf1/abe4/2839085c8f3c/). '/' at the end, not the beginning
224 public static String
uuidAsPath(String uuid
) {
225 StringBuffer path
= new StringBuffer(uuid
.length());
226 String
[] tokens
= uuid
.split("-");
227 for (int i
= 0; i
< tokens
.length
; i
++) {
228 path
.append(tokens
[i
]);
232 return path
.toString();
236 * The provided data as a path ('/' at the end, not the beginning)
238 * @param cal the date
239 * @param addHour whether to add hour as well
241 public static String
dateAsPath(Calendar cal
, Boolean addHour
) {
242 StringBuffer buf
= new StringBuffer(14);
244 buf
.append(cal
.get(Calendar
.YEAR
));
247 int month
= cal
.get(Calendar
.MONTH
) + 1;
254 int day
= cal
.get(Calendar
.DAY_OF_MONTH
);
262 int hour
= cal
.get(Calendar
.HOUR_OF_DAY
);
269 return buf
.toString();
273 /** Converts in one call a string into a gregorian calendar. */
274 public static Calendar
parseCalendar(DateFormat dateFormat
, String value
) {
276 Date date
= dateFormat
.parse(value
);
277 Calendar calendar
= new GregorianCalendar();
278 calendar
.setTime(date
);
280 } catch (ParseException e
) {
281 throw new ArgeoJcrException("Cannot parse " + value
+ " with date format " + dateFormat
, e
);
286 /** The last element of a path. */
287 public static String
lastPathElement(String path
) {
288 if (path
.charAt(path
.length() - 1) == '/')
289 throw new ArgeoJcrException("Path " + path
+ " cannot end with '/'");
290 int index
= path
.lastIndexOf('/');
293 return path
.substring(index
+ 1);
297 * Call {@link Node#getName()} without exceptions (useful in super
300 public static String
getNameQuietly(Node node
) {
302 return node
.getName();
303 } catch (RepositoryException e
) {
304 throw new ArgeoJcrException("Cannot get name from " + node
, e
);
309 * Call {@link Node#getProperty(String)} without exceptions (useful in super
312 public static String
getStringPropertyQuietly(Node node
, String propertyName
) {
314 return node
.getProperty(propertyName
).getString();
315 } catch (RepositoryException e
) {
316 throw new ArgeoJcrException("Cannot get name from " + node
, e
);
321 * Routine that get the child with this name, adding id it does not already
324 public static Node
getOrAdd(Node parent
, String childName
, String childPrimaryNodeType
) throws RepositoryException
{
325 return parent
.hasNode(childName
) ? parent
.getNode(childName
) : parent
.addNode(childName
, childPrimaryNodeType
);
329 * Routine that get the child with this name, adding id it does not already
332 public static Node
getOrAdd(Node parent
, String childName
) throws RepositoryException
{
333 return parent
.hasNode(childName
) ? parent
.getNode(childName
) : parent
.addNode(childName
);
336 /** Convert a {@link NodeIterator} to a list of {@link Node} */
337 public static List
<Node
> nodeIteratorToList(NodeIterator nodeIterator
) {
338 List
<Node
> nodes
= new ArrayList
<Node
>();
339 while (nodeIterator
.hasNext()) {
340 nodes
.add(nodeIterator
.nextNode());
350 * Concisely get the string value of a property or null if this node doesn't
353 public static String
get(Node node
, String propertyName
) {
355 if (!node
.hasProperty(propertyName
))
357 return node
.getProperty(propertyName
).getString();
358 } catch (RepositoryException e
) {
359 throw new ArgeoJcrException("Cannot get property " + propertyName
+ " of " + node
, e
);
363 /** Concisely get the path of the given node. */
364 public static String
getPath(Node node
) {
366 return node
.getPath();
367 } catch (RepositoryException e
) {
368 throw new ArgeoJcrException("Cannot get path of " + node
, e
);
372 /** Concisely get the boolean value of a property */
373 public static Boolean
check(Node node
, String propertyName
) {
375 return node
.getProperty(propertyName
).getBoolean();
376 } catch (RepositoryException e
) {
377 throw new ArgeoJcrException("Cannot get property " + propertyName
+ " of " + node
, e
);
381 /** Concisely get the bytes array value of a property */
382 public static byte[] getBytes(Node node
, String propertyName
) {
384 return getBinaryAsBytes(node
.getProperty(propertyName
));
385 } catch (RepositoryException e
) {
386 throw new ArgeoJcrException("Cannot get property " + propertyName
+ " of " + node
, e
);
395 * Create sub nodes relative to a parent node
397 public static Node
mkdirs(Node parentNode
, String relativePath
) {
398 return mkdirs(parentNode
, relativePath
, null, null);
402 * Create sub nodes relative to a parent node
404 * @param nodeType the type of the leaf node
406 public static Node
mkdirs(Node parentNode
, String relativePath
, String nodeType
) {
407 return mkdirs(parentNode
, relativePath
, nodeType
, null);
411 * Create sub nodes relative to a parent node
413 * @param nodeType the type of the leaf node
415 public static Node
mkdirs(Node parentNode
, String relativePath
, String nodeType
, String intermediaryNodeType
) {
416 List
<String
> tokens
= tokenize(relativePath
);
417 Node currParent
= parentNode
;
419 for (int i
= 0; i
< tokens
.size(); i
++) {
420 String name
= tokens
.get(i
);
421 if (currParent
.hasNode(name
)) {
422 currParent
= currParent
.getNode(name
);
424 if (i
!= (tokens
.size() - 1)) {// intermediary
425 currParent
= currParent
.addNode(name
, intermediaryNodeType
);
427 currParent
= currParent
.addNode(name
, nodeType
);
432 } catch (RepositoryException e
) {
433 throw new ArgeoJcrException("Cannot mkdirs relative path " + relativePath
+ " from " + parentNode
, e
);
438 * Synchronized and save is performed, to avoid race conditions in initializers
439 * leading to duplicate nodes.
441 public synchronized static Node
mkdirsSafe(Session session
, String path
, String type
) {
443 if (session
.hasPendingChanges())
444 throw new ArgeoJcrException("Session has pending changes, save them first.");
445 Node node
= mkdirs(session
, path
, type
);
448 } catch (RepositoryException e
) {
449 discardQuietly(session
);
450 throw new ArgeoJcrException("Cannot safely make directories", e
);
454 public synchronized static Node
mkdirsSafe(Session session
, String path
) {
455 return mkdirsSafe(session
, path
, null);
458 /** Creates the nodes making path, if they don't exist. */
459 public static Node
mkdirs(Session session
, String path
) {
460 return mkdirs(session
, path
, null, null, false);
464 * @param type the type of the leaf node
466 public static Node
mkdirs(Session session
, String path
, String type
) {
467 return mkdirs(session
, path
, type
, null, false);
471 * Creates the nodes making path, if they don't exist. This is up to the caller
472 * to save the session. Use with caution since it can create duplicate nodes if
473 * used concurrently. Requires read access to the root node of the workspace.
475 public static Node
mkdirs(Session session
, String path
, String type
, String intermediaryNodeType
,
476 Boolean versioning
) {
478 if (path
.equals("/"))
479 return session
.getRootNode();
481 if (session
.itemExists(path
)) {
482 Node node
= session
.getNode(path
);
484 if (type
!= null && !node
.isNodeType(type
) && !node
.getPath().equals("/"))
485 throw new ArgeoJcrException("Node " + node
+ " exists but is of type "
486 + node
.getPrimaryNodeType().getName() + " not of type " + type
);
487 // TODO: check versioning
491 // StringBuffer current = new StringBuffer("/");
492 // Node currentNode = session.getRootNode();
494 Node currentNode
= findClosestExistingParent(session
, path
);
495 String closestExistingParentPath
= currentNode
.getPath();
496 StringBuffer current
= new StringBuffer(closestExistingParentPath
);
497 if (!closestExistingParentPath
.endsWith("/"))
499 Iterator
<String
> it
= tokenize(path
.substring(closestExistingParentPath
.length())).iterator();
500 while (it
.hasNext()) {
501 String part
= it
.next();
502 current
.append(part
).append('/');
503 if (!session
.itemExists(current
.toString())) {
504 if (!it
.hasNext() && type
!= null)
505 currentNode
= currentNode
.addNode(part
, type
);
506 else if (it
.hasNext() && intermediaryNodeType
!= null)
507 currentNode
= currentNode
.addNode(part
, intermediaryNodeType
);
509 currentNode
= currentNode
.addNode(part
);
511 currentNode
.addMixin(NodeType
.MIX_VERSIONABLE
);
512 if (log
.isTraceEnabled())
513 log
.debug("Added folder " + part
+ " as " + current
);
515 currentNode
= (Node
) session
.getItem(current
.toString());
519 } catch (RepositoryException e
) {
520 discardQuietly(session
);
521 throw new ArgeoJcrException("Cannot mkdirs " + path
, e
);
526 private static Node
findClosestExistingParent(Session session
, String path
) throws RepositoryException
{
527 int idx
= path
.lastIndexOf('/');
529 return session
.getRootNode();
530 String parentPath
= path
.substring(0, idx
);
531 if (session
.itemExists(parentPath
))
532 return session
.getNode(parentPath
);
534 return findClosestExistingParent(session
, parentPath
);
537 /** Convert a path to the list of its tokens */
538 public static List
<String
> tokenize(String path
) {
539 List
<String
> tokens
= new ArrayList
<String
>();
540 boolean optimized
= false;
542 String
[] rawTokens
= path
.split("/");
543 for (String token
: rawTokens
) {
544 if (!token
.equals(""))
548 StringBuffer curr
= new StringBuffer();
549 char[] arr
= path
.toCharArray();
550 chars
: for (int i
= 0; i
< arr
.length
; i
++) {
553 if (i
== 0 || (i
== arr
.length
- 1))
555 if (curr
.length() > 0) {
556 tokens
.add(curr
.toString());
557 curr
= new StringBuffer();
562 if (curr
.length() > 0) {
563 tokens
.add(curr
.toString());
564 curr
= new StringBuffer();
567 return Collections
.unmodifiableList(tokens
);
571 // * use {@link #mkdirs(Session, String, String, String, Boolean)} instead.
576 // public static Node mkdirs(Session session, String path, String type,
577 // Boolean versioning) {
578 // return mkdirs(session, path, type, type, false);
582 * Safe and repository implementation independent registration of a namespace.
584 public static void registerNamespaceSafely(Session session
, String prefix
, String uri
) {
586 registerNamespaceSafely(session
.getWorkspace().getNamespaceRegistry(), prefix
, uri
);
587 } catch (RepositoryException e
) {
588 throw new ArgeoJcrException("Cannot find namespace registry", e
);
593 * Safe and repository implementation independent registration of a namespace.
595 public static void registerNamespaceSafely(NamespaceRegistry nr
, String prefix
, String uri
) {
597 String
[] prefixes
= nr
.getPrefixes();
598 for (String pref
: prefixes
)
599 if (pref
.equals(prefix
)) {
600 String registeredUri
= nr
.getURI(pref
);
601 if (!registeredUri
.equals(uri
))
602 throw new ArgeoJcrException("Prefix " + pref
+ " already registered for URI " + registeredUri
603 + " which is different from provided URI " + uri
);
607 nr
.registerNamespace(prefix
, uri
);
608 } catch (RepositoryException e
) {
609 throw new ArgeoJcrException("Cannot register namespace " + uri
+ " under prefix " + prefix
, e
);
613 /** Recursively outputs the contents of the given node. */
614 public static void debug(Node node
) {
618 /** Recursively outputs the contents of the given node. */
619 public static void debug(Node node
, Log log
) {
621 // First output the node path
622 log
.debug(node
.getPath());
623 // Skip the virtual (and large!) jcr:system subtree
624 if (node
.getName().equals("jcr:system")) {
628 // Then the children nodes (recursive)
629 NodeIterator it
= node
.getNodes();
630 while (it
.hasNext()) {
631 Node childNode
= it
.nextNode();
632 debug(childNode
, log
);
635 // Then output the properties
636 PropertyIterator properties
= node
.getProperties();
637 // log.debug("Property are : ");
639 properties
: while (properties
.hasNext()) {
640 Property property
= properties
.nextProperty();
641 if (property
.getType() == PropertyType
.BINARY
)
642 continue properties
;// skip
643 if (property
.getDefinition().isMultiple()) {
644 // A multi-valued property, print all values
645 Value
[] values
= property
.getValues();
646 for (int i
= 0; i
< values
.length
; i
++) {
647 log
.debug(property
.getPath() + "=" + values
[i
].getString());
650 // A single-valued property
651 log
.debug(property
.getPath() + "=" + property
.getString());
654 } catch (Exception e
) {
655 log
.error("Could not debug " + node
, e
);
660 /** Logs the effective access control policies */
661 public static void logEffectiveAccessPolicies(Node node
) {
663 logEffectiveAccessPolicies(node
.getSession(), node
.getPath());
664 } catch (RepositoryException e
) {
665 log
.error("Cannot log effective access policies of " + node
, e
);
669 /** Logs the effective access control policies */
670 public static void logEffectiveAccessPolicies(Session session
, String path
) {
671 if (!log
.isDebugEnabled())
675 AccessControlPolicy
[] effectivePolicies
= session
.getAccessControlManager().getEffectivePolicies(path
);
676 if (effectivePolicies
.length
> 0) {
677 for (AccessControlPolicy policy
: effectivePolicies
) {
678 if (policy
instanceof AccessControlList
) {
679 AccessControlList acl
= (AccessControlList
) policy
;
680 log
.debug("Access control list for " + path
+ "\n" + accessControlListSummary(acl
));
684 log
.debug("No effective access control policy for " + path
);
686 } catch (RepositoryException e
) {
687 log
.error("Cannot log effective access policies of " + path
, e
);
691 /** Returns a human-readable summary of this access control list. */
692 public static String
accessControlListSummary(AccessControlList acl
) {
693 StringBuffer buf
= new StringBuffer("");
695 for (AccessControlEntry ace
: acl
.getAccessControlEntries()) {
696 buf
.append('\t').append(ace
.getPrincipal().getName()).append('\n');
697 for (Privilege priv
: ace
.getPrivileges())
698 buf
.append("\t\t").append(priv
.getName()).append('\n');
700 return buf
.toString();
701 } catch (RepositoryException e
) {
702 throw new ArgeoJcrException("Cannot write summary of " + acl
, e
);
707 * Copies recursively the content of a node to another one. Do NOT copy the
708 * property values of {@link NodeType#MIX_CREATED} and
709 * {@link NodeType#MIX_LAST_MODIFIED}, but update the
710 * {@link Property#JCR_LAST_MODIFIED} and {@link Property#JCR_LAST_MODIFIED_BY}
711 * properties if the target node has the {@link NodeType#MIX_LAST_MODIFIED}
714 public static void copy(Node fromNode
, Node toNode
) {
716 if (toNode
.getDefinition().isProtected())
719 // process properties
720 PropertyIterator pit
= fromNode
.getProperties();
721 properties
: while (pit
.hasNext()) {
722 Property fromProperty
= pit
.nextProperty();
723 String propertyName
= fromProperty
.getName();
724 if (toNode
.hasProperty(propertyName
) && toNode
.getProperty(propertyName
).getDefinition().isProtected())
727 if (fromProperty
.getDefinition().isProtected())
730 if (propertyName
.equals("jcr:created") || propertyName
.equals("jcr:createdBy")
731 || propertyName
.equals("jcr:lastModified") || propertyName
.equals("jcr:lastModifiedBy"))
734 if (fromProperty
.isMultiple()) {
735 toNode
.setProperty(propertyName
, fromProperty
.getValues());
737 toNode
.setProperty(propertyName
, fromProperty
.getValue());
741 // update jcr:lastModified and jcr:lastModifiedBy in toNode in case
742 // they existed, before adding the mixins
743 updateLastModified(toNode
);
746 for (NodeType mixinType
: fromNode
.getMixinNodeTypes()) {
747 toNode
.addMixin(mixinType
.getName());
750 // process children nodes
751 NodeIterator nit
= fromNode
.getNodes();
752 while (nit
.hasNext()) {
753 Node fromChild
= nit
.nextNode();
754 Integer index
= fromChild
.getIndex();
755 String nodeRelPath
= fromChild
.getName() + "[" + index
+ "]";
757 if (toNode
.hasNode(nodeRelPath
))
758 toChild
= toNode
.getNode(nodeRelPath
);
760 toChild
= toNode
.addNode(fromChild
.getName(), fromChild
.getPrimaryNodeType().getName());
761 copy(fromChild
, toChild
);
763 } catch (RepositoryException e
) {
764 throw new ArgeoJcrException("Cannot copy " + fromNode
+ " to " + toNode
, e
);
769 * Check whether all first-level properties (except jcr:* properties) are equal.
770 * Skip jcr:* properties
772 public static Boolean
allPropertiesEquals(Node reference
, Node observed
, Boolean onlyCommonProperties
) {
774 PropertyIterator pit
= reference
.getProperties();
775 props
: while (pit
.hasNext()) {
776 Property propReference
= pit
.nextProperty();
777 String propName
= propReference
.getName();
778 if (propName
.startsWith("jcr:"))
781 if (!observed
.hasProperty(propName
))
782 if (onlyCommonProperties
)
786 // TODO: deal with multiple property values?
787 if (!observed
.getProperty(propName
).getValue().equals(propReference
.getValue()))
791 } catch (RepositoryException e
) {
792 throw new ArgeoJcrException("Cannot check all properties equals of " + reference
+ " and " + observed
, e
);
796 public static Map
<String
, PropertyDiff
> diffProperties(Node reference
, Node observed
) {
797 Map
<String
, PropertyDiff
> diffs
= new TreeMap
<String
, PropertyDiff
>();
798 diffPropertiesLevel(diffs
, null, reference
, observed
);
803 * Compare the properties of two nodes. Recursivity to child nodes is not yet
804 * supported. Skip jcr:* properties.
806 static void diffPropertiesLevel(Map
<String
, PropertyDiff
> diffs
, String baseRelPath
, Node reference
,
809 // check removed and modified
810 PropertyIterator pit
= reference
.getProperties();
811 props
: while (pit
.hasNext()) {
812 Property p
= pit
.nextProperty();
813 String name
= p
.getName();
814 if (name
.startsWith("jcr:"))
817 if (!observed
.hasProperty(name
)) {
818 String relPath
= propertyRelPath(baseRelPath
, name
);
819 PropertyDiff pDiff
= new PropertyDiff(PropertyDiff
.REMOVED
, relPath
, p
.getValue(), null);
820 diffs
.put(relPath
, pDiff
);
822 if (p
.isMultiple()) {
823 // FIXME implement multiple
825 Value referenceValue
= p
.getValue();
826 Value newValue
= observed
.getProperty(name
).getValue();
827 if (!referenceValue
.equals(newValue
)) {
828 String relPath
= propertyRelPath(baseRelPath
, name
);
829 PropertyDiff pDiff
= new PropertyDiff(PropertyDiff
.MODIFIED
, relPath
, referenceValue
,
831 diffs
.put(relPath
, pDiff
);
837 pit
= observed
.getProperties();
838 props
: while (pit
.hasNext()) {
839 Property p
= pit
.nextProperty();
840 String name
= p
.getName();
841 if (name
.startsWith("jcr:"))
843 if (!reference
.hasProperty(name
)) {
844 if (p
.isMultiple()) {
845 // FIXME implement multiple
847 String relPath
= propertyRelPath(baseRelPath
, name
);
848 PropertyDiff pDiff
= new PropertyDiff(PropertyDiff
.ADDED
, relPath
, null, p
.getValue());
849 diffs
.put(relPath
, pDiff
);
853 } catch (RepositoryException e
) {
854 throw new ArgeoJcrException("Cannot diff " + reference
+ " and " + observed
, e
);
859 * Compare only a restricted list of properties of two nodes. No recursivity.
862 public static Map
<String
, PropertyDiff
> diffProperties(Node reference
, Node observed
, List
<String
> properties
) {
863 Map
<String
, PropertyDiff
> diffs
= new TreeMap
<String
, PropertyDiff
>();
865 Iterator
<String
> pit
= properties
.iterator();
867 props
: while (pit
.hasNext()) {
868 String name
= pit
.next();
869 if (!reference
.hasProperty(name
)) {
870 if (!observed
.hasProperty(name
))
872 Value val
= observed
.getProperty(name
).getValue();
874 // empty String but not null
875 if ("".equals(val
.getString()))
877 } catch (Exception e
) {
878 // not parseable as String, silent
880 PropertyDiff pDiff
= new PropertyDiff(PropertyDiff
.ADDED
, name
, null, val
);
881 diffs
.put(name
, pDiff
);
882 } else if (!observed
.hasProperty(name
)) {
883 PropertyDiff pDiff
= new PropertyDiff(PropertyDiff
.REMOVED
, name
,
884 reference
.getProperty(name
).getValue(), null);
885 diffs
.put(name
, pDiff
);
887 Value referenceValue
= reference
.getProperty(name
).getValue();
888 Value newValue
= observed
.getProperty(name
).getValue();
889 if (!referenceValue
.equals(newValue
)) {
890 PropertyDiff pDiff
= new PropertyDiff(PropertyDiff
.MODIFIED
, name
, referenceValue
, newValue
);
891 diffs
.put(name
, pDiff
);
895 } catch (RepositoryException e
) {
896 throw new ArgeoJcrException("Cannot diff " + reference
+ " and " + observed
, e
);
901 /** Builds a property relPath to be used in the diff. */
902 private static String
propertyRelPath(String baseRelPath
, String propertyName
) {
903 if (baseRelPath
== null)
906 return baseRelPath
+ '/' + propertyName
;
910 * Normalizes a name so that it can be stored in contexts not supporting names
911 * with ':' (typically databases). Replaces ':' by '_'.
913 public static String
normalize(String name
) {
914 return name
.replace(':', '_');
918 * Replaces characters which are invalid in a JCR name by '_'. Currently not
921 * @see JcrUtils#INVALID_NAME_CHARACTERS
923 public static String
replaceInvalidChars(String name
) {
924 return replaceInvalidChars(name
, '_');
928 * Replaces characters which are invalid in a JCR name. Currently not
931 * @see JcrUtils#INVALID_NAME_CHARACTERS
933 public static String
replaceInvalidChars(String name
, char replacement
) {
934 boolean modified
= false;
935 char[] arr
= name
.toCharArray();
936 for (int i
= 0; i
< arr
.length
; i
++) {
938 invalid
: for (char invalid
: INVALID_NAME_CHARACTERS
) {
940 arr
[i
] = replacement
;
947 return new String(arr
);
949 // do not create new object if unnecessary
954 // * Removes forbidden characters from a path, replacing them with '_'
956 // * @deprecated use {@link #replaceInvalidChars(String)} instead
958 // public static String removeForbiddenCharacters(String str) {
959 // return str.replace('[', '_').replace(']', '_').replace('/', '_').replace('*',
964 /** Cleanly disposes a {@link Binary} even if it is null. */
965 public static void closeQuietly(Binary binary
) {
971 /** Retrieve a {@link Binary} as a byte array */
972 public static byte[] getBinaryAsBytes(Property property
) {
973 // ByteArrayOutputStream out = new ByteArrayOutputStream();
974 // InputStream in = null;
975 // Binary binary = null;
976 try (ByteArrayOutputStream out
= new ByteArrayOutputStream();
977 Bin binary
= new Bin(property
);
978 InputStream in
= binary
.getStream()) {
979 // binary = property.getBinary();
980 // in = binary.getStream();
981 IOUtils
.copy(in
, out
);
982 return out
.toByteArray();
983 } catch (Exception e
) {
984 throw new ArgeoJcrException("Cannot read binary " + property
+ " as bytes", e
);
986 // IOUtils.closeQuietly(out);
987 // IOUtils.closeQuietly(in);
988 // closeQuietly(binary);
992 /** Writes a {@link Binary} from a byte array */
993 public static void setBinaryAsBytes(Node node
, String property
, byte[] bytes
) {
994 // InputStream in = null;
995 Binary binary
= null;
996 try (InputStream in
= new ByteArrayInputStream(bytes
)) {
997 // in = new ByteArrayInputStream(bytes);
998 binary
= node
.getSession().getValueFactory().createBinary(in
);
999 node
.setProperty(property
, binary
);
1000 } catch (Exception e
) {
1001 throw new ArgeoJcrException("Cannot read binary " + property
+ " as bytes", e
);
1003 // IOUtils.closeQuietly(in);
1004 closeQuietly(binary
);
1009 * Creates depth from a string (typically a username) by adding levels based on
1010 * its first characters: "aBcD",2 becomes a/aB
1012 public static String
firstCharsToPath(String str
, Integer nbrOfChars
) {
1013 if (str
.length() < nbrOfChars
)
1014 throw new ArgeoJcrException("String " + str
+ " length must be greater or equal than " + nbrOfChars
);
1015 StringBuffer path
= new StringBuffer("");
1016 StringBuffer curr
= new StringBuffer("");
1017 for (int i
= 0; i
< nbrOfChars
; i
++) {
1018 curr
.append(str
.charAt(i
));
1020 if (i
< nbrOfChars
- 1)
1023 return path
.toString();
1027 * Discards the current changes in the session attached to this node. To be used
1028 * typically in a catch block.
1030 * @see #discardQuietly(Session)
1032 public static void discardUnderlyingSessionQuietly(Node node
) {
1034 discardQuietly(node
.getSession());
1035 } catch (RepositoryException e
) {
1036 log
.warn("Cannot quietly discard session of node " + node
+ ": " + e
.getMessage());
1041 * Discards the current changes in a session by calling
1042 * {@link Session#refresh(boolean)} with <code>false</code>, only logging
1043 * potential errors when doing so. To be used typically in a catch block.
1045 public static void discardQuietly(Session session
) {
1047 if (session
!= null)
1048 session
.refresh(false);
1049 } catch (RepositoryException e
) {
1050 log
.warn("Cannot quietly discard session " + session
+ ": " + e
.getMessage());
1055 * Login to a workspace with implicit credentials, creates the workspace with
1056 * these credentials if it does not already exist.
1058 public static Session
loginOrCreateWorkspace(Repository repository
, String workspaceName
)
1059 throws RepositoryException
{
1060 Session workspaceSession
= null;
1061 Session defaultSession
= null;
1064 workspaceSession
= repository
.login(workspaceName
);
1065 } catch (NoSuchWorkspaceException e
) {
1066 // try to create workspace
1067 defaultSession
= repository
.login();
1068 defaultSession
.getWorkspace().createWorkspace(workspaceName
);
1069 workspaceSession
= repository
.login(workspaceName
);
1071 return workspaceSession
;
1073 logoutQuietly(defaultSession
);
1077 /** Logs out the session, not throwing any exception, even if it is null. */
1078 public static void logoutQuietly(Session session
) {
1080 if (session
!= null)
1081 if (session
.isLive())
1083 } catch (Exception e
) {
1089 * Convenient method to add a listener. uuids passed as null, deep=true,
1090 * local=true, only one node type
1092 public static void addListener(Session session
, EventListener listener
, int eventTypes
, String basePath
,
1095 session
.getWorkspace().getObservationManager().addEventListener(listener
, eventTypes
, basePath
, true, null,
1096 nodeType
== null ?
null : new String
[] { nodeType
}, true);
1097 } catch (RepositoryException e
) {
1098 throw new ArgeoJcrException("Cannot add JCR listener " + listener
+ " to session " + session
, e
);
1102 /** Removes a listener without throwing exception */
1103 public static void removeListenerQuietly(Session session
, EventListener listener
) {
1104 if (session
== null || !session
.isLive())
1107 session
.getWorkspace().getObservationManager().removeEventListener(listener
);
1108 } catch (RepositoryException e
) {
1114 * Quietly unregisters an {@link EventListener} from the udnerlying workspace of
1117 public static void unregisterQuietly(Node node
, EventListener eventListener
) {
1119 unregisterQuietly(node
.getSession().getWorkspace(), eventListener
);
1120 } catch (RepositoryException e
) {
1122 if (log
.isTraceEnabled())
1123 log
.trace("Could not unregister event listener " + eventListener
);
1127 /** Quietly unregisters an {@link EventListener} from this workspace */
1128 public static void unregisterQuietly(Workspace workspace
, EventListener eventListener
) {
1129 if (eventListener
== null)
1132 workspace
.getObservationManager().removeEventListener(eventListener
);
1133 } catch (RepositoryException e
) {
1135 if (log
.isTraceEnabled())
1136 log
.trace("Could not unregister event listener " + eventListener
);
1141 * If this node is has the {@link NodeType#MIX_LAST_MODIFIED} mixin, it updates
1142 * the {@link Property#JCR_LAST_MODIFIED} property with the current time and the
1143 * {@link Property#JCR_LAST_MODIFIED_BY} property with the underlying session
1144 * user id. In Jackrabbit 2.x,
1145 * <a href="https://issues.apache.org/jira/browse/JCR-2233">these properties are
1146 * not automatically updated</a>, hence the need for manual update. The session
1149 public static void updateLastModified(Node node
) {
1151 if (!node
.isNodeType(NodeType
.MIX_LAST_MODIFIED
))
1152 node
.addMixin(NodeType
.MIX_LAST_MODIFIED
);
1153 node
.setProperty(Property
.JCR_LAST_MODIFIED
, new GregorianCalendar());
1154 node
.setProperty(Property
.JCR_LAST_MODIFIED_BY
, node
.getSession().getUserID());
1155 } catch (RepositoryException e
) {
1156 throw new ArgeoJcrException("Cannot update last modified on " + node
, e
);
1161 * Update lastModified recursively until this parent.
1163 * @param node the node
1164 * @param untilPath the base path, null is equivalent to "/"
1166 public static void updateLastModifiedAndParents(Node node
, String untilPath
) {
1168 if (untilPath
!= null && !node
.getPath().startsWith(untilPath
))
1169 throw new ArgeoJcrException(node
+ " is not under " + untilPath
);
1170 updateLastModified(node
);
1171 if (untilPath
== null) {
1172 if (!node
.getPath().equals("/"))
1173 updateLastModifiedAndParents(node
.getParent(), untilPath
);
1175 if (!node
.getPath().equals(untilPath
))
1176 updateLastModifiedAndParents(node
.getParent(), untilPath
);
1178 } catch (RepositoryException e
) {
1179 throw new ArgeoJcrException("Cannot update lastModified from " + node
+ " until " + untilPath
, e
);
1184 * Returns a String representing the short version (see
1185 * <a href="http://jackrabbit.apache.org/node-type-notation.html"> Node type
1186 * Notation </a> attributes grammar) of the main business attributes of this
1187 * property definition
1191 public static String
getPropertyDefinitionAsString(Property prop
) {
1192 StringBuffer sbuf
= new StringBuffer();
1194 if (prop
.getDefinition().isAutoCreated())
1196 if (prop
.getDefinition().isMandatory())
1198 if (prop
.getDefinition().isProtected())
1200 if (prop
.getDefinition().isMultiple())
1202 } catch (RepositoryException re
) {
1203 throw new ArgeoJcrException("unexpected error while getting property definition as String", re
);
1205 return sbuf
.toString();
1209 * Estimate the sub tree size from current node. Computation is based on the Jcr
1210 * {@link Property#getLength()} method. Note : it is not the exact size used on
1211 * the disk by the current part of the JCR Tree.
1214 public static long getNodeApproxSize(Node node
) {
1215 long curNodeSize
= 0;
1217 PropertyIterator pi
= node
.getProperties();
1218 while (pi
.hasNext()) {
1219 Property prop
= pi
.nextProperty();
1220 if (prop
.isMultiple()) {
1221 int nb
= prop
.getLengths().length
;
1222 for (int i
= 0; i
< nb
; i
++) {
1223 curNodeSize
+= (prop
.getLengths()[i
] > 0 ? prop
.getLengths()[i
] : 0);
1226 curNodeSize
+= (prop
.getLength() > 0 ? prop
.getLength() : 0);
1229 NodeIterator ni
= node
.getNodes();
1230 while (ni
.hasNext())
1231 curNodeSize
+= getNodeApproxSize(ni
.nextNode());
1233 } catch (RepositoryException re
) {
1234 throw new ArgeoJcrException("Unexpected error while recursively determining node size.", re
);
1243 * Convenience method for adding a single privilege to a principal (user or
1244 * role), typically jcr:all
1246 public synchronized static void addPrivilege(Session session
, String path
, String principal
, String privilege
)
1247 throws RepositoryException
{
1248 List
<Privilege
> privileges
= new ArrayList
<Privilege
>();
1249 privileges
.add(session
.getAccessControlManager().privilegeFromName(privilege
));
1250 addPrivileges(session
, path
, new SimplePrincipal(principal
), privileges
);
1254 * Add privileges on a path to a {@link Principal}. The path must already exist.
1255 * Session is saved. Synchronized to prevent concurrent modifications of the
1258 public synchronized static Boolean
addPrivileges(Session session
, String path
, Principal principal
,
1259 List
<Privilege
> privs
) throws RepositoryException
{
1260 // make sure the session is in line with the persisted state
1261 session
.refresh(false);
1262 AccessControlManager acm
= session
.getAccessControlManager();
1263 AccessControlList acl
= getAccessControlList(acm
, path
);
1265 accessControlEntries
: for (AccessControlEntry ace
: acl
.getAccessControlEntries()) {
1266 Principal currentPrincipal
= ace
.getPrincipal();
1267 if (currentPrincipal
.getName().equals(principal
.getName())) {
1268 Privilege
[] currentPrivileges
= ace
.getPrivileges();
1269 if (currentPrivileges
.length
!= privs
.size())
1270 break accessControlEntries
;
1271 for (int i
= 0; i
< currentPrivileges
.length
; i
++) {
1272 Privilege currP
= currentPrivileges
[i
];
1273 Privilege p
= privs
.get(i
);
1274 if (!currP
.getName().equals(p
.getName())) {
1275 break accessControlEntries
;
1282 Privilege
[] privileges
= privs
.toArray(new Privilege
[privs
.size()]);
1283 acl
.addAccessControlEntry(principal
, privileges
);
1284 acm
.setPolicy(path
, acl
);
1285 if (log
.isDebugEnabled()) {
1286 StringBuffer privBuf
= new StringBuffer();
1287 for (Privilege priv
: privs
)
1288 privBuf
.append(priv
.getName());
1289 log
.debug("Added privileges " + privBuf
+ " to " + principal
.getName() + " on " + path
+ " in '"
1290 + session
.getWorkspace().getName() + "'");
1292 session
.refresh(true);
1297 /** Gets access control list for this path, throws exception if not found */
1298 public synchronized static AccessControlList
getAccessControlList(AccessControlManager acm
, String path
)
1299 throws RepositoryException
{
1300 // search for an access control list
1301 AccessControlList acl
= null;
1302 AccessControlPolicyIterator policyIterator
= acm
.getApplicablePolicies(path
);
1303 if (policyIterator
.hasNext()) {
1304 while (policyIterator
.hasNext()) {
1305 AccessControlPolicy acp
= policyIterator
.nextAccessControlPolicy();
1306 if (acp
instanceof AccessControlList
)
1307 acl
= ((AccessControlList
) acp
);
1310 AccessControlPolicy
[] existingPolicies
= acm
.getPolicies(path
);
1311 for (AccessControlPolicy acp
: existingPolicies
) {
1312 if (acp
instanceof AccessControlList
)
1313 acl
= ((AccessControlList
) acp
);
1319 throw new ArgeoJcrException("ACL not found at " + path
);
1322 /** Clear authorizations for a user at this path */
1323 public synchronized static void clearAccessControList(Session session
, String path
, String username
)
1324 throws RepositoryException
{
1325 AccessControlManager acm
= session
.getAccessControlManager();
1326 AccessControlList acl
= getAccessControlList(acm
, path
);
1327 for (AccessControlEntry ace
: acl
.getAccessControlEntries()) {
1328 if (ace
.getPrincipal().getName().equals(username
)) {
1329 acl
.removeAccessControlEntry(ace
);
1332 // the new access control list must be applied otherwise this call:
1333 // acl.removeAccessControlEntry(ace); has no effect
1334 acm
.setPolicy(path
, acl
);
1341 * Creates the nodes making the path as {@link NodeType#NT_FOLDER}
1343 public static Node
mkfolders(Session session
, String path
) {
1344 return mkdirs(session
, path
, NodeType
.NT_FOLDER
, NodeType
.NT_FOLDER
, false);
1348 * Copy only nt:folder and nt:file, without their additional types and
1351 * @param recursive if true copies folders as well, otherwise only first level
1353 * @return how many files were copied
1355 public static Long
copyFiles(Node fromNode
, Node toNode
, Boolean recursive
, JcrMonitor monitor
, boolean onlyAdd
) {
1358 // Binary binary = null;
1359 // InputStream in = null;
1361 NodeIterator fromChildren
= fromNode
.getNodes();
1362 children
: while (fromChildren
.hasNext()) {
1363 if (monitor
!= null && monitor
.isCanceled())
1364 throw new ArgeoJcrException("Copy cancelled before it was completed");
1366 Node fromChild
= fromChildren
.nextNode();
1367 String fileName
= fromChild
.getName();
1368 if (fromChild
.isNodeType(NodeType
.NT_FILE
)) {
1369 if (onlyAdd
&& toNode
.hasNode(fileName
)) {
1370 monitor
.subTask("Skip existing " + fileName
);
1374 if (monitor
!= null)
1375 monitor
.subTask("Copy " + fileName
);
1376 try (Bin binary
= new Bin(fromChild
.getNode(Node
.JCR_CONTENT
).getProperty(Property
.JCR_DATA
));
1377 InputStream in
= binary
.getStream();) {
1378 copyStreamAsFile(toNode
, fileName
, in
);
1380 // IOUtils.closeQuietly(in);
1381 // closeQuietly(binary);
1384 toNode
.getSession().save();
1387 if (log
.isDebugEnabled())
1388 log
.debug("Copied file " + fromChild
.getPath());
1389 if (monitor
!= null)
1391 } else if (fromChild
.isNodeType(NodeType
.NT_FOLDER
) && recursive
) {
1393 if (toNode
.hasNode(fileName
)) {
1394 toChildFolder
= toNode
.getNode(fileName
);
1395 if (!toChildFolder
.isNodeType(NodeType
.NT_FOLDER
))
1396 throw new ArgeoJcrException(toChildFolder
+ " is not of type nt:folder");
1398 toChildFolder
= toNode
.addNode(fileName
, NodeType
.NT_FOLDER
);
1401 toNode
.getSession().save();
1403 count
= count
+ copyFiles(fromChild
, toChildFolder
, recursive
, monitor
, onlyAdd
);
1407 } catch (RepositoryException
| IOException e
) {
1408 throw new ArgeoJcrException("Cannot copy files between " + fromNode
+ " and " + toNode
);
1410 // in case there was an exception
1411 // IOUtils.closeQuietly(in);
1412 // closeQuietly(binary);
1417 * Iteratively count all file nodes in subtree, inefficient but can be useful
1418 * when query are poorly supported, such as in remoting.
1420 public static Long
countFiles(Node node
) {
1421 Long localCount
= 0l;
1423 for (NodeIterator nit
= node
.getNodes(); nit
.hasNext();) {
1424 Node child
= nit
.nextNode();
1425 if (child
.isNodeType(NodeType
.NT_FOLDER
))
1426 localCount
= localCount
+ countFiles(child
);
1427 else if (child
.isNodeType(NodeType
.NT_FILE
))
1428 localCount
= localCount
+ 1;
1430 } catch (RepositoryException e
) {
1431 throw new ArgeoJcrException("Cannot count all children of " + node
);
1437 * Copy a file as an nt:file, assuming an nt:folder hierarchy. The session is
1440 * @return the created file node
1442 public static Node
copyFile(Node folderNode
, File file
) {
1443 // InputStream in = null;
1444 try (InputStream in
= new FileInputStream(file
)) {
1445 // in = new FileInputStream(file);
1446 return copyStreamAsFile(folderNode
, file
.getName(), in
);
1447 } catch (IOException e
) {
1448 throw new ArgeoJcrException("Cannot copy file " + file
+ " under " + folderNode
, e
);
1450 // IOUtils.closeQuietly(in);
1454 /** Copy bytes as an nt:file */
1455 public static Node
copyBytesAsFile(Node folderNode
, String fileName
, byte[] bytes
) {
1456 // InputStream in = null;
1457 try (InputStream in
= new ByteArrayInputStream(bytes
)) {
1458 // in = new ByteArrayInputStream(bytes);
1459 return copyStreamAsFile(folderNode
, fileName
, in
);
1460 } catch (Exception e
) {
1461 throw new ArgeoJcrException("Cannot copy file " + fileName
+ " under " + folderNode
, e
);
1463 // IOUtils.closeQuietly(in);
1468 * Copy a stream as an nt:file, assuming an nt:folder hierarchy. The session is
1471 * @return the created file node
1473 public static Node
copyStreamAsFile(Node folderNode
, String fileName
, InputStream in
) {
1474 Binary binary
= null;
1478 if (folderNode
.hasNode(fileName
)) {
1479 fileNode
= folderNode
.getNode(fileName
);
1480 if (!fileNode
.isNodeType(NodeType
.NT_FILE
))
1481 throw new ArgeoJcrException(fileNode
+ " is not of type nt:file");
1482 // we assume that the content node is already there
1483 contentNode
= fileNode
.getNode(Node
.JCR_CONTENT
);
1485 fileNode
= folderNode
.addNode(fileName
, NodeType
.NT_FILE
);
1486 contentNode
= fileNode
.addNode(Node
.JCR_CONTENT
, NodeType
.NT_RESOURCE
);
1488 binary
= contentNode
.getSession().getValueFactory().createBinary(in
);
1489 contentNode
.setProperty(Property
.JCR_DATA
, binary
);
1491 } catch (Exception e
) {
1492 throw new ArgeoJcrException("Cannot create file node " + fileName
+ " under " + folderNode
, e
);
1494 closeQuietly(binary
);
1499 * Computes the checksum of an nt:file.
1501 * @deprecated use separate digest utilities
1504 public static String
checksumFile(Node fileNode
, String algorithm
) {
1506 try (InputStream in
= fileNode
.getNode(Node
.JCR_CONTENT
).getProperty(Property
.JCR_DATA
).getBinary()
1508 return digest(algorithm
, in
);
1509 } catch (RepositoryException
| IOException e
) {
1510 throw new ArgeoJcrException("Cannot checksum file " + fileNode
, e
);
1517 private static String
digest(String algorithm
, InputStream in
) {
1518 final Integer byteBufferCapacity
= 100 * 1024;// 100 KB
1520 MessageDigest digest
= MessageDigest
.getInstance(algorithm
);
1521 byte[] buffer
= new byte[byteBufferCapacity
];
1523 while ((read
= in
.read(buffer
)) > 0) {
1524 digest
.update(buffer
, 0, read
);
1527 byte[] checksum
= digest
.digest();
1528 String res
= encodeHexString(checksum
);
1530 } catch (Exception e
) {
1531 throw new ArgeoJcrException("Cannot digest with algorithm " + algorithm
, e
);
1537 * http://stackoverflow.com/questions/9655181/how-to-convert-a-byte-array-to
1538 * -a-hex-string-in-java
1541 private static String
encodeHexString(byte[] bytes
) {
1542 final char[] hexArray
= "0123456789abcdef".toCharArray();
1543 char[] hexChars
= new char[bytes
.length
* 2];
1544 for (int j
= 0; j
< bytes
.length
; j
++) {
1545 int v
= bytes
[j
] & 0xFF;
1546 hexChars
[j
* 2] = hexArray
[v
>>> 4];
1547 hexChars
[j
* 2 + 1] = hexArray
[v
& 0x0F];
1549 return new String(hexChars
);