View Javadoc
1   /**
2    * This file Copyright (c) 2013-2014 Magnolia International
3    * Ltd.  (http://www.magnolia-cms.com). All rights reserved.
4    *
5    *
6    * This file is dual-licensed under both the Magnolia
7    * Network Agreement and the GNU General Public License.
8    * You may elect to use one or the other of these licenses.
9    *
10   * This file is distributed in the hope that it will be
11   * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
12   * implied warranty of MERCHANTABILITY or FITNESS FOR A
13   * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
14   * Redistribution, except as permitted by whichever of the GPL
15   * or MNA you select, is prohibited.
16   *
17   * 1. For the GPL license (GPL), you can redistribute and/or
18   * modify this file under the terms of the GNU General
19   * Public License, Version 3, as published by the Free Software
20   * Foundation.  You should have received a copy of the GNU
21   * General Public License, Version 3 along with this program;
22   * if not, write to the Free Software Foundation, Inc., 51
23   * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
24   *
25   * 2. For the Magnolia Network Agreement (MNA), this file
26   * and the accompanying materials are made available under the
27   * terms of the MNA which accompanies this distribution, and
28   * is available at http://www.magnolia-cms.com/mna.html
29   *
30   * Any modifications to this file must keep this entire header
31   * intact.
32   *
33   */
34  package info.magnolia.ui.vaadin.integration.jcr;
35  
36  import info.magnolia.context.MgnlContext;
37  
38  import java.util.ArrayList;
39  import java.util.List;
40  
41  import javax.jcr.Item;
42  import javax.jcr.ItemNotFoundException;
43  import javax.jcr.Node;
44  import javax.jcr.RepositoryException;
45  import javax.jcr.Session;
46  
47  import org.apache.commons.lang3.StringUtils;
48  import org.slf4j.Logger;
49  import org.slf4j.LoggerFactory;
50  
51  /**
52   * Utility methods for item ids used in the container.
53   * <p/>
54   * The format is:
55   * <ul>
56   *     <li>for nodes &lt;node identifier&gt;
57   *     <li>for properties &lt;node identifier&gt;@&lt;propertyName&gt;
58   * </ul>
59   */
60  public class JcrItemUtil {
61  
62      private static final Logger log = LoggerFactory.getLogger(JcrItemUtil.class);
63  
64      /**
65       * String separating property name and node identifier.
66       */
67      public static final String PROPERTY_NAME_AND_IDENTIFIER_SEPARATOR = "@";
68  
69      /**
70       * @return all chars in front of #PROPERTY_NAME_AND_IDENTIFIER_SEPARATOR - if it doesn't contain #PROPERTY_NAME_AND_IDENTIFIER_SEPARATOR the provided itemId (then we assume it's already a nodeId)
71       */
72      public static String parseNodeIdentifier(final String itemId) {
73          return isPropertyItemId(itemId) ? itemId.substring(0, itemId.indexOf(PROPERTY_NAME_AND_IDENTIFIER_SEPARATOR)) : itemId;
74      }
75  
76      public static String parsePropertyName(final String itemId) {
77          return itemId.substring(itemId.indexOf(PROPERTY_NAME_AND_IDENTIFIER_SEPARATOR) + 1);
78      }
79  
80      public static boolean isPropertyItemId(final String itemId) {
81          return itemId != null && itemId.contains(PROPERTY_NAME_AND_IDENTIFIER_SEPARATOR);
82      }
83  
84      /**
85       * Returns the JCR Item represented by the given itemId or returns null if it doesn't exist.
86       */
87      public static Item getJcrItem(final JcrItemId itemId) throws RepositoryException {
88          if (itemId == null) {
89              return null;
90          }
91          Node node;
92          String workspaceName = itemId.getWorkspace();
93          try {
94              node = MgnlContext.getJCRSession(workspaceName).getNodeByIdentifier(itemId.getUuid());
95          } catch (ItemNotFoundException e) {
96              log.debug("Couldn't find item with id {} in workspace {}.", itemId, workspaceName);
97              return null;
98          }
99  
100         if (!(itemId instanceof JcrPropertyItemId)) {
101             return node;
102         }
103 
104         final String propertyName = ((JcrPropertyItemId)itemId).getPropertyName();
105         if (node.hasProperty(propertyName)) {
106             return node.getProperty(propertyName);
107         }
108         return null;
109     }
110 
111     public static boolean itemExists(JcrItemId itemId) throws RepositoryException {
112         return getJcrItem(itemId) != null;
113     }
114 
115     public static JcrItemId getItemId(final Item jcrItem) throws RepositoryException {
116         if (jcrItem == null) {
117             return null;
118         }
119 
120         if (jcrItem.isNode()) {
121             return new JcrNodeItemId(((Node) jcrItem).getIdentifier(), jcrItem.getSession().getWorkspace().getName());
122         } else {
123             return new JcrPropertyItemId((jcrItem.getParent()).getIdentifier(), jcrItem.getSession().getWorkspace().getName(), jcrItem.getName());
124         }
125     }
126 
127     /**
128      * Returns the itemId for a node at the given path if it exists, otherwise returns null.
129      */
130     public static JcrItemId getItemId(final String workspaceName, final String absPath) throws RepositoryException {
131 
132         if (StringUtils.isEmpty(workspaceName) || StringUtils.isEmpty(absPath)) {
133             return null;
134         }
135 
136         Session session = MgnlContext.getJCRSession(workspaceName);
137         if (!session.nodeExists(absPath)) {
138             return null;
139         }
140 
141         return getItemId(session.getNode(absPath));
142     }
143 
144     public static List<Item> getJcrItems(List<JcrItemId> ids) {
145         // sanity check
146         List<Item> items = new ArrayList<Item>();
147         for (JcrItemId id : ids) {
148             Item item;
149             try {
150                 item = getJcrItem(id);
151                 if (item != null) {
152                     items.add(item);
153                 }
154             } catch (RepositoryException e) {
155                 log.debug("Cannot find item with id [{}] in workspace [{}].", id.getUuid(), id.getWorkspace());
156             } catch (IllegalArgumentException e1) {
157                 log.debug("Workspace [{}] is not initialized.", id.getWorkspace());
158             }
159         }
160         return items;
161     }
162 
163     public static String getItemPath(Item item) {
164         if (item == null) {
165             return null;
166         }
167         String path = "unknown";
168         try {
169             if (item.isNode()) {
170                 path = item.getPath();
171             } else {
172                 String parentPath = item.getParent().getPath();
173                 String name = item.getName();
174                 path = parentPath + PROPERTY_NAME_AND_IDENTIFIER_SEPARATOR + name;
175             }
176         } catch (RepositoryException re) {
177             log.error("Cannot get path for item: " + item);
178         }
179         return path;
180     }
181 
182 }