]> git.argeo.org Git - lgpl/argeo-commons.git/blob - jcr/org.argeo.cms.jcr/src/org/argeo/jcr/Jcr.java
Clarify system roles
[lgpl/argeo-commons.git] / jcr / org.argeo.cms.jcr / src / org / argeo / jcr / Jcr.java
1 package org.argeo.jcr;
2
3 import java.io.ByteArrayOutputStream;
4 import java.io.IOException;
5 import java.io.InputStream;
6 import java.math.BigDecimal;
7 import java.text.MessageFormat;
8 import java.time.Instant;
9 import java.util.ArrayList;
10 import java.util.Arrays;
11 import java.util.Calendar;
12 import java.util.Collections;
13 import java.util.Date;
14 import java.util.GregorianCalendar;
15 import java.util.Iterator;
16 import java.util.List;
17
18 import javax.jcr.Binary;
19 import javax.jcr.ItemNotFoundException;
20 import javax.jcr.Node;
21 import javax.jcr.NodeIterator;
22 import javax.jcr.Property;
23 import javax.jcr.PropertyType;
24 import javax.jcr.Repository;
25 import javax.jcr.RepositoryException;
26 import javax.jcr.Session;
27 import javax.jcr.Value;
28 import javax.jcr.Workspace;
29 import javax.jcr.nodetype.NodeType;
30 import javax.jcr.query.Query;
31 import javax.jcr.query.QueryManager;
32 import javax.jcr.query.Row;
33 import javax.jcr.security.Privilege;
34 import javax.jcr.version.Version;
35 import javax.jcr.version.VersionHistory;
36 import javax.jcr.version.VersionIterator;
37 import javax.jcr.version.VersionManager;
38
39 import org.apache.commons.io.IOUtils;
40
41 /**
42 * Utility class whose purpose is to make using JCR less verbose by
43 * systematically using unchecked exceptions and returning <code>null</code>
44 * when something is not found. This is especially useful when writing user
45 * interfaces (such as with SWT) where listeners and callbacks expect unchecked
46 * exceptions. Loosely inspired by Java's <code>Files</code> singleton.
47 */
48 public class Jcr {
49 /**
50 * The name of a node which will be serialized as XML text, as per section 7.3.1
51 * of the JCR 2.0 specifications.
52 */
53 public final static String JCR_XMLTEXT = "jcr:xmltext";
54 /**
55 * The name of a property which will be serialized as XML text, as per section
56 * 7.3.1 of the JCR 2.0 specifications.
57 */
58 public final static String JCR_XMLCHARACTERS = "jcr:xmlcharacters";
59 /**
60 * <code>jcr:name</code>, when used in another context than
61 * {@link Property#JCR_NAME}, typically to name a node rather than a property.
62 */
63 public final static String JCR_NAME = "jcr:name";
64 /**
65 * <code>jcr:path</code>, when used in another context than
66 * {@link Property#JCR_PATH}, typically to name a node rather than a property.
67 */
68 public final static String JCR_PATH = "jcr:path";
69 /**
70 * <code>jcr:primaryType</code> with prefix instead of namespace (as in
71 * {@link Property#JCR_PRIMARY_TYPE}.
72 */
73 public final static String JCR_PRIMARY_TYPE = "jcr:primaryType";
74 /**
75 * <code>jcr:mixinTypes</code> with prefix instead of namespace (as in
76 * {@link Property#JCR_MIXIN_TYPES}.
77 */
78 public final static String JCR_MIXIN_TYPES = "jcr:mixinTypes";
79 /**
80 * <code>jcr:uuid</code> with prefix instead of namespace (as in
81 * {@link Property#JCR_UUID}.
82 */
83 public final static String JCR_UUID = "jcr:uuid";
84 /**
85 * <code>jcr:created</code> with prefix instead of namespace (as in
86 * {@link Property#JCR_CREATED}.
87 */
88 public final static String JCR_CREATED = "jcr:created";
89 /**
90 * <code>jcr:createdBy</code> with prefix instead of namespace (as in
91 * {@link Property#JCR_CREATED_BY}.
92 */
93 public final static String JCR_CREATED_BY = "jcr:createdBy";
94 /**
95 * <code>jcr:lastModified</code> with prefix instead of namespace (as in
96 * {@link Property#JCR_LAST_MODIFIED}.
97 */
98 public final static String JCR_LAST_MODIFIED = "jcr:lastModified";
99 /**
100 * <code>jcr:lastModifiedBy</code> with prefix instead of namespace (as in
101 * {@link Property#JCR_LAST_MODIFIED_BY}.
102 */
103 public final static String JCR_LAST_MODIFIED_BY = "jcr:lastModifiedBy";
104
105 /**
106 * @see Node#isNodeType(String)
107 * @throws JcrException caused by {@link RepositoryException}
108 */
109 public static boolean isNodeType(Node node, String nodeTypeName) {
110 try {
111 return node.isNodeType(nodeTypeName);
112 } catch (RepositoryException e) {
113 throw new JcrException("Cannot get whether " + node + " is of type " + nodeTypeName, e);
114 }
115 }
116
117 /**
118 * @see Node#hasNodes()
119 * @throws JcrException caused by {@link RepositoryException}
120 */
121 public static boolean hasNodes(Node node) {
122 try {
123 return node.hasNodes();
124 } catch (RepositoryException e) {
125 throw new JcrException("Cannot get whether " + node + " has children.", e);
126 }
127 }
128
129 /**
130 * @see Node#getParent()
131 * @throws JcrException caused by {@link RepositoryException}
132 */
133 public static Node getParent(Node node) {
134 try {
135 return isRoot(node) ? null : node.getParent();
136 } catch (RepositoryException e) {
137 throw new JcrException("Cannot get parent of " + node, e);
138 }
139 }
140
141 /**
142 * @see Node#getParent()
143 * @throws JcrException caused by {@link RepositoryException}
144 */
145 public static String getParentPath(Node node) {
146 return getPath(getParent(node));
147 }
148
149 /**
150 * Whether this node is the root node.
151 *
152 * @throws JcrException caused by {@link RepositoryException}
153 */
154 public static boolean isRoot(Node node) {
155 try {
156 return node.getDepth() == 0;
157 } catch (RepositoryException e) {
158 throw new JcrException("Cannot get depth of " + node, e);
159 }
160 }
161
162 /**
163 * @see Node#getPath()
164 * @throws JcrException caused by {@link RepositoryException}
165 */
166 public static String getPath(Node node) {
167 try {
168 return node.getPath();
169 } catch (RepositoryException e) {
170 throw new JcrException("Cannot get path of " + node, e);
171 }
172 }
173
174 /**
175 * @see Node#getSession()
176 * @see Session#getWorkspace()
177 * @see Workspace#getName()
178 */
179 public static String getWorkspaceName(Node node) {
180 return session(node).getWorkspace().getName();
181 }
182
183 /**
184 * @see Node#getIdentifier()
185 * @throws JcrException caused by {@link RepositoryException}
186 */
187 public static String getIdentifier(Node node) {
188 try {
189 return node.getIdentifier();
190 } catch (RepositoryException e) {
191 throw new JcrException("Cannot get identifier of " + node, e);
192 }
193 }
194
195 /**
196 * @see Node#getName()
197 * @throws JcrException caused by {@link RepositoryException}
198 */
199 public static String getName(Node node) {
200 try {
201 return node.getName();
202 } catch (RepositoryException e) {
203 throw new JcrException("Cannot get name of " + node, e);
204 }
205 }
206
207 /**
208 * Returns the node name with its current index (useful for re-ordering).
209 *
210 * @see Node#getName()
211 * @see Node#getIndex()
212 * @throws JcrException caused by {@link RepositoryException}
213 */
214 public static String getIndexedName(Node node) {
215 try {
216 return node.getName() + "[" + node.getIndex() + "]";
217 } catch (RepositoryException e) {
218 throw new JcrException("Cannot get name of " + node, e);
219 }
220 }
221
222 /**
223 * @see Node#getProperty(String)
224 * @throws JcrException caused by {@link RepositoryException}
225 */
226 public static Property getProperty(Node node, String property) {
227 try {
228 if (node.hasProperty(property))
229 return node.getProperty(property);
230 else
231 return null;
232 } catch (RepositoryException e) {
233 throw new JcrException("Cannot get property " + property + " of " + node, e);
234 }
235 }
236
237 /**
238 * @see Node#getIndex()
239 * @throws JcrException caused by {@link RepositoryException}
240 */
241 public static int getIndex(Node node) {
242 try {
243 return node.getIndex();
244 } catch (RepositoryException e) {
245 throw new JcrException("Cannot get index of " + node, e);
246 }
247 }
248
249 /**
250 * If node has mixin {@link NodeType#MIX_TITLE}, return
251 * {@link Property#JCR_TITLE}, otherwise return {@link #getName(Node)}.
252 */
253 public static String getTitle(Node node) {
254 if (Jcr.isNodeType(node, NodeType.MIX_TITLE))
255 return get(node, Property.JCR_TITLE);
256 else
257 return Jcr.getName(node);
258 }
259
260 /** Accesses a {@link NodeIterator} as an {@link Iterable}. */
261 @SuppressWarnings("unchecked")
262 public static Iterable<Node> iterate(NodeIterator nodeIterator) {
263 return new Iterable<Node>() {
264
265 @Override
266 public Iterator<Node> iterator() {
267 return nodeIterator;
268 }
269 };
270 }
271
272 /**
273 * @return the children as an {@link Iterable} for use in for-each llops.
274 * @see Node#getNodes()
275 * @throws JcrException caused by {@link RepositoryException}
276 */
277 public static Iterable<Node> nodes(Node node) {
278 try {
279 return iterate(node.getNodes());
280 } catch (RepositoryException e) {
281 throw new JcrException("Cannot get children of " + node, e);
282 }
283 }
284
285 /**
286 * @return the children as a (possibly empty) {@link List}.
287 * @see Node#getNodes()
288 * @throws JcrException caused by {@link RepositoryException}
289 */
290 public static List<Node> getNodes(Node node) {
291 List<Node> nodes = new ArrayList<>();
292 try {
293 if (node.hasNodes()) {
294 NodeIterator nit = node.getNodes();
295 while (nit.hasNext())
296 nodes.add(nit.nextNode());
297 return nodes;
298 } else
299 return nodes;
300 } catch (RepositoryException e) {
301 throw new JcrException("Cannot get children of " + node, e);
302 }
303 }
304
305 /**
306 * @return the child or <code>null</node> if not found
307 * @see Node#getNode(String)
308 * @throws JcrException caused by {@link RepositoryException}
309 */
310 public static Node getNode(Node node, String child) {
311 try {
312 if (node.hasNode(child))
313 return node.getNode(child);
314 else
315 return null;
316 } catch (RepositoryException e) {
317 throw new JcrException("Cannot get child of " + node, e);
318 }
319 }
320
321 /**
322 * @return the node at this path or <code>null</node> if not found
323 * @see Session#getNode(String)
324 * @throws JcrException caused by {@link RepositoryException}
325 */
326 public static Node getNode(Session session, String path) {
327 try {
328 if (session.nodeExists(path))
329 return session.getNode(path);
330 else
331 return null;
332 } catch (RepositoryException e) {
333 throw new JcrException("Cannot get node " + path, e);
334 }
335 }
336
337 /**
338 * Add a node to this parent, setting its primary type and its mixins.
339 *
340 * @param parent the parent node
341 * @param name the name of the node, if <code>null</code>, the primary
342 * type will be used (typically for XML structures)
343 * @param primaryType the primary type, if <code>null</code>
344 * {@link NodeType#NT_UNSTRUCTURED} will be used.
345 * @param mixins the mixins
346 * @return the created node
347 * @see Node#addNode(String, String)
348 * @see Node#addMixin(String)
349 */
350 public static Node addNode(Node parent, String name, String primaryType, String... mixins) {
351 if (name == null && primaryType == null)
352 throw new IllegalArgumentException("Both node name and primary type cannot be null");
353 try {
354 Node newNode = parent.addNode(name == null ? primaryType : name,
355 primaryType == null ? NodeType.NT_UNSTRUCTURED : primaryType);
356 for (String mixin : mixins) {
357 newNode.addMixin(mixin);
358 }
359 return newNode;
360 } catch (RepositoryException e) {
361 throw new JcrException("Cannot add node " + name + " to " + parent, e);
362 }
363 }
364
365 /**
366 * Add an {@link NodeType#NT_BASE} node to this parent.
367 *
368 * @param parent the parent node
369 * @param name the name of the node, cannot be <code>null</code>
370 * @return the created node
371 *
372 * @see Node#addNode(String)
373 */
374 public static Node addNode(Node parent, String name) {
375 if (name == null)
376 throw new IllegalArgumentException("Node name cannot be null");
377 try {
378 Node newNode = parent.addNode(name);
379 return newNode;
380 } catch (RepositoryException e) {
381 throw new JcrException("Cannot add node " + name + " to " + parent, e);
382 }
383 }
384
385 /**
386 * Add mixins to a node.
387 *
388 * @param node the node
389 * @param mixins the mixins
390 * @return the created node
391 * @see Node#addMixin(String)
392 */
393 public static void addMixin(Node node, String... mixins) {
394 try {
395 for (String mixin : mixins) {
396 node.addMixin(mixin);
397 }
398 } catch (RepositoryException e) {
399 throw new JcrException("Cannot add mixins " + Arrays.asList(mixins) + " to " + node, e);
400 }
401 }
402
403 /**
404 * Removes this node.
405 *
406 * @see Node#remove()
407 */
408 public static void remove(Node node) {
409 try {
410 node.remove();
411 } catch (RepositoryException e) {
412 throw new JcrException("Cannot remove node " + node, e);
413 }
414 }
415
416 /**
417 * @return the node with htis id or <code>null</node> if not found
418 * @see Session#getNodeByIdentifier(String)
419 * @throws JcrException caused by {@link RepositoryException}
420 */
421 public static Node getNodeById(Session session, String id) {
422 try {
423 return session.getNodeByIdentifier(id);
424 } catch (ItemNotFoundException e) {
425 return null;
426 } catch (RepositoryException e) {
427 throw new JcrException("Cannot get node with id " + id, e);
428 }
429 }
430
431 /**
432 * Set a property to the given value, or remove it if the value is
433 * <code>null</code>.
434 *
435 * @throws JcrException caused by {@link RepositoryException}
436 */
437 public static void set(Node node, String property, Object value) {
438 try {
439 if (!node.hasProperty(property)) {
440 if (value != null) {
441 if (value instanceof List) {// multiple
442 List<?> lst = (List<?>) value;
443 String[] values = new String[lst.size()];
444 for (int i = 0; i < lst.size(); i++) {
445 values[i] = lst.get(i).toString();
446 }
447 node.setProperty(property, values);
448 } else {
449 node.setProperty(property, value.toString());
450 }
451 }
452 return;
453 }
454 Property prop = node.getProperty(property);
455 if (value == null) {
456 prop.remove();
457 return;
458 }
459
460 // multiple
461 if (value instanceof List) {
462 List<?> lst = (List<?>) value;
463 String[] values = new String[lst.size()];
464 // TODO better cast?
465 for (int i = 0; i < lst.size(); i++) {
466 values[i] = lst.get(i).toString();
467 }
468 if (!prop.isMultiple())
469 prop.remove();
470 node.setProperty(property, values);
471 return;
472 }
473
474 // single
475 if (prop.isMultiple()) {
476 prop.remove();
477 node.setProperty(property, value.toString());
478 return;
479 }
480
481 if (value instanceof String)
482 prop.setValue((String) value);
483 else if (value instanceof Long)
484 prop.setValue((Long) value);
485 else if (value instanceof Integer)
486 prop.setValue(((Integer) value).longValue());
487 else if (value instanceof Double)
488 prop.setValue((Double) value);
489 else if (value instanceof Float)
490 prop.setValue(((Float) value).doubleValue());
491 else if (value instanceof Calendar)
492 prop.setValue((Calendar) value);
493 else if (value instanceof BigDecimal)
494 prop.setValue((BigDecimal) value);
495 else if (value instanceof Boolean)
496 prop.setValue((Boolean) value);
497 else if (value instanceof byte[])
498 JcrUtils.setBinaryAsBytes(prop, (byte[]) value);
499 else if (value instanceof Instant) {
500 Instant instant = (Instant) value;
501 GregorianCalendar calendar = new GregorianCalendar();
502 calendar.setTime(Date.from(instant));
503 prop.setValue(calendar);
504 } else // try with toString()
505 prop.setValue(value.toString());
506 } catch (RepositoryException e) {
507 throw new JcrException("Cannot set property " + property + " of " + node + " to " + value, e);
508 }
509 }
510
511 /**
512 * Get property as {@link String}.
513 *
514 * @return the value of
515 * {@link Node#getProperty(String)}.{@link Property#getString()} or
516 * <code>null</code> if the property does not exist.
517 * @throws JcrException caused by {@link RepositoryException}
518 */
519 public static String get(Node node, String property) {
520 return get(node, property, null);
521 }
522
523 /**
524 * Get property as a {@link String}. If the property is multiple it returns the
525 * first value.
526 *
527 * @return the value of
528 * {@link Node#getProperty(String)}.{@link Property#getString()} or
529 * <code>defaultValue</code> if the property does not exist.
530 * @throws JcrException caused by {@link RepositoryException}
531 */
532 public static String get(Node node, String property, String defaultValue) {
533 try {
534 if (node.hasProperty(property)) {
535 Property p = node.getProperty(property);
536 if (!p.isMultiple())
537 return p.getString();
538 else {
539 Value[] values = p.getValues();
540 if (values.length == 0)
541 return defaultValue;
542 else
543 return values[0].getString();
544 }
545 } else
546 return defaultValue;
547 } catch (RepositoryException e) {
548 throw new JcrException("Cannot retrieve property " + property + " from " + node, e);
549 }
550 }
551
552 /**
553 * Get property as a {@link Value}.
554 *
555 * @return {@link Node#getProperty(String)} or <code>null</code> if the property
556 * does not exist.
557 * @throws JcrException caused by {@link RepositoryException}
558 */
559 public static Value getValue(Node node, String property) {
560 try {
561 if (node.hasProperty(property))
562 return node.getProperty(property).getValue();
563 else
564 return null;
565 } catch (RepositoryException e) {
566 throw new JcrException("Cannot retrieve property " + property + " from " + node, e);
567 }
568 }
569
570 /**
571 * Get property doing a best effort to cast it as the target object.
572 *
573 * @return the value of {@link Node#getProperty(String)} or
574 * <code>defaultValue</code> if the property does not exist.
575 * @throws IllegalArgumentException if the value could not be cast
576 * @throws JcrException in case of unexpected
577 * {@link RepositoryException}
578 */
579 @SuppressWarnings("unchecked")
580 public static <T> T getAs(Node node, String property, T defaultValue) {
581 try {
582 // TODO deal with multiple
583 if (node.hasProperty(property)) {
584 Property p = node.getProperty(property);
585 try {
586 if (p.isMultiple()) {
587 throw new UnsupportedOperationException("Multiple values properties are not supported");
588 }
589 Value value = p.getValue();
590 return (T) get(value);
591 } catch (ClassCastException e) {
592 throw new IllegalArgumentException(
593 "Cannot cast property of type " + PropertyType.nameFromValue(p.getType()), e);
594 }
595 } else {
596 return defaultValue;
597 }
598 } catch (RepositoryException e) {
599 throw new JcrException("Cannot retrieve property " + property + " from " + node, e);
600 }
601 }
602
603 public static <T> T getAs(Node node, String property, Class<T> clss) {
604 if (String.class.isAssignableFrom(clss)) {
605 return (T) get(node, property);
606 } else if (Long.class.isAssignableFrom(clss)) {
607 return (T) get(node, property);
608 } else {
609 throw new IllegalArgumentException("Unsupported format " + clss);
610 }
611 }
612
613 /**
614 * Get a multiple property as a list, doing a best effort to cast it as the
615 * target list.
616 *
617 * @return the value of {@link Node#getProperty(String)}.
618 * @throws IllegalArgumentException if the value could not be cast
619 * @throws JcrException in case of unexpected
620 * {@link RepositoryException}
621 */
622 public static <T> List<T> getMultiple(Node node, String property) {
623 try {
624 if (node.hasProperty(property)) {
625 Property p = node.getProperty(property);
626 return getMultiple(p);
627 } else {
628 return null;
629 }
630 } catch (RepositoryException e) {
631 throw new JcrException("Cannot retrieve multiple values property " + property + " from " + node, e);
632 }
633 }
634
635 /**
636 * Get a multiple property as a list, doing a best effort to cast it as the
637 * target list.
638 */
639 @SuppressWarnings("unchecked")
640 public static <T> List<T> getMultiple(Property p) {
641 try {
642 List<T> res = new ArrayList<>();
643 if (!p.isMultiple()) {
644 res.add((T) get(p.getValue()));
645 return res;
646 }
647 Value[] values = p.getValues();
648 for (Value value : values) {
649 res.add((T) get(value));
650 }
651 return res;
652 } catch (ClassCastException | RepositoryException e) {
653 throw new IllegalArgumentException("Cannot get property " + p, e);
654 }
655 }
656
657 /** Cast a {@link Value} to a standard Java object. */
658 public static Object get(Value value) {
659 Binary binary = null;
660 try {
661 switch (value.getType()) {
662 case PropertyType.STRING:
663 return value.getString();
664 case PropertyType.DOUBLE:
665 return (Double) value.getDouble();
666 case PropertyType.LONG:
667 return (Long) value.getLong();
668 case PropertyType.BOOLEAN:
669 return (Boolean) value.getBoolean();
670 case PropertyType.DATE:
671 return value.getDate();
672 case PropertyType.BINARY:
673 binary = value.getBinary();
674 byte[] arr = null;
675 try (InputStream in = binary.getStream(); ByteArrayOutputStream out = new ByteArrayOutputStream();) {
676 IOUtils.copy(in, out);
677 arr = out.toByteArray();
678 } catch (IOException e) {
679 throw new RuntimeException("Cannot read binary from " + value, e);
680 }
681 return arr;
682 default:
683 return value.getString();
684 }
685 } catch (RepositoryException e) {
686 throw new JcrException("Cannot cast value from " + value, e);
687 } finally {
688 if (binary != null)
689 binary.dispose();
690 }
691 }
692
693 /**
694 * Retrieves the {@link Session} related to this node.
695 *
696 * @deprecated Use {@link #getSession(Node)} instead.
697 */
698 @Deprecated
699 public static Session session(Node node) {
700 return getSession(node);
701 }
702
703 /** Retrieves the {@link Session} related to this node. */
704 public static Session getSession(Node node) {
705 try {
706 return node.getSession();
707 } catch (RepositoryException e) {
708 throw new JcrException("Cannot retrieve session related to " + node, e);
709 }
710 }
711
712 /** Retrieves the root node related to this session. */
713 public static Node getRootNode(Session session) {
714 try {
715 return session.getRootNode();
716 } catch (RepositoryException e) {
717 throw new JcrException("Cannot get root node for " + session, e);
718 }
719 }
720
721 /** Whether this item exists. */
722 public static boolean itemExists(Session session, String path) {
723 try {
724 return session.itemExists(path);
725 } catch (RepositoryException e) {
726 throw new JcrException("Cannot check whether " + path + " exists", e);
727 }
728 }
729
730 /**
731 * Saves the {@link Session} related to this node. Note that all other unrelated
732 * modifications in this session will also be saved.
733 */
734 public static void save(Node node) {
735 try {
736 Session session = node.getSession();
737 // if (node.isNodeType(NodeType.MIX_LAST_MODIFIED)) {
738 // set(node, Property.JCR_LAST_MODIFIED, Instant.now());
739 // set(node, Property.JCR_LAST_MODIFIED_BY, session.getUserID());
740 // }
741 if (session.hasPendingChanges())
742 session.save();
743 } catch (RepositoryException e) {
744 throw new JcrException("Cannot save session related to " + node + " in workspace "
745 + session(node).getWorkspace().getName(), e);
746 }
747 }
748
749 /** Login to a JCR repository. */
750 public static Session login(Repository repository, String workspace) {
751 try {
752 return repository.login(workspace);
753 } catch (RepositoryException e) {
754 throw new IllegalArgumentException("Cannot login to repository", e);
755 }
756 }
757
758 /** Safely and silently logs out a session. */
759 public static void logout(Session session) {
760 try {
761 if (session != null)
762 if (session.isLive())
763 session.logout();
764 } catch (Exception e) {
765 // silent
766 }
767 }
768
769 /** Safely and silently logs out the underlying session. */
770 public static void logout(Node node) {
771 Jcr.logout(session(node));
772 }
773
774 /*
775 * SECURITY
776 */
777 /**
778 * Add a single privilege to a node.
779 *
780 * @see Privilege
781 */
782 public static void addPrivilege(Node node, String principal, String privilege) {
783 try {
784 Session session = node.getSession();
785 JcrUtils.addPrivilege(session, node.getPath(), principal, privilege);
786 } catch (RepositoryException e) {
787 throw new JcrException("Cannot add privilege " + privilege + " to " + node, e);
788 }
789 }
790
791 /*
792 * VERSIONING
793 */
794 /** Get checked out status. */
795 public static boolean isCheckedOut(Node node) {
796 try {
797 return node.isCheckedOut();
798 } catch (RepositoryException e) {
799 throw new JcrException("Cannot retrieve checked out status of " + node, e);
800 }
801 }
802
803 /** @see VersionManager#checkpoint(String) */
804 public static void checkpoint(Node node) {
805 try {
806 versionManager(node).checkpoint(node.getPath());
807 } catch (RepositoryException e) {
808 throw new JcrException("Cannot check in " + node, e);
809 }
810 }
811
812 /** @see VersionManager#checkin(String) */
813 public static void checkin(Node node) {
814 try {
815 versionManager(node).checkin(node.getPath());
816 } catch (RepositoryException e) {
817 throw new JcrException("Cannot check in " + node, e);
818 }
819 }
820
821 /** @see VersionManager#checkout(String) */
822 public static void checkout(Node node) {
823 try {
824 versionManager(node).checkout(node.getPath());
825 } catch (RepositoryException e) {
826 throw new JcrException("Cannot check out " + node, e);
827 }
828 }
829
830 /** Get the {@link VersionManager} related to this node. */
831 public static VersionManager versionManager(Node node) {
832 try {
833 return node.getSession().getWorkspace().getVersionManager();
834 } catch (RepositoryException e) {
835 throw new JcrException("Cannot get version manager from " + node, e);
836 }
837 }
838
839 /** Get the {@link VersionHistory} related to this node. */
840 public static VersionHistory getVersionHistory(Node node) {
841 try {
842 return versionManager(node).getVersionHistory(node.getPath());
843 } catch (RepositoryException e) {
844 throw new JcrException("Cannot get version history from " + node, e);
845 }
846 }
847
848 /**
849 * The linear versions of this version history in reverse order and without the
850 * root version.
851 */
852 public static List<Version> getLinearVersions(VersionHistory versionHistory) {
853 try {
854 List<Version> lst = new ArrayList<>();
855 VersionIterator vit = versionHistory.getAllLinearVersions();
856 while (vit.hasNext())
857 lst.add(vit.nextVersion());
858 lst.remove(0);
859 Collections.reverse(lst);
860 return lst;
861 } catch (RepositoryException e) {
862 throw new JcrException("Cannot get linear versions from " + versionHistory, e);
863 }
864 }
865
866 /** The frozen node related to this {@link Version}. */
867 public static Node getFrozenNode(Version version) {
868 try {
869 return version.getFrozenNode();
870 } catch (RepositoryException e) {
871 throw new JcrException("Cannot get frozen node from " + version, e);
872 }
873 }
874
875 /** Get the base {@link Version} related to this node. */
876 public static Version getBaseVersion(Node node) {
877 try {
878 return versionManager(node).getBaseVersion(node.getPath());
879 } catch (RepositoryException e) {
880 throw new JcrException("Cannot get base version from " + node, e);
881 }
882 }
883
884 /*
885 * FILES
886 */
887 /**
888 * Returns the size of this file.
889 *
890 * @see NodeType#NT_FILE
891 */
892 public static long getFileSize(Node fileNode) {
893 try {
894 if (!fileNode.isNodeType(NodeType.NT_FILE))
895 throw new IllegalArgumentException(fileNode + " must be a file.");
896 return getBinarySize(fileNode.getNode(Node.JCR_CONTENT).getProperty(Property.JCR_DATA).getBinary());
897 } catch (RepositoryException e) {
898 throw new JcrException("Cannot get file size of " + fileNode, e);
899 }
900 }
901
902 /** Returns the size of this {@link Binary}. */
903 public static long getBinarySize(Binary binaryArg) {
904 try {
905 try (Bin binary = new Bin(binaryArg)) {
906 return binary.getSize();
907 }
908 } catch (RepositoryException e) {
909 throw new JcrException("Cannot get file size of binary " + binaryArg, e);
910 }
911 }
912
913 // QUERY
914 /** Creates a JCR-SQL2 query using {@link MessageFormat}. */
915 public static Query createQuery(QueryManager qm, String sql, Object... args) {
916 // fix single quotes
917 sql = sql.replaceAll("'", "''");
918 String query = MessageFormat.format(sql, args);
919 try {
920 return qm.createQuery(query, Query.JCR_SQL2);
921 } catch (RepositoryException e) {
922 throw new JcrException("Cannot create JCR-SQL2 query from " + query, e);
923 }
924 }
925
926 /** Executes a JCR-SQL2 query using {@link MessageFormat}. */
927 public static NodeIterator executeQuery(QueryManager qm, String sql, Object... args) {
928 Query query = createQuery(qm, sql, args);
929 try {
930 return query.execute().getNodes();
931 } catch (RepositoryException e) {
932 throw new JcrException("Cannot execute query " + sql + " with arguments " + Arrays.asList(args), e);
933 }
934 }
935
936 /** Executes a JCR-SQL2 query using {@link MessageFormat}. */
937 public static NodeIterator executeQuery(Session session, String sql, Object... args) {
938 QueryManager queryManager;
939 try {
940 queryManager = session.getWorkspace().getQueryManager();
941 } catch (RepositoryException e) {
942 throw new JcrException("Cannot get query manager from session " + session, e);
943 }
944 return executeQuery(queryManager, sql, args);
945 }
946
947 /**
948 * Executes a JCR-SQL2 query using {@link MessageFormat}, which must return a
949 * single node at most.
950 *
951 * @return the node or <code>null</code> if not found.
952 */
953 public static Node getNode(QueryManager qm, String sql, Object... args) {
954 NodeIterator nit = executeQuery(qm, sql, args);
955 if (nit.hasNext()) {
956 Node node = nit.nextNode();
957 if (nit.hasNext())
958 throw new IllegalStateException(
959 "Query " + sql + " with arguments " + Arrays.asList(args) + " returned more than one node.");
960 return node;
961 } else {
962 return null;
963 }
964 }
965
966 /**
967 * Executes a JCR-SQL2 query using {@link MessageFormat}, which must return a
968 * single node at most.
969 *
970 * @return the node or <code>null</code> if not found.
971 */
972 public static Node getNode(Session session, String sql, Object... args) {
973 QueryManager queryManager;
974 try {
975 queryManager = session.getWorkspace().getQueryManager();
976 } catch (RepositoryException e) {
977 throw new JcrException("Cannot get query manager from session " + session, e);
978 }
979 return getNode(queryManager, sql, args);
980 }
981
982 public static Node getRowNode(Row row, String selectorName) {
983 try {
984 return row.getNode(selectorName);
985 } catch (RepositoryException e) {
986 throw new JcrException("Cannot get node " + selectorName + " from row", e);
987 }
988 }
989
990 /** Singleton. */
991 private Jcr() {
992
993 }
994 }