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
90 * if more than one node was found
92 public static Node
querySingleNode(Query query
) {
93 NodeIterator nodeIterator
;
95 QueryResult queryResult
= query
.execute();
96 nodeIterator
= queryResult
.getNodes();
97 } catch (RepositoryException e
) {
98 throw new ArgeoJcrException("Cannot execute query " + query
, e
);
101 if (nodeIterator
.hasNext())
102 node
= nodeIterator
.nextNode();
106 if (nodeIterator
.hasNext())
107 throw new ArgeoJcrException("Query returned more than one node.");
111 /** Retrieves the node name from the provided path */
112 public static String
nodeNameFromPath(String path
) {
113 if (path
.equals("/"))
115 if (path
.charAt(0) != '/')
116 throw new ArgeoJcrException("Path " + path
+ " must start with a '/'");
118 if (pathT
.charAt(pathT
.length() - 1) == '/')
119 pathT
= pathT
.substring(0, pathT
.length() - 2);
121 int index
= pathT
.lastIndexOf('/');
122 return pathT
.substring(index
+ 1);
125 /** Retrieves the parent path of the provided path */
126 public static String
parentPath(String path
) {
127 if (path
.equals("/"))
128 throw new ArgeoJcrException("Root path '/' has no parent path");
129 if (path
.charAt(0) != '/')
130 throw new ArgeoJcrException("Path " + path
+ " must start with a '/'");
132 if (pathT
.charAt(pathT
.length() - 1) == '/')
133 pathT
= pathT
.substring(0, pathT
.length() - 2);
135 int index
= pathT
.lastIndexOf('/');
136 return pathT
.substring(0, index
);
139 /** The provided data as a path ('/' at the end, not the beginning) */
140 public static String
dateAsPath(Calendar cal
) {
141 return dateAsPath(cal
, false);
145 * Creates a deep path based on a URL:
146 * http://subdomain.example.com/to/content?args becomes
147 * com/example/subdomain/to/content
149 public static String
urlAsPath(String url
) {
151 URL u
= new URL(url
);
152 StringBuffer path
= new StringBuffer(url
.length());
154 path
.append(hostAsPath(u
.getHost()));
155 // we don't put port since it may not always be there and may change
156 path
.append(u
.getPath());
157 return path
.toString();
158 } catch (MalformedURLException e
) {
159 throw new ArgeoJcrException("Cannot generate URL path for " + url
, e
);
163 /** Set the {@link NodeType#NT_ADDRESS} properties based on this URL. */
164 public static void urlToAddressProperties(Node node
, String url
) {
166 URL u
= new URL(url
);
167 node
.setProperty(Property
.JCR_PROTOCOL
, u
.getProtocol());
168 node
.setProperty(Property
.JCR_HOST
, u
.getHost());
169 node
.setProperty(Property
.JCR_PORT
, Integer
.toString(u
.getPort()));
170 node
.setProperty(Property
.JCR_PATH
, normalizePath(u
.getPath()));
171 } catch (Exception e
) {
172 throw new ArgeoJcrException("Cannot set URL " + url
+ " as nt:address properties", e
);
176 /** Build URL based on the {@link NodeType#NT_ADDRESS} properties. */
177 public static String
urlFromAddressProperties(Node node
) {
179 URL u
= new URL(node
.getProperty(Property
.JCR_PROTOCOL
).getString(),
180 node
.getProperty(Property
.JCR_HOST
).getString(),
181 (int) node
.getProperty(Property
.JCR_PORT
).getLong(),
182 node
.getProperty(Property
.JCR_PATH
).getString());
184 } catch (Exception e
) {
185 throw new ArgeoJcrException("Cannot get URL from nt:address properties of " + node
, e
);
194 * Make sure that: starts with '/', do not end with '/', do not have '//'
196 public static String
normalizePath(String path
) {
197 List
<String
> tokens
= tokenize(path
);
198 StringBuffer buf
= new StringBuffer(path
.length());
199 for (String token
: tokens
) {
203 return buf
.toString();
207 * Creates a path from a FQDN, inverting the order of the component:
208 * www.argeo.org becomes org.argeo.www
210 public static String
hostAsPath(String host
) {
211 StringBuffer path
= new StringBuffer(host
.length());
212 String
[] hostTokens
= host
.split("\\.");
213 for (int i
= hostTokens
.length
- 1; i
>= 0; i
--) {
214 path
.append(hostTokens
[i
]);
218 return path
.toString();
222 * Creates a path from a UUID (e.g. 6ebda899-217d-4bf1-abe4-2839085c8f3c becomes
223 * 6ebda899-217d/4bf1/abe4/2839085c8f3c/). '/' at the end, not the beginning
225 public static String
uuidAsPath(String uuid
) {
226 StringBuffer path
= new StringBuffer(uuid
.length());
227 String
[] tokens
= uuid
.split("-");
228 for (int i
= 0; i
< tokens
.length
; i
++) {
229 path
.append(tokens
[i
]);
233 return path
.toString();
237 * The provided data as a path ('/' at the end, not the beginning)
242 * whether to add hour as well
244 public static String
dateAsPath(Calendar cal
, Boolean addHour
) {
245 StringBuffer buf
= new StringBuffer(14);
247 buf
.append(cal
.get(Calendar
.YEAR
));
250 int month
= cal
.get(Calendar
.MONTH
) + 1;
257 int day
= cal
.get(Calendar
.DAY_OF_MONTH
);
265 int hour
= cal
.get(Calendar
.HOUR_OF_DAY
);
272 return buf
.toString();
276 /** Converts in one call a string into a gregorian calendar. */
277 public static Calendar
parseCalendar(DateFormat dateFormat
, String value
) {
279 Date date
= dateFormat
.parse(value
);
280 Calendar calendar
= new GregorianCalendar();
281 calendar
.setTime(date
);
283 } catch (ParseException e
) {
284 throw new ArgeoJcrException("Cannot parse " + value
+ " with date format " + dateFormat
, e
);
289 /** The last element of a path. */
290 public static String
lastPathElement(String path
) {
291 if (path
.charAt(path
.length() - 1) == '/')
292 throw new ArgeoJcrException("Path " + path
+ " cannot end with '/'");
293 int index
= path
.lastIndexOf('/');
296 return path
.substring(index
+ 1);
300 * Call {@link Node#getName()} without exceptions (useful in super
303 public static String
getNameQuietly(Node node
) {
305 return node
.getName();
306 } catch (RepositoryException e
) {
307 throw new ArgeoJcrException("Cannot get name from " + node
, e
);
312 * Call {@link Node#getProperty(String)} without exceptions (useful in super
315 public static String
getStringPropertyQuietly(Node node
, String propertyName
) {
317 return node
.getProperty(propertyName
).getString();
318 } catch (RepositoryException e
) {
319 throw new ArgeoJcrException("Cannot get name from " + node
, e
);
324 * Routine that get the child with this name, adding id it does not already
327 public static Node
getOrAdd(Node parent
, String childName
, String childPrimaryNodeType
) throws RepositoryException
{
328 return parent
.hasNode(childName
) ? parent
.getNode(childName
) : parent
.addNode(childName
, childPrimaryNodeType
);
332 * Routine that get the child with this name, adding id it does not already
335 public static Node
getOrAdd(Node parent
, String childName
) throws RepositoryException
{
336 return parent
.hasNode(childName
) ? parent
.getNode(childName
) : parent
.addNode(childName
);
339 /** Convert a {@link NodeIterator} to a list of {@link Node} */
340 public static List
<Node
> nodeIteratorToList(NodeIterator nodeIterator
) {
341 List
<Node
> nodes
= new ArrayList
<Node
>();
342 while (nodeIterator
.hasNext()) {
343 nodes
.add(nodeIterator
.nextNode());
353 * Concisely get the string value of a property or null if this node doesn't
356 public static String
get(Node node
, String propertyName
) {
358 if (!node
.hasProperty(propertyName
))
360 return node
.getProperty(propertyName
).getString();
361 } catch (RepositoryException e
) {
362 throw new ArgeoJcrException("Cannot get property " + propertyName
+ " of " + node
, e
);
366 /** Concisely get the boolean value of a property */
367 public static Boolean
check(Node node
, String propertyName
) {
369 return node
.getProperty(propertyName
).getBoolean();
370 } catch (RepositoryException e
) {
371 throw new ArgeoJcrException("Cannot get property " + propertyName
+ " of " + node
, e
);
375 /** Concisely get the bytes array value of a property */
376 public static byte[] getBytes(Node node
, String propertyName
) {
378 return getBinaryAsBytes(node
.getProperty(propertyName
));
379 } catch (RepositoryException e
) {
380 throw new ArgeoJcrException("Cannot get property " + propertyName
+ " of " + node
, e
);
389 * Create sub nodes relative to a parent node
391 public static Node
mkdirs(Node parentNode
, String relativePath
) {
392 return mkdirs(parentNode
, relativePath
, null, null);
396 * Create sub nodes relative to a parent node
399 * the type of the leaf node
401 public static Node
mkdirs(Node parentNode
, String relativePath
, String nodeType
) {
402 return mkdirs(parentNode
, relativePath
, nodeType
, null);
406 * Create sub nodes relative to a parent node
409 * the type of the leaf node
411 public static Node
mkdirs(Node parentNode
, String relativePath
, String nodeType
, String intermediaryNodeType
) {
412 List
<String
> tokens
= tokenize(relativePath
);
413 Node currParent
= parentNode
;
415 for (int i
= 0; i
< tokens
.size(); i
++) {
416 String name
= tokens
.get(i
);
417 if (currParent
.hasNode(name
)) {
418 currParent
= currParent
.getNode(name
);
420 if (i
!= (tokens
.size() - 1)) {// intermediary
421 currParent
= currParent
.addNode(name
, intermediaryNodeType
);
423 currParent
= currParent
.addNode(name
, nodeType
);
428 } catch (RepositoryException e
) {
429 throw new ArgeoJcrException("Cannot mkdirs relative path " + relativePath
+ " from " + parentNode
, e
);
434 * Synchronized and save is performed, to avoid race conditions in initializers
435 * leading to duplicate nodes.
437 public synchronized static Node
mkdirsSafe(Session session
, String path
, String type
) {
439 if (session
.hasPendingChanges())
440 throw new ArgeoJcrException("Session has pending changes, save them first.");
441 Node node
= mkdirs(session
, path
, type
);
444 } catch (RepositoryException e
) {
445 discardQuietly(session
);
446 throw new ArgeoJcrException("Cannot safely make directories", e
);
450 public synchronized static Node
mkdirsSafe(Session session
, String path
) {
451 return mkdirsSafe(session
, path
, null);
454 /** Creates the nodes making path, if they don't exist. */
455 public static Node
mkdirs(Session session
, String path
) {
456 return mkdirs(session
, path
, null, null, false);
461 * the type of the leaf node
463 public static Node
mkdirs(Session session
, String path
, String type
) {
464 return mkdirs(session
, path
, type
, null, false);
468 * Creates the nodes making path, if they don't exist. This is up to the caller
469 * to save the session. Use with caution since it can create duplicate nodes if
470 * used concurrently. Requires read access to the root node of the workspace.
472 public static Node
mkdirs(Session session
, String path
, String type
, String intermediaryNodeType
,
473 Boolean versioning
) {
475 if (path
.equals("/"))
476 return session
.getRootNode();
478 if (session
.itemExists(path
)) {
479 Node node
= session
.getNode(path
);
481 if (type
!= null && !node
.isNodeType(type
) && !node
.getPath().equals("/"))
482 throw new ArgeoJcrException("Node " + node
+ " exists but is of type "
483 + node
.getPrimaryNodeType().getName() + " not of type " + type
);
484 // TODO: check versioning
488 // StringBuffer current = new StringBuffer("/");
489 // Node currentNode = session.getRootNode();
491 Node currentNode
= findClosestExistingParent(session
, path
);
492 String closestExistingParentPath
= currentNode
.getPath();
493 StringBuffer current
= new StringBuffer(closestExistingParentPath
);
494 if (!closestExistingParentPath
.endsWith("/"))
496 Iterator
<String
> it
= tokenize(path
.substring(closestExistingParentPath
.length())).iterator();
497 while (it
.hasNext()) {
498 String part
= it
.next();
499 current
.append(part
).append('/');
500 if (!session
.itemExists(current
.toString())) {
501 if (!it
.hasNext() && type
!= null)
502 currentNode
= currentNode
.addNode(part
, type
);
503 else if (it
.hasNext() && intermediaryNodeType
!= null)
504 currentNode
= currentNode
.addNode(part
, intermediaryNodeType
);
506 currentNode
= currentNode
.addNode(part
);
508 currentNode
.addMixin(NodeType
.MIX_VERSIONABLE
);
509 if (log
.isTraceEnabled())
510 log
.debug("Added folder " + part
+ " as " + current
);
512 currentNode
= (Node
) session
.getItem(current
.toString());
516 } catch (RepositoryException e
) {
517 discardQuietly(session
);
518 throw new ArgeoJcrException("Cannot mkdirs " + path
, e
);
523 private static Node
findClosestExistingParent(Session session
, String path
) throws RepositoryException
{
524 int idx
= path
.lastIndexOf('/');
526 return session
.getRootNode();
527 String parentPath
= path
.substring(0, idx
);
528 if (session
.itemExists(parentPath
))
529 return session
.getNode(parentPath
);
531 return findClosestExistingParent(session
, parentPath
);
534 /** Convert a path to the list of its tokens */
535 public static List
<String
> tokenize(String path
) {
536 List
<String
> tokens
= new ArrayList
<String
>();
537 boolean optimized
= false;
539 String
[] rawTokens
= path
.split("/");
540 for (String token
: rawTokens
) {
541 if (!token
.equals(""))
545 StringBuffer curr
= new StringBuffer();
546 char[] arr
= path
.toCharArray();
547 chars
: for (int i
= 0; i
< arr
.length
; i
++) {
550 if (i
== 0 || (i
== arr
.length
- 1))
552 if (curr
.length() > 0) {
553 tokens
.add(curr
.toString());
554 curr
= new StringBuffer();
559 if (curr
.length() > 0) {
560 tokens
.add(curr
.toString());
561 curr
= new StringBuffer();
564 return Collections
.unmodifiableList(tokens
);
568 // * use {@link #mkdirs(Session, String, String, String, Boolean)} instead.
573 // public static Node mkdirs(Session session, String path, String type,
574 // Boolean versioning) {
575 // return mkdirs(session, path, type, type, false);
579 * Safe and repository implementation independent registration of a namespace.
581 public static void registerNamespaceSafely(Session session
, String prefix
, String uri
) {
583 registerNamespaceSafely(session
.getWorkspace().getNamespaceRegistry(), prefix
, uri
);
584 } catch (RepositoryException e
) {
585 throw new ArgeoJcrException("Cannot find namespace registry", e
);
590 * Safe and repository implementation independent registration of a namespace.
592 public static void registerNamespaceSafely(NamespaceRegistry nr
, String prefix
, String uri
) {
594 String
[] prefixes
= nr
.getPrefixes();
595 for (String pref
: prefixes
)
596 if (pref
.equals(prefix
)) {
597 String registeredUri
= nr
.getURI(pref
);
598 if (!registeredUri
.equals(uri
))
599 throw new ArgeoJcrException("Prefix " + pref
+ " already registered for URI " + registeredUri
600 + " which is different from provided URI " + uri
);
604 nr
.registerNamespace(prefix
, uri
);
605 } catch (RepositoryException e
) {
606 throw new ArgeoJcrException("Cannot register namespace " + uri
+ " under prefix " + prefix
, e
);
610 /** Recursively outputs the contents of the given node. */
611 public static void debug(Node node
) {
615 /** Recursively outputs the contents of the given node. */
616 public static void debug(Node node
, Log log
) {
618 // First output the node path
619 log
.debug(node
.getPath());
620 // Skip the virtual (and large!) jcr:system subtree
621 if (node
.getName().equals("jcr:system")) {
625 // Then the children nodes (recursive)
626 NodeIterator it
= node
.getNodes();
627 while (it
.hasNext()) {
628 Node childNode
= it
.nextNode();
629 debug(childNode
, log
);
632 // Then output the properties
633 PropertyIterator properties
= node
.getProperties();
634 // log.debug("Property are : ");
636 properties
: while (properties
.hasNext()) {
637 Property property
= properties
.nextProperty();
638 if (property
.getType() == PropertyType
.BINARY
)
639 continue properties
;// skip
640 if (property
.getDefinition().isMultiple()) {
641 // A multi-valued property, print all values
642 Value
[] values
= property
.getValues();
643 for (int i
= 0; i
< values
.length
; i
++) {
644 log
.debug(property
.getPath() + "=" + values
[i
].getString());
647 // A single-valued property
648 log
.debug(property
.getPath() + "=" + property
.getString());
651 } catch (Exception e
) {
652 log
.error("Could not debug " + node
, e
);
657 /** Logs the effective access control policies */
658 public static void logEffectiveAccessPolicies(Node node
) {
660 logEffectiveAccessPolicies(node
.getSession(), node
.getPath());
661 } catch (RepositoryException e
) {
662 log
.error("Cannot log effective access policies of " + node
, e
);
666 /** Logs the effective access control policies */
667 public static void logEffectiveAccessPolicies(Session session
, String path
) {
668 if (!log
.isDebugEnabled())
672 AccessControlPolicy
[] effectivePolicies
= session
.getAccessControlManager().getEffectivePolicies(path
);
673 if (effectivePolicies
.length
> 0) {
674 for (AccessControlPolicy policy
: effectivePolicies
) {
675 if (policy
instanceof AccessControlList
) {
676 AccessControlList acl
= (AccessControlList
) policy
;
677 log
.debug("Access control list for " + path
+ "\n" + accessControlListSummary(acl
));
681 log
.debug("No effective access control policy for " + path
);
683 } catch (RepositoryException e
) {
684 log
.error("Cannot log effective access policies of " + path
, e
);
688 /** Returns a human-readable summary of this access control list. */
689 public static String
accessControlListSummary(AccessControlList acl
) {
690 StringBuffer buf
= new StringBuffer("");
692 for (AccessControlEntry ace
: acl
.getAccessControlEntries()) {
693 buf
.append('\t').append(ace
.getPrincipal().getName()).append('\n');
694 for (Privilege priv
: ace
.getPrivileges())
695 buf
.append("\t\t").append(priv
.getName()).append('\n');
697 return buf
.toString();
698 } catch (RepositoryException e
) {
699 throw new ArgeoJcrException("Cannot write summary of " + acl
, e
);
704 * Copies recursively the content of a node to another one. Do NOT copy the
705 * property values of {@link NodeType#MIX_CREATED} and
706 * {@link NodeType#MIX_LAST_MODIFIED}, but update the
707 * {@link Property#JCR_LAST_MODIFIED} and {@link Property#JCR_LAST_MODIFIED_BY}
708 * properties if the target node has the {@link NodeType#MIX_LAST_MODIFIED}
711 public static void copy(Node fromNode
, Node toNode
) {
713 if (toNode
.getDefinition().isProtected())
716 // process properties
717 PropertyIterator pit
= fromNode
.getProperties();
718 properties
: while (pit
.hasNext()) {
719 Property fromProperty
= pit
.nextProperty();
720 String propertyName
= fromProperty
.getName();
721 if (toNode
.hasProperty(propertyName
) && toNode
.getProperty(propertyName
).getDefinition().isProtected())
724 if (fromProperty
.getDefinition().isProtected())
727 if (propertyName
.equals("jcr:created") || propertyName
.equals("jcr:createdBy")
728 || propertyName
.equals("jcr:lastModified") || propertyName
.equals("jcr:lastModifiedBy"))
731 if (fromProperty
.isMultiple()) {
732 toNode
.setProperty(propertyName
, fromProperty
.getValues());
734 toNode
.setProperty(propertyName
, fromProperty
.getValue());
738 // update jcr:lastModified and jcr:lastModifiedBy in toNode in case
739 // they existed, before adding the mixins
740 updateLastModified(toNode
);
743 for (NodeType mixinType
: fromNode
.getMixinNodeTypes()) {
744 toNode
.addMixin(mixinType
.getName());
747 // process children nodes
748 NodeIterator nit
= fromNode
.getNodes();
749 while (nit
.hasNext()) {
750 Node fromChild
= nit
.nextNode();
751 Integer index
= fromChild
.getIndex();
752 String nodeRelPath
= fromChild
.getName() + "[" + index
+ "]";
754 if (toNode
.hasNode(nodeRelPath
))
755 toChild
= toNode
.getNode(nodeRelPath
);
757 toChild
= toNode
.addNode(fromChild
.getName(), fromChild
.getPrimaryNodeType().getName());
758 copy(fromChild
, toChild
);
760 } catch (RepositoryException e
) {
761 throw new ArgeoJcrException("Cannot copy " + fromNode
+ " to " + toNode
, e
);
766 * Check whether all first-level properties (except jcr:* properties) are equal.
767 * Skip jcr:* properties
769 public static Boolean
allPropertiesEquals(Node reference
, Node observed
, Boolean onlyCommonProperties
) {
771 PropertyIterator pit
= reference
.getProperties();
772 props
: while (pit
.hasNext()) {
773 Property propReference
= pit
.nextProperty();
774 String propName
= propReference
.getName();
775 if (propName
.startsWith("jcr:"))
778 if (!observed
.hasProperty(propName
))
779 if (onlyCommonProperties
)
783 // TODO: deal with multiple property values?
784 if (!observed
.getProperty(propName
).getValue().equals(propReference
.getValue()))
788 } catch (RepositoryException e
) {
789 throw new ArgeoJcrException("Cannot check all properties equals of " + reference
+ " and " + observed
, e
);
793 public static Map
<String
, PropertyDiff
> diffProperties(Node reference
, Node observed
) {
794 Map
<String
, PropertyDiff
> diffs
= new TreeMap
<String
, PropertyDiff
>();
795 diffPropertiesLevel(diffs
, null, reference
, observed
);
800 * Compare the properties of two nodes. Recursivity to child nodes is not yet
801 * supported. Skip jcr:* properties.
803 static void diffPropertiesLevel(Map
<String
, PropertyDiff
> diffs
, String baseRelPath
, Node reference
,
806 // check removed and modified
807 PropertyIterator pit
= reference
.getProperties();
808 props
: while (pit
.hasNext()) {
809 Property p
= pit
.nextProperty();
810 String name
= p
.getName();
811 if (name
.startsWith("jcr:"))
814 if (!observed
.hasProperty(name
)) {
815 String relPath
= propertyRelPath(baseRelPath
, name
);
816 PropertyDiff pDiff
= new PropertyDiff(PropertyDiff
.REMOVED
, relPath
, p
.getValue(), null);
817 diffs
.put(relPath
, pDiff
);
819 if (p
.isMultiple()) {
820 // FIXME implement multiple
822 Value referenceValue
= p
.getValue();
823 Value newValue
= observed
.getProperty(name
).getValue();
824 if (!referenceValue
.equals(newValue
)) {
825 String relPath
= propertyRelPath(baseRelPath
, name
);
826 PropertyDiff pDiff
= new PropertyDiff(PropertyDiff
.MODIFIED
, relPath
, referenceValue
,
828 diffs
.put(relPath
, pDiff
);
834 pit
= observed
.getProperties();
835 props
: while (pit
.hasNext()) {
836 Property p
= pit
.nextProperty();
837 String name
= p
.getName();
838 if (name
.startsWith("jcr:"))
840 if (!reference
.hasProperty(name
)) {
841 if (p
.isMultiple()) {
842 // FIXME implement multiple
844 String relPath
= propertyRelPath(baseRelPath
, name
);
845 PropertyDiff pDiff
= new PropertyDiff(PropertyDiff
.ADDED
, relPath
, null, p
.getValue());
846 diffs
.put(relPath
, pDiff
);
850 } catch (RepositoryException e
) {
851 throw new ArgeoJcrException("Cannot diff " + reference
+ " and " + observed
, e
);
856 * Compare only a restricted list of properties of two nodes. No recursivity.
859 public static Map
<String
, PropertyDiff
> diffProperties(Node reference
, Node observed
, List
<String
> properties
) {
860 Map
<String
, PropertyDiff
> diffs
= new TreeMap
<String
, PropertyDiff
>();
862 Iterator
<String
> pit
= properties
.iterator();
864 props
: while (pit
.hasNext()) {
865 String name
= pit
.next();
866 if (!reference
.hasProperty(name
)) {
867 if (!observed
.hasProperty(name
))
869 Value val
= observed
.getProperty(name
).getValue();
871 // empty String but not null
872 if ("".equals(val
.getString()))
874 } catch (Exception e
) {
875 // not parseable as String, silent
877 PropertyDiff pDiff
= new PropertyDiff(PropertyDiff
.ADDED
, name
, null, val
);
878 diffs
.put(name
, pDiff
);
879 } else if (!observed
.hasProperty(name
)) {
880 PropertyDiff pDiff
= new PropertyDiff(PropertyDiff
.REMOVED
, name
,
881 reference
.getProperty(name
).getValue(), null);
882 diffs
.put(name
, pDiff
);
884 Value referenceValue
= reference
.getProperty(name
).getValue();
885 Value newValue
= observed
.getProperty(name
).getValue();
886 if (!referenceValue
.equals(newValue
)) {
887 PropertyDiff pDiff
= new PropertyDiff(PropertyDiff
.MODIFIED
, name
, referenceValue
, newValue
);
888 diffs
.put(name
, pDiff
);
892 } catch (RepositoryException e
) {
893 throw new ArgeoJcrException("Cannot diff " + reference
+ " and " + observed
, e
);
898 /** Builds a property relPath to be used in the diff. */
899 private static String
propertyRelPath(String baseRelPath
, String propertyName
) {
900 if (baseRelPath
== null)
903 return baseRelPath
+ '/' + propertyName
;
907 * Normalizes a name so that it can be stored in contexts not supporting names
908 * with ':' (typically databases). Replaces ':' by '_'.
910 public static String
normalize(String name
) {
911 return name
.replace(':', '_');
915 * Replaces characters which are invalid in a JCR name by '_'. Currently not
918 * @see JcrUtils#INVALID_NAME_CHARACTERS
920 public static String
replaceInvalidChars(String name
) {
921 return replaceInvalidChars(name
, '_');
925 * Replaces characters which are invalid in a JCR name. Currently not
928 * @see JcrUtils#INVALID_NAME_CHARACTERS
930 public static String
replaceInvalidChars(String name
, char replacement
) {
931 boolean modified
= false;
932 char[] arr
= name
.toCharArray();
933 for (int i
= 0; i
< arr
.length
; i
++) {
935 invalid
: for (char invalid
: INVALID_NAME_CHARACTERS
) {
937 arr
[i
] = replacement
;
944 return new String(arr
);
946 // do not create new object if unnecessary
951 // * Removes forbidden characters from a path, replacing them with '_'
953 // * @deprecated use {@link #replaceInvalidChars(String)} instead
955 // public static String removeForbiddenCharacters(String str) {
956 // return str.replace('[', '_').replace(']', '_').replace('/', '_').replace('*',
961 /** Cleanly disposes a {@link Binary} even if it is null. */
962 public static void closeQuietly(Binary binary
) {
968 /** Retrieve a {@link Binary} as a byte array */
969 public static byte[] getBinaryAsBytes(Property property
) {
970 // ByteArrayOutputStream out = new ByteArrayOutputStream();
971 // InputStream in = null;
972 // Binary binary = null;
973 try (ByteArrayOutputStream out
= new ByteArrayOutputStream();
974 Bin binary
= new Bin(property
);
975 InputStream in
= binary
.getStream()) {
976 // binary = property.getBinary();
977 // in = binary.getStream();
978 IOUtils
.copy(in
, out
);
979 return out
.toByteArray();
980 } catch (Exception e
) {
981 throw new ArgeoJcrException("Cannot read binary " + property
+ " as bytes", e
);
983 // IOUtils.closeQuietly(out);
984 // IOUtils.closeQuietly(in);
985 // closeQuietly(binary);
989 /** Writes a {@link Binary} from a byte array */
990 public static void setBinaryAsBytes(Node node
, String property
, byte[] bytes
) {
991 // InputStream in = null;
992 Binary binary
= null;
993 try (InputStream in
= new ByteArrayInputStream(bytes
)) {
994 // in = new ByteArrayInputStream(bytes);
995 binary
= node
.getSession().getValueFactory().createBinary(in
);
996 node
.setProperty(property
, binary
);
997 } catch (Exception e
) {
998 throw new ArgeoJcrException("Cannot read binary " + property
+ " as bytes", e
);
1000 // IOUtils.closeQuietly(in);
1001 closeQuietly(binary
);
1006 * Creates depth from a string (typically a username) by adding levels based on
1007 * its first characters: "aBcD",2 becomes a/aB
1009 public static String
firstCharsToPath(String str
, Integer nbrOfChars
) {
1010 if (str
.length() < nbrOfChars
)
1011 throw new ArgeoJcrException("String " + str
+ " length must be greater or equal than " + nbrOfChars
);
1012 StringBuffer path
= new StringBuffer("");
1013 StringBuffer curr
= new StringBuffer("");
1014 for (int i
= 0; i
< nbrOfChars
; i
++) {
1015 curr
.append(str
.charAt(i
));
1017 if (i
< nbrOfChars
- 1)
1020 return path
.toString();
1024 * Discards the current changes in the session attached to this node. To be used
1025 * typically in a catch block.
1027 * @see #discardQuietly(Session)
1029 public static void discardUnderlyingSessionQuietly(Node node
) {
1031 discardQuietly(node
.getSession());
1032 } catch (RepositoryException e
) {
1033 log
.warn("Cannot quietly discard session of node " + node
+ ": " + e
.getMessage());
1038 * Discards the current changes in a session by calling
1039 * {@link Session#refresh(boolean)} with <code>false</code>, only logging
1040 * potential errors when doing so. To be used typically in a catch block.
1042 public static void discardQuietly(Session session
) {
1044 if (session
!= null)
1045 session
.refresh(false);
1046 } catch (RepositoryException e
) {
1047 log
.warn("Cannot quietly discard session " + session
+ ": " + e
.getMessage());
1052 * Login to a workspace with implicit credentials, creates the workspace with
1053 * these credentials if it does not already exist.
1055 public static Session
loginOrCreateWorkspace(Repository repository
, String workspaceName
)
1056 throws RepositoryException
{
1057 Session workspaceSession
= null;
1058 Session defaultSession
= null;
1061 workspaceSession
= repository
.login(workspaceName
);
1062 } catch (NoSuchWorkspaceException e
) {
1063 // try to create workspace
1064 defaultSession
= repository
.login();
1065 defaultSession
.getWorkspace().createWorkspace(workspaceName
);
1066 workspaceSession
= repository
.login(workspaceName
);
1068 return workspaceSession
;
1070 logoutQuietly(defaultSession
);
1074 /** Logs out the session, not throwing any exception, even if it is null. */
1075 public static void logoutQuietly(Session session
) {
1077 if (session
!= null)
1078 if (session
.isLive())
1080 } catch (Exception e
) {
1086 * Convenient method to add a listener. uuids passed as null, deep=true,
1087 * local=true, only one node type
1089 public static void addListener(Session session
, EventListener listener
, int eventTypes
, String basePath
,
1092 session
.getWorkspace().getObservationManager().addEventListener(listener
, eventTypes
, basePath
, true, null,
1093 nodeType
== null ?
null : new String
[] { nodeType
}, true);
1094 } catch (RepositoryException e
) {
1095 throw new ArgeoJcrException("Cannot add JCR listener " + listener
+ " to session " + session
, e
);
1099 /** Removes a listener without throwing exception */
1100 public static void removeListenerQuietly(Session session
, EventListener listener
) {
1101 if (session
== null || !session
.isLive())
1104 session
.getWorkspace().getObservationManager().removeEventListener(listener
);
1105 } catch (RepositoryException e
) {
1111 * Quietly unregisters an {@link EventListener} from the udnerlying workspace of
1114 public static void unregisterQuietly(Node node
, EventListener eventListener
) {
1116 unregisterQuietly(node
.getSession().getWorkspace(), eventListener
);
1117 } catch (RepositoryException e
) {
1119 if (log
.isTraceEnabled())
1120 log
.trace("Could not unregister event listener " + eventListener
);
1124 /** Quietly unregisters an {@link EventListener} from this workspace */
1125 public static void unregisterQuietly(Workspace workspace
, EventListener eventListener
) {
1126 if (eventListener
== null)
1129 workspace
.getObservationManager().removeEventListener(eventListener
);
1130 } catch (RepositoryException e
) {
1132 if (log
.isTraceEnabled())
1133 log
.trace("Could not unregister event listener " + eventListener
);
1138 * If this node is has the {@link NodeType#MIX_LAST_MODIFIED} mixin, it updates
1139 * the {@link Property#JCR_LAST_MODIFIED} property with the current time and the
1140 * {@link Property#JCR_LAST_MODIFIED_BY} property with the underlying session
1141 * user id. In Jackrabbit 2.x,
1142 * <a href="https://issues.apache.org/jira/browse/JCR-2233">these properties are
1143 * not automatically updated</a>, hence the need for manual update. The session
1146 public static void updateLastModified(Node node
) {
1148 if (!node
.isNodeType(NodeType
.MIX_LAST_MODIFIED
))
1149 node
.addMixin(NodeType
.MIX_LAST_MODIFIED
);
1150 node
.setProperty(Property
.JCR_LAST_MODIFIED
, new GregorianCalendar());
1151 node
.setProperty(Property
.JCR_LAST_MODIFIED_BY
, node
.getSession().getUserID());
1152 } catch (RepositoryException e
) {
1153 throw new ArgeoJcrException("Cannot update last modified on " + node
, e
);
1158 * Update lastModified recursively until this parent.
1163 * the base path, null is equivalent to "/"
1165 public static void updateLastModifiedAndParents(Node node
, String untilPath
) {
1167 if (untilPath
!= null && !node
.getPath().startsWith(untilPath
))
1168 throw new ArgeoJcrException(node
+ " is not under " + untilPath
);
1169 updateLastModified(node
);
1170 if (untilPath
== null) {
1171 if (!node
.getPath().equals("/"))
1172 updateLastModifiedAndParents(node
.getParent(), untilPath
);
1174 if (!node
.getPath().equals(untilPath
))
1175 updateLastModifiedAndParents(node
.getParent(), untilPath
);
1177 } catch (RepositoryException e
) {
1178 throw new ArgeoJcrException("Cannot update lastModified from " + node
+ " until " + untilPath
, e
);
1183 * Returns a String representing the short version (see
1184 * <a href="http://jackrabbit.apache.org/node-type-notation.html"> Node type
1185 * Notation </a> attributes grammar) of the main business attributes of this
1186 * property definition
1190 public static String
getPropertyDefinitionAsString(Property prop
) {
1191 StringBuffer sbuf
= new StringBuffer();
1193 if (prop
.getDefinition().isAutoCreated())
1195 if (prop
.getDefinition().isMandatory())
1197 if (prop
.getDefinition().isProtected())
1199 if (prop
.getDefinition().isMultiple())
1201 } catch (RepositoryException re
) {
1202 throw new ArgeoJcrException("unexpected error while getting property definition as String", re
);
1204 return sbuf
.toString();
1208 * Estimate the sub tree size from current node. Computation is based on the Jcr
1209 * {@link Property#getLength()} method. Note : it is not the exact size used on
1210 * the disk by the current part of the JCR Tree.
1213 public static long getNodeApproxSize(Node node
) {
1214 long curNodeSize
= 0;
1216 PropertyIterator pi
= node
.getProperties();
1217 while (pi
.hasNext()) {
1218 Property prop
= pi
.nextProperty();
1219 if (prop
.isMultiple()) {
1220 int nb
= prop
.getLengths().length
;
1221 for (int i
= 0; i
< nb
; i
++) {
1222 curNodeSize
+= (prop
.getLengths()[i
] > 0 ? prop
.getLengths()[i
] : 0);
1225 curNodeSize
+= (prop
.getLength() > 0 ? prop
.getLength() : 0);
1228 NodeIterator ni
= node
.getNodes();
1229 while (ni
.hasNext())
1230 curNodeSize
+= getNodeApproxSize(ni
.nextNode());
1232 } catch (RepositoryException re
) {
1233 throw new ArgeoJcrException("Unexpected error while recursively determining node size.", re
);
1242 * Convenience method for adding a single privilege to a principal (user or
1243 * role), typically jcr:all
1245 public synchronized static void addPrivilege(Session session
, String path
, String principal
, String privilege
)
1246 throws RepositoryException
{
1247 List
<Privilege
> privileges
= new ArrayList
<Privilege
>();
1248 privileges
.add(session
.getAccessControlManager().privilegeFromName(privilege
));
1249 addPrivileges(session
, path
, new SimplePrincipal(principal
), privileges
);
1253 * Add privileges on a path to a {@link Principal}. The path must already exist.
1254 * Session is saved. Synchronized to prevent concurrent modifications of the
1257 public synchronized static Boolean
addPrivileges(Session session
, String path
, Principal principal
,
1258 List
<Privilege
> privs
) throws RepositoryException
{
1259 // make sure the session is in line with the persisted state
1260 session
.refresh(false);
1261 AccessControlManager acm
= session
.getAccessControlManager();
1262 AccessControlList acl
= getAccessControlList(acm
, path
);
1264 accessControlEntries
: for (AccessControlEntry ace
: acl
.getAccessControlEntries()) {
1265 Principal currentPrincipal
= ace
.getPrincipal();
1266 if (currentPrincipal
.getName().equals(principal
.getName())) {
1267 Privilege
[] currentPrivileges
= ace
.getPrivileges();
1268 if (currentPrivileges
.length
!= privs
.size())
1269 break accessControlEntries
;
1270 for (int i
= 0; i
< currentPrivileges
.length
; i
++) {
1271 Privilege currP
= currentPrivileges
[i
];
1272 Privilege p
= privs
.get(i
);
1273 if (!currP
.getName().equals(p
.getName())) {
1274 break accessControlEntries
;
1281 Privilege
[] privileges
= privs
.toArray(new Privilege
[privs
.size()]);
1282 acl
.addAccessControlEntry(principal
, privileges
);
1283 acm
.setPolicy(path
, acl
);
1284 if (log
.isDebugEnabled()) {
1285 StringBuffer privBuf
= new StringBuffer();
1286 for (Privilege priv
: privs
)
1287 privBuf
.append(priv
.getName());
1288 log
.debug("Added privileges " + privBuf
+ " to " + principal
.getName() + " on " + path
+ " in '"
1289 + session
.getWorkspace().getName() + "'");
1291 session
.refresh(true);
1296 /** Gets access control list for this path, throws exception if not found */
1297 public synchronized static AccessControlList
getAccessControlList(AccessControlManager acm
, String path
)
1298 throws RepositoryException
{
1299 // search for an access control list
1300 AccessControlList acl
= null;
1301 AccessControlPolicyIterator policyIterator
= acm
.getApplicablePolicies(path
);
1302 if (policyIterator
.hasNext()) {
1303 while (policyIterator
.hasNext()) {
1304 AccessControlPolicy acp
= policyIterator
.nextAccessControlPolicy();
1305 if (acp
instanceof AccessControlList
)
1306 acl
= ((AccessControlList
) acp
);
1309 AccessControlPolicy
[] existingPolicies
= acm
.getPolicies(path
);
1310 for (AccessControlPolicy acp
: existingPolicies
) {
1311 if (acp
instanceof AccessControlList
)
1312 acl
= ((AccessControlList
) acp
);
1318 throw new ArgeoJcrException("ACL not found at " + path
);
1321 /** Clear authorizations for a user at this path */
1322 public synchronized static void clearAccessControList(Session session
, String path
, String username
)
1323 throws RepositoryException
{
1324 AccessControlManager acm
= session
.getAccessControlManager();
1325 AccessControlList acl
= getAccessControlList(acm
, path
);
1326 for (AccessControlEntry ace
: acl
.getAccessControlEntries()) {
1327 if (ace
.getPrincipal().getName().equals(username
)) {
1328 acl
.removeAccessControlEntry(ace
);
1331 // the new access control list must be applied otherwise this call:
1332 // acl.removeAccessControlEntry(ace); has no effect
1333 acm
.setPolicy(path
, acl
);
1340 * Creates the nodes making the path as {@link NodeType#NT_FOLDER}
1342 public static Node
mkfolders(Session session
, String path
) {
1343 return mkdirs(session
, path
, NodeType
.NT_FOLDER
, NodeType
.NT_FOLDER
, false);
1347 * Copy only nt:folder and nt:file, without their additional types and
1351 * if true copies folders as well, otherwise only first level files
1352 * @return how many files were copied
1354 public static Long
copyFiles(Node fromNode
, Node toNode
, Boolean recursive
, JcrMonitor monitor
, boolean onlyAdd
) {
1357 // Binary binary = null;
1358 // InputStream in = null;
1360 NodeIterator fromChildren
= fromNode
.getNodes();
1361 children
: while (fromChildren
.hasNext()) {
1362 if (monitor
!= null && monitor
.isCanceled())
1363 throw new ArgeoJcrException("Copy cancelled before it was completed");
1365 Node fromChild
= fromChildren
.nextNode();
1366 String fileName
= fromChild
.getName();
1367 if (fromChild
.isNodeType(NodeType
.NT_FILE
)) {
1368 if (onlyAdd
&& toNode
.hasNode(fileName
)) {
1369 monitor
.subTask("Skip existing " + fileName
);
1373 if (monitor
!= null)
1374 monitor
.subTask("Copy " + fileName
);
1375 try (Bin binary
= new Bin(fromChild
.getNode(Node
.JCR_CONTENT
).getProperty(Property
.JCR_DATA
));
1376 InputStream in
= binary
.getStream();) {
1377 copyStreamAsFile(toNode
, fileName
, in
);
1379 // IOUtils.closeQuietly(in);
1380 // closeQuietly(binary);
1383 toNode
.getSession().save();
1386 if (log
.isDebugEnabled())
1387 log
.debug("Copied file " + fromChild
.getPath());
1388 if (monitor
!= null)
1390 } else if (fromChild
.isNodeType(NodeType
.NT_FOLDER
) && recursive
) {
1392 if (toNode
.hasNode(fileName
)) {
1393 toChildFolder
= toNode
.getNode(fileName
);
1394 if (!toChildFolder
.isNodeType(NodeType
.NT_FOLDER
))
1395 throw new ArgeoJcrException(toChildFolder
+ " is not of type nt:folder");
1397 toChildFolder
= toNode
.addNode(fileName
, NodeType
.NT_FOLDER
);
1400 toNode
.getSession().save();
1402 count
= count
+ copyFiles(fromChild
, toChildFolder
, recursive
, monitor
, onlyAdd
);
1406 } catch (RepositoryException
| IOException e
) {
1407 throw new ArgeoJcrException("Cannot copy files between " + fromNode
+ " and " + toNode
);
1409 // in case there was an exception
1410 // IOUtils.closeQuietly(in);
1411 // closeQuietly(binary);
1416 * Iteratively count all file nodes in subtree, inefficient but can be useful
1417 * when query are poorly supported, such as in remoting.
1419 public static Long
countFiles(Node node
) {
1420 Long localCount
= 0l;
1422 for (NodeIterator nit
= node
.getNodes(); nit
.hasNext();) {
1423 Node child
= nit
.nextNode();
1424 if (child
.isNodeType(NodeType
.NT_FOLDER
))
1425 localCount
= localCount
+ countFiles(child
);
1426 else if (child
.isNodeType(NodeType
.NT_FILE
))
1427 localCount
= localCount
+ 1;
1429 } catch (RepositoryException e
) {
1430 throw new ArgeoJcrException("Cannot count all children of " + node
);
1436 * Copy a file as an nt:file, assuming an nt:folder hierarchy. The session is
1439 * @return the created file node
1441 public static Node
copyFile(Node folderNode
, File file
) {
1442 // InputStream in = null;
1443 try (InputStream in
= new FileInputStream(file
)) {
1444 // in = new FileInputStream(file);
1445 return copyStreamAsFile(folderNode
, file
.getName(), in
);
1446 } catch (IOException e
) {
1447 throw new ArgeoJcrException("Cannot copy file " + file
+ " under " + folderNode
, e
);
1449 // IOUtils.closeQuietly(in);
1453 /** Copy bytes as an nt:file */
1454 public static Node
copyBytesAsFile(Node folderNode
, String fileName
, byte[] bytes
) {
1455 // InputStream in = null;
1456 try (InputStream in
= new ByteArrayInputStream(bytes
)) {
1457 // in = new ByteArrayInputStream(bytes);
1458 return copyStreamAsFile(folderNode
, fileName
, in
);
1459 } catch (Exception e
) {
1460 throw new ArgeoJcrException("Cannot copy file " + fileName
+ " under " + folderNode
, e
);
1462 // IOUtils.closeQuietly(in);
1467 * Copy a stream as an nt:file, assuming an nt:folder hierarchy. The session is
1470 * @return the created file node
1472 public static Node
copyStreamAsFile(Node folderNode
, String fileName
, InputStream in
) {
1473 Binary binary
= null;
1477 if (folderNode
.hasNode(fileName
)) {
1478 fileNode
= folderNode
.getNode(fileName
);
1479 if (!fileNode
.isNodeType(NodeType
.NT_FILE
))
1480 throw new ArgeoJcrException(fileNode
+ " is not of type nt:file");
1481 // we assume that the content node is already there
1482 contentNode
= fileNode
.getNode(Node
.JCR_CONTENT
);
1484 fileNode
= folderNode
.addNode(fileName
, NodeType
.NT_FILE
);
1485 contentNode
= fileNode
.addNode(Node
.JCR_CONTENT
, NodeType
.NT_RESOURCE
);
1487 binary
= contentNode
.getSession().getValueFactory().createBinary(in
);
1488 contentNode
.setProperty(Property
.JCR_DATA
, binary
);
1490 } catch (Exception e
) {
1491 throw new ArgeoJcrException("Cannot create file node " + fileName
+ " under " + folderNode
, e
);
1493 closeQuietly(binary
);
1498 * Computes the checksum of an nt:file.
1500 * @deprecated use separate digest utilities
1503 public static String
checksumFile(Node fileNode
, String algorithm
) {
1505 try (InputStream in
= fileNode
.getNode(Node
.JCR_CONTENT
).getProperty(Property
.JCR_DATA
).getBinary()
1507 return digest(algorithm
, in
);
1508 } catch (RepositoryException
| IOException e
) {
1509 throw new ArgeoJcrException("Cannot checksum file " + fileNode
, e
);
1516 private static String
digest(String algorithm
, InputStream in
) {
1517 final Integer byteBufferCapacity
= 100 * 1024;// 100 KB
1519 MessageDigest digest
= MessageDigest
.getInstance(algorithm
);
1520 byte[] buffer
= new byte[byteBufferCapacity
];
1522 while ((read
= in
.read(buffer
)) > 0) {
1523 digest
.update(buffer
, 0, read
);
1526 byte[] checksum
= digest
.digest();
1527 String res
= encodeHexString(checksum
);
1529 } catch (Exception e
) {
1530 throw new ArgeoJcrException("Cannot digest with algorithm " + algorithm
, e
);
1536 * http://stackoverflow.com/questions/9655181/how-to-convert-a-byte-array-to
1537 * -a-hex-string-in-java
1540 private static String
encodeHexString(byte[] bytes
) {
1541 final char[] hexArray
= "0123456789abcdef".toCharArray();
1542 char[] hexChars
= new char[bytes
.length
* 2];
1543 for (int j
= 0; j
< bytes
.length
; j
++) {
1544 int v
= bytes
[j
] & 0xFF;
1545 hexChars
[j
* 2] = hexArray
[v
>>> 4];
1546 hexChars
[j
* 2 + 1] = hexArray
[v
& 0x0F];
1548 return new String(hexChars
);