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
;
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
.security
.Privilege
;
33 import javax
.jcr
.version
.Version
;
34 import javax
.jcr
.version
.VersionHistory
;
35 import javax
.jcr
.version
.VersionIterator
;
36 import javax
.jcr
.version
.VersionManager
;
38 import org
.apache
.commons
.io
.IOUtils
;
41 * Utility class whose purpose is to make using JCR less verbose by
42 * systematically using unchecked exceptions and returning <code>null</code>
43 * when something is not found. This is especially useful when writing user
44 * interfaces (such as with SWT) where listeners and callbacks expect unchecked
45 * exceptions. Loosely inspired by Java's <code>Files</code> singleton.
49 * The name of a node which will be serialized as XML text, as per section 7.3.1
50 * of the JCR 2.0 specifications.
52 public final static String JCR_XMLTEXT
= "jcr:xmltext";
54 * The name of a property which will be serialized as XML text, as per section
55 * 7.3.1 of the JCR 2.0 specifications.
57 public final static String JCR_XMLCHARACTERS
= "jcr:xmlcharacters";
59 * <code>jcr:name</code>, when used in another context than
60 * {@link Property#JCR_NAME}, typically to name a node rather than a property.
62 public final static String JCR_NAME
= "jcr:name";
64 * <code>jcr:path</code>, when used in another context than
65 * {@link Property#JCR_PATH}, typically to name a node rather than a property.
67 public final static String JCR_PATH
= "jcr:path";
69 * <code>jcr:primaryType</code> with prefix instead of namespace (as in
70 * {@link Property#JCR_PRIMARY_TYPE}.
72 public final static String JCR_PRIMARY_TYPE
= "jcr:primaryType";
74 * <code>jcr:mixinTypes</code> with prefix instead of namespace (as in
75 * {@link Property#JCR_MIXIN_TYPES}.
77 public final static String JCR_MIXIN_TYPES
= "jcr:mixinTypes";
79 * <code>jcr:uuid</code> with prefix instead of namespace (as in
80 * {@link Property#JCR_UUID}.
82 public final static String JCR_UUID
= "jcr:uuid";
84 * <code>jcr:created</code> with prefix instead of namespace (as in
85 * {@link Property#JCR_CREATED}.
87 public final static String JCR_CREATED
= "jcr:created";
89 * <code>jcr:createdBy</code> with prefix instead of namespace (as in
90 * {@link Property#JCR_CREATED_BY}.
92 public final static String JCR_CREATED_BY
= "jcr:createdBy";
94 * <code>jcr:lastModified</code> with prefix instead of namespace (as in
95 * {@link Property#JCR_LAST_MODIFIED}.
97 public final static String JCR_LAST_MODIFIED
= "jcr:lastModified";
99 * <code>jcr:lastModifiedBy</code> with prefix instead of namespace (as in
100 * {@link Property#JCR_LAST_MODIFIED_BY}.
102 public final static String JCR_LAST_MODIFIED_BY
= "jcr:lastModifiedBy";
105 * @see Node#isNodeType(String)
106 * @throws JcrException caused by {@link RepositoryException}
108 public static boolean isNodeType(Node node
, String nodeTypeName
) {
110 return node
.isNodeType(nodeTypeName
);
111 } catch (RepositoryException e
) {
112 throw new JcrException("Cannot get whether " + node
+ " is of type " + nodeTypeName
, e
);
117 * @see Node#hasNodes()
118 * @throws JcrException caused by {@link RepositoryException}
120 public static boolean hasNodes(Node node
) {
122 return node
.hasNodes();
123 } catch (RepositoryException e
) {
124 throw new JcrException("Cannot get whether " + node
+ " has children.", e
);
129 * @see Node#getParent()
130 * @throws JcrException caused by {@link RepositoryException}
132 public static Node
getParent(Node node
) {
134 return isRoot(node
) ?
null : node
.getParent();
135 } catch (RepositoryException e
) {
136 throw new JcrException("Cannot get parent of " + node
, e
);
141 * @see Node#getParent()
142 * @throws JcrException caused by {@link RepositoryException}
144 public static String
getParentPath(Node node
) {
145 return getPath(getParent(node
));
149 * Whether this node is the root node.
151 * @throws JcrException caused by {@link RepositoryException}
153 public static boolean isRoot(Node node
) {
155 return node
.getDepth() == 0;
156 } catch (RepositoryException e
) {
157 throw new JcrException("Cannot get depth of " + node
, e
);
162 * @see Node#getPath()
163 * @throws JcrException caused by {@link RepositoryException}
165 public static String
getPath(Node node
) {
167 return node
.getPath();
168 } catch (RepositoryException e
) {
169 throw new JcrException("Cannot get path of " + node
, e
);
174 * @see Node#getSession()
175 * @see Session#getWorkspace()
176 * @see Workspace#getName()
178 public static String
getWorkspaceName(Node node
) {
179 return session(node
).getWorkspace().getName();
183 * @see Node#getIdentifier()
184 * @throws JcrException caused by {@link RepositoryException}
186 public static String
getIdentifier(Node node
) {
188 return node
.getIdentifier();
189 } catch (RepositoryException e
) {
190 throw new JcrException("Cannot get identifier of " + node
, e
);
195 * @see Node#getName()
196 * @throws JcrException caused by {@link RepositoryException}
198 public static String
getName(Node node
) {
200 return node
.getName();
201 } catch (RepositoryException e
) {
202 throw new JcrException("Cannot get name of " + node
, e
);
207 * Returns the node name with its current index (useful for re-ordering).
209 * @see Node#getName()
210 * @see Node#getIndex()
211 * @throws JcrException caused by {@link RepositoryException}
213 public static String
getIndexedName(Node node
) {
215 return node
.getName() + "[" + node
.getIndex() + "]";
216 } catch (RepositoryException e
) {
217 throw new JcrException("Cannot get name of " + node
, e
);
222 * @see Node#getProperty(String)
223 * @throws JcrException caused by {@link RepositoryException}
225 public static Property
getProperty(Node node
, String property
) {
227 if (node
.hasProperty(property
))
228 return node
.getProperty(property
);
231 } catch (RepositoryException e
) {
232 throw new JcrException("Cannot get property " + property
+ " of " + node
, e
);
237 * @see Node#getIndex()
238 * @throws JcrException caused by {@link RepositoryException}
240 public static int getIndex(Node node
) {
242 return node
.getIndex();
243 } catch (RepositoryException e
) {
244 throw new JcrException("Cannot get index of " + node
, e
);
249 * If node has mixin {@link NodeType#MIX_TITLE}, return
250 * {@link Property#JCR_TITLE}, otherwise return {@link #getName(Node)}.
252 public static String
getTitle(Node node
) {
253 if (Jcr
.isNodeType(node
, NodeType
.MIX_TITLE
))
254 return get(node
, Property
.JCR_TITLE
);
256 return Jcr
.getName(node
);
259 /** Accesses a {@link NodeIterator} as an {@link Iterable}. */
260 @SuppressWarnings("unchecked")
261 public static Iterable
<Node
> iterate(NodeIterator nodeIterator
) {
262 return new Iterable
<Node
>() {
265 public Iterator
<Node
> iterator() {
272 * @return the children as an {@link Iterable} for use in for-each llops.
273 * @see Node#getNodes()
274 * @throws JcrException caused by {@link RepositoryException}
276 public static Iterable
<Node
> nodes(Node node
) {
278 return iterate(node
.getNodes());
279 } catch (RepositoryException e
) {
280 throw new JcrException("Cannot get children of " + node
, e
);
285 * @return the children as a (possibly empty) {@link List}.
286 * @see Node#getNodes()
287 * @throws JcrException caused by {@link RepositoryException}
289 public static List
<Node
> getNodes(Node node
) {
290 List
<Node
> nodes
= new ArrayList
<>();
292 if (node
.hasNodes()) {
293 NodeIterator nit
= node
.getNodes();
294 while (nit
.hasNext())
295 nodes
.add(nit
.nextNode());
299 } catch (RepositoryException e
) {
300 throw new JcrException("Cannot get children of " + node
, e
);
305 * @return the child or <code>null</node> if not found
306 * @see Node#getNode(String)
307 * @throws JcrException caused by {@link RepositoryException}
309 public static Node
getNode(Node node
, String child
) {
311 if (node
.hasNode(child
))
312 return node
.getNode(child
);
315 } catch (RepositoryException e
) {
316 throw new JcrException("Cannot get child of " + node
, e
);
321 * @return the node at this path or <code>null</node> if not found
322 * @see Session#getNode(String)
323 * @throws JcrException caused by {@link RepositoryException}
325 public static Node
getNode(Session session
, String path
) {
327 if (session
.nodeExists(path
))
328 return session
.getNode(path
);
331 } catch (RepositoryException e
) {
332 throw new JcrException("Cannot get node " + path
, e
);
337 * Add a node to this parent, setting its primary type and its mixins.
339 * @param parent the parent node
340 * @param name the name of the node, if <code>null</code>, the primary
341 * type will be used (typically for XML structures)
342 * @param primaryType the primary type, if <code>null</code>
343 * {@link NodeType#NT_UNSTRUCTURED} will be used.
344 * @param mixins the mixins
345 * @return the created node
346 * @see Node#addNode(String, String)
347 * @see Node#addMixin(String)
349 public static Node
addNode(Node parent
, String name
, String primaryType
, String
... mixins
) {
350 if (name
== null && primaryType
== null)
351 throw new IllegalArgumentException("Both node name and primary type cannot be null");
353 Node newNode
= parent
.addNode(name
== null ? primaryType
: name
,
354 primaryType
== null ? NodeType
.NT_UNSTRUCTURED
: primaryType
);
355 for (String mixin
: mixins
) {
356 newNode
.addMixin(mixin
);
359 } catch (RepositoryException e
) {
360 throw new JcrException("Cannot add node " + name
+ " to " + parent
, e
);
365 * Add an {@link NodeType#NT_BASE} node to this parent.
367 * @param parent the parent node
368 * @param name the name of the node, cannot be <code>null</code>
369 * @return the created node
371 * @see Node#addNode(String)
373 public static Node
addNode(Node parent
, String name
) {
375 throw new IllegalArgumentException("Node name cannot be null");
377 Node newNode
= parent
.addNode(name
);
379 } catch (RepositoryException e
) {
380 throw new JcrException("Cannot add node " + name
+ " to " + parent
, e
);
385 * Add mixins to a node.
387 * @param node the node
388 * @param mixins the mixins
389 * @return the created node
390 * @see Node#addMixin(String)
392 public static void addMixin(Node node
, String
... mixins
) {
394 for (String mixin
: mixins
) {
395 node
.addMixin(mixin
);
397 } catch (RepositoryException e
) {
398 throw new JcrException("Cannot add mixins " + Arrays
.asList(mixins
) + " to " + node
, e
);
407 public static void remove(Node node
) {
410 } catch (RepositoryException e
) {
411 throw new JcrException("Cannot remove node " + node
, e
);
416 * @return the node with htis id or <code>null</node> if not found
417 * @see Session#getNodeByIdentifier(String)
418 * @throws JcrException caused by {@link RepositoryException}
420 public static Node
getNodeById(Session session
, String id
) {
422 return session
.getNodeByIdentifier(id
);
423 } catch (ItemNotFoundException e
) {
425 } catch (RepositoryException e
) {
426 throw new JcrException("Cannot get node with id " + id
, e
);
431 * Set a property to the given value, or remove it if the value is
434 * @throws JcrException caused by {@link RepositoryException}
436 public static void set(Node node
, String property
, Object value
) {
438 if (!node
.hasProperty(property
)) {
440 if (value
instanceof List
) {// multiple
441 List
<?
> lst
= (List
<?
>) value
;
442 String
[] values
= new String
[lst
.size()];
443 for (int i
= 0; i
< lst
.size(); i
++) {
444 values
[i
] = lst
.get(i
).toString();
446 node
.setProperty(property
, values
);
448 node
.setProperty(property
, value
.toString());
453 Property prop
= node
.getProperty(property
);
460 if (value
instanceof List
) {
461 List
<?
> lst
= (List
<?
>) value
;
462 String
[] values
= new String
[lst
.size()];
464 for (int i
= 0; i
< lst
.size(); i
++) {
465 values
[i
] = lst
.get(i
).toString();
467 if (!prop
.isMultiple())
469 node
.setProperty(property
, values
);
474 if (prop
.isMultiple()) {
476 node
.setProperty(property
, value
.toString());
480 if (value
instanceof String
)
481 prop
.setValue((String
) value
);
482 else if (value
instanceof Long
)
483 prop
.setValue((Long
) value
);
484 else if (value
instanceof Integer
)
485 prop
.setValue(((Integer
) value
).longValue());
486 else if (value
instanceof Double
)
487 prop
.setValue((Double
) value
);
488 else if (value
instanceof Float
)
489 prop
.setValue(((Float
) value
).doubleValue());
490 else if (value
instanceof Calendar
)
491 prop
.setValue((Calendar
) value
);
492 else if (value
instanceof BigDecimal
)
493 prop
.setValue((BigDecimal
) value
);
494 else if (value
instanceof Boolean
)
495 prop
.setValue((Boolean
) value
);
496 else if (value
instanceof byte[])
497 JcrUtils
.setBinaryAsBytes(prop
, (byte[]) value
);
498 else if (value
instanceof Instant
) {
499 Instant instant
= (Instant
) value
;
500 GregorianCalendar calendar
= new GregorianCalendar();
501 calendar
.setTime(Date
.from(instant
));
502 prop
.setValue(calendar
);
503 } else // try with toString()
504 prop
.setValue(value
.toString());
505 } catch (RepositoryException e
) {
506 throw new JcrException("Cannot set property " + property
+ " of " + node
+ " to " + value
, e
);
511 * Get property as {@link String}.
513 * @return the value of
514 * {@link Node#getProperty(String)}.{@link Property#getString()} or
515 * <code>null</code> if the property does not exist.
516 * @throws JcrException caused by {@link RepositoryException}
518 public static String
get(Node node
, String property
) {
519 return get(node
, property
, null);
523 * Get property as a {@link String}. If the property is multiple it returns the
526 * @return the value of
527 * {@link Node#getProperty(String)}.{@link Property#getString()} or
528 * <code>defaultValue</code> if the property does not exist.
529 * @throws JcrException caused by {@link RepositoryException}
531 public static String
get(Node node
, String property
, String defaultValue
) {
533 if (node
.hasProperty(property
)) {
534 Property p
= node
.getProperty(property
);
536 return p
.getString();
538 Value
[] values
= p
.getValues();
539 if (values
.length
== 0)
542 return values
[0].getString();
546 } catch (RepositoryException e
) {
547 throw new JcrException("Cannot retrieve property " + property
+ " from " + node
, e
);
552 * Get property as a {@link Value}.
554 * @return {@link Node#getProperty(String)} or <code>null</code> if the property
556 * @throws JcrException caused by {@link RepositoryException}
558 public static Value
getValue(Node node
, String property
) {
560 if (node
.hasProperty(property
))
561 return node
.getProperty(property
).getValue();
564 } catch (RepositoryException e
) {
565 throw new JcrException("Cannot retrieve property " + property
+ " from " + node
, e
);
570 * Get property doing a best effort to cast it as the target object.
572 * @return the value of {@link Node#getProperty(String)} or
573 * <code>defaultValue</code> if the property does not exist.
574 * @throws IllegalArgumentException if the value could not be cast
575 * @throws JcrException in case of unexpected
576 * {@link RepositoryException}
578 @SuppressWarnings("unchecked")
579 public static <T
> T
getAs(Node node
, String property
, T defaultValue
) {
581 // TODO deal with multiple
582 if (node
.hasProperty(property
)) {
583 Property p
= node
.getProperty(property
);
585 if (p
.isMultiple()) {
586 throw new UnsupportedOperationException("Multiple values properties are not supported");
588 Value value
= p
.getValue();
589 return (T
) get(value
);
590 } catch (ClassCastException e
) {
591 throw new IllegalArgumentException(
592 "Cannot cast property of type " + PropertyType
.nameFromValue(p
.getType()), e
);
597 } catch (RepositoryException e
) {
598 throw new JcrException("Cannot retrieve property " + property
+ " from " + node
, e
);
602 public static <T
> T
getAs(Node node
, String property
, Class
<T
> clss
) {
603 if(String
.class.isAssignableFrom(clss
)) {
604 return (T
)get(node
,property
);
605 } else if(Long
.class.isAssignableFrom(clss
)) {
606 return (T
)get(node
,property
);
608 throw new IllegalArgumentException("Unsupported format "+clss
);
613 * Get a multiple property as a list, doing a best effort to cast it as the
616 * @return the value of {@link Node#getProperty(String)}.
617 * @throws IllegalArgumentException if the value could not be cast
618 * @throws JcrException in case of unexpected
619 * {@link RepositoryException}
621 public static <T
> List
<T
> getMultiple(Node node
, String property
) {
623 if (node
.hasProperty(property
)) {
624 Property p
= node
.getProperty(property
);
625 return getMultiple(p
);
629 } catch (RepositoryException e
) {
630 throw new JcrException("Cannot retrieve multiple values property " + property
+ " from " + node
, e
);
635 * Get a multiple property as a list, doing a best effort to cast it as the
638 @SuppressWarnings("unchecked")
639 public static <T
> List
<T
> getMultiple(Property p
) {
641 List
<T
> res
= new ArrayList
<>();
642 if (!p
.isMultiple()) {
643 res
.add((T
) get(p
.getValue()));
646 Value
[] values
= p
.getValues();
647 for (Value value
: values
) {
648 res
.add((T
) get(value
));
651 } catch (ClassCastException
| RepositoryException e
) {
652 throw new IllegalArgumentException("Cannot get property " + p
, e
);
656 /** Cast a {@link Value} to a standard Java object. */
657 public static Object
get(Value value
) {
658 Binary binary
= null;
660 switch (value
.getType()) {
661 case PropertyType
.STRING
:
662 return value
.getString();
663 case PropertyType
.DOUBLE
:
664 return (Double
) value
.getDouble();
665 case PropertyType
.LONG
:
666 return (Long
) value
.getLong();
667 case PropertyType
.BOOLEAN
:
668 return (Boolean
) value
.getBoolean();
669 case PropertyType
.DATE
:
670 return value
.getDate();
671 case PropertyType
.BINARY
:
672 binary
= value
.getBinary();
674 try (InputStream in
= binary
.getStream(); ByteArrayOutputStream out
= new ByteArrayOutputStream();) {
675 IOUtils
.copy(in
, out
);
676 arr
= out
.toByteArray();
677 } catch (IOException e
) {
678 throw new RuntimeException("Cannot read binary from " + value
, e
);
682 return value
.getString();
684 } catch (RepositoryException e
) {
685 throw new JcrException("Cannot cast value from " + value
, e
);
693 * Retrieves the {@link Session} related to this node.
695 * @deprecated Use {@link #getSession(Node)} instead.
698 public static Session
session(Node node
) {
699 return getSession(node
);
702 /** Retrieves the {@link Session} related to this node. */
703 public static Session
getSession(Node node
) {
705 return node
.getSession();
706 } catch (RepositoryException e
) {
707 throw new JcrException("Cannot retrieve session related to " + node
, e
);
711 /** Retrieves the root node related to this session. */
712 public static Node
getRootNode(Session session
) {
714 return session
.getRootNode();
715 } catch (RepositoryException e
) {
716 throw new JcrException("Cannot get root node for " + session
, e
);
720 /** Whether this item exists. */
721 public static boolean itemExists(Session session
, String path
) {
723 return session
.itemExists(path
);
724 } catch (RepositoryException e
) {
725 throw new JcrException("Cannot check whether " + path
+ " exists", e
);
730 * Saves the {@link Session} related to this node. Note that all other unrelated
731 * modifications in this session will also be saved.
733 public static void save(Node node
) {
735 Session session
= node
.getSession();
736 // if (node.isNodeType(NodeType.MIX_LAST_MODIFIED)) {
737 // set(node, Property.JCR_LAST_MODIFIED, Instant.now());
738 // set(node, Property.JCR_LAST_MODIFIED_BY, session.getUserID());
740 if (session
.hasPendingChanges())
742 } catch (RepositoryException e
) {
743 throw new JcrException("Cannot save session related to " + node
+ " in workspace "
744 + session(node
).getWorkspace().getName(), e
);
748 /** Login to a JCR repository. */
749 public static Session
login(Repository repository
, String workspace
) {
751 return repository
.login(workspace
);
752 } catch (RepositoryException e
) {
753 throw new IllegalArgumentException("Cannot login to repository", e
);
757 /** Safely and silently logs out a session. */
758 public static void logout(Session session
) {
761 if (session
.isLive())
763 } catch (Exception e
) {
768 /** Safely and silently logs out the underlying session. */
769 public static void logout(Node node
) {
770 Jcr
.logout(session(node
));
777 * Add a single privilege to a node.
781 public static void addPrivilege(Node node
, String principal
, String privilege
) {
783 Session session
= node
.getSession();
784 JcrUtils
.addPrivilege(session
, node
.getPath(), principal
, privilege
);
785 } catch (RepositoryException e
) {
786 throw new JcrException("Cannot add privilege " + privilege
+ " to " + node
, e
);
793 /** Get checked out status. */
794 public static boolean isCheckedOut(Node node
) {
796 return node
.isCheckedOut();
797 } catch (RepositoryException e
) {
798 throw new JcrException("Cannot retrieve checked out status of " + node
, e
);
802 /** @see VersionManager#checkpoint(String) */
803 public static void checkpoint(Node node
) {
805 versionManager(node
).checkpoint(node
.getPath());
806 } catch (RepositoryException e
) {
807 throw new JcrException("Cannot check in " + node
, e
);
811 /** @see VersionManager#checkin(String) */
812 public static void checkin(Node node
) {
814 versionManager(node
).checkin(node
.getPath());
815 } catch (RepositoryException e
) {
816 throw new JcrException("Cannot check in " + node
, e
);
820 /** @see VersionManager#checkout(String) */
821 public static void checkout(Node node
) {
823 versionManager(node
).checkout(node
.getPath());
824 } catch (RepositoryException e
) {
825 throw new JcrException("Cannot check out " + node
, e
);
829 /** Get the {@link VersionManager} related to this node. */
830 public static VersionManager
versionManager(Node node
) {
832 return node
.getSession().getWorkspace().getVersionManager();
833 } catch (RepositoryException e
) {
834 throw new JcrException("Cannot get version manager from " + node
, e
);
838 /** Get the {@link VersionHistory} related to this node. */
839 public static VersionHistory
getVersionHistory(Node node
) {
841 return versionManager(node
).getVersionHistory(node
.getPath());
842 } catch (RepositoryException e
) {
843 throw new JcrException("Cannot get version history from " + node
, e
);
848 * The linear versions of this version history in reverse order and without the
851 public static List
<Version
> getLinearVersions(VersionHistory versionHistory
) {
853 List
<Version
> lst
= new ArrayList
<>();
854 VersionIterator vit
= versionHistory
.getAllLinearVersions();
855 while (vit
.hasNext())
856 lst
.add(vit
.nextVersion());
858 Collections
.reverse(lst
);
860 } catch (RepositoryException e
) {
861 throw new JcrException("Cannot get linear versions from " + versionHistory
, e
);
865 /** The frozen node related to this {@link Version}. */
866 public static Node
getFrozenNode(Version version
) {
868 return version
.getFrozenNode();
869 } catch (RepositoryException e
) {
870 throw new JcrException("Cannot get frozen node from " + version
, e
);
874 /** Get the base {@link Version} related to this node. */
875 public static Version
getBaseVersion(Node node
) {
877 return versionManager(node
).getBaseVersion(node
.getPath());
878 } catch (RepositoryException e
) {
879 throw new JcrException("Cannot get base version from " + node
, e
);
887 * Returns the size of this file.
889 * @see NodeType#NT_FILE
891 public static long getFileSize(Node fileNode
) {
893 if (!fileNode
.isNodeType(NodeType
.NT_FILE
))
894 throw new IllegalArgumentException(fileNode
+ " must be a file.");
895 return getBinarySize(fileNode
.getNode(Node
.JCR_CONTENT
).getProperty(Property
.JCR_DATA
).getBinary());
896 } catch (RepositoryException e
) {
897 throw new JcrException("Cannot get file size of " + fileNode
, e
);
901 /** Returns the size of this {@link Binary}. */
902 public static long getBinarySize(Binary binaryArg
) {
904 try (Bin binary
= new Bin(binaryArg
)) {
905 return binary
.getSize();
907 } catch (RepositoryException e
) {
908 throw new JcrException("Cannot get file size of binary " + binaryArg
, e
);
913 /** Creates a JCR-SQL2 query using {@link MessageFormat}. */
914 public static Query
createQuery(QueryManager qm
, String sql
, Object
... args
) {
916 sql
= sql
.replaceAll("'", "''");
917 String query
= MessageFormat
.format(sql
, args
);
919 return qm
.createQuery(query
, Query
.JCR_SQL2
);
920 } catch (RepositoryException e
) {
921 throw new JcrException("Cannot create JCR-SQL2 query from " + query
, e
);
925 /** Executes a JCR-SQL2 query using {@link MessageFormat}. */
926 public static NodeIterator
executeQuery(QueryManager qm
, String sql
, Object
... args
) {
927 Query query
= createQuery(qm
, sql
, args
);
929 return query
.execute().getNodes();
930 } catch (RepositoryException e
) {
931 throw new JcrException("Cannot execute query " + sql
+ " with arguments " + Arrays
.asList(args
), e
);
935 /** Executes a JCR-SQL2 query using {@link MessageFormat}. */
936 public static NodeIterator
executeQuery(Session session
, String sql
, Object
... args
) {
937 QueryManager queryManager
;
939 queryManager
= session
.getWorkspace().getQueryManager();
940 } catch (RepositoryException e
) {
941 throw new JcrException("Cannot get query manager from session " + session
, e
);
943 return executeQuery(queryManager
, sql
, args
);
947 * Executes a JCR-SQL2 query using {@link MessageFormat}, which must return a
948 * single node at most.
950 * @return the node or <code>null</code> if not found.
952 public static Node
getNode(QueryManager qm
, String sql
, Object
... args
) {
953 NodeIterator nit
= executeQuery(qm
, sql
, args
);
955 Node node
= nit
.nextNode();
957 throw new IllegalStateException(
958 "Query " + sql
+ " with arguments " + Arrays
.asList(args
) + " returned more than one node.");
966 * Executes a JCR-SQL2 query using {@link MessageFormat}, which must return a
967 * single node at most.
969 * @return the node or <code>null</code> if not found.
971 public static Node
getNode(Session session
, String sql
, Object
... args
) {
972 QueryManager queryManager
;
974 queryManager
= session
.getWorkspace().getQueryManager();
975 } catch (RepositoryException e
) {
976 throw new JcrException("Cannot get query manager from session " + session
, e
);
978 return getNode(queryManager
, sql
, args
);